GENKEY: New command to generate a key without saving.
[pwmd.git] / src / commands.c
blob679d052793a4d579aa0c02a31c462117cd388d6c
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;
498 client->flags |= FLAG_NEW;
499 // data file disappeared. clear the cache entry.
500 cache_clear (NULL, client->filename, 1);
501 cdata = NULL;
503 else if (cdata && cdata->doc) // cached document
505 int reload = 0;
506 int defer = 0;
508 if (!rc && !(client->flags & FLAG_NEW))
510 rc = validate_checksum (client, client->filename, cdata, &crc,
511 &crclen);
512 if (rc == GPG_ERR_CHECKSUM)
514 rc = 0;
515 reload = 1;
519 if (!rc)
521 rc = cache_iscached (client->filename, &defer, 0, 0);
522 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
524 rc = 0;
525 reload = 2;
529 if (!rc && reload)
531 if (reload == 1)
532 log_write ("%s: %s", client->filename,
533 pwmd_strerror (GPG_ERR_CHECKSUM));
534 cache_clear (NULL, client->filename, 1);
535 cdata = NULL;
536 rc = crypto_decrypt (client, client->crypto);
538 #ifdef WITH_GNUTLS
539 else if (!rc)
541 if (client->thd->remote
542 && config_get_boolean (client->filename, "tcp_require_key")
543 && !(client->flags & FLAG_NEW))
544 rc = crypto_try_decrypt (client,
545 (client->flags & FLAG_NO_PINENTRY));
547 #endif
549 if (!rc && cdata)
551 client->crypto->plaintext = cdata->doc;
552 client->crypto->plaintext_size = cdata->size;
553 rc = cache_decrypt (client->crypto);
554 if (!rc)
556 cdata->doc = NULL;
557 cdata->size = 0;
558 strv_free (client->crypto->pubkey);
559 xfree (client->crypto->sigkey);
560 client->crypto->pubkey = strv_dup (cdata->pubkey);
561 client->crypto->sigkey = str_dup (cdata->sigkey);
562 cached = 1;
564 else
566 client->crypto->plaintext = NULL;
567 client->crypto->plaintext_size = 0;
571 else // existing file
573 cached = cdata != NULL;
574 rc = crypto_decrypt (client, client->crypto);
578 if (!rc)
580 rc = parse_xml (ctx, client->flags & FLAG_NEW);
581 if (!rc)
583 rc = cache_encrypt (client->crypto);
584 if (rc)
585 cache_clear (NULL, client->filename, 1);
586 else
588 int timeout = config_get_integer (client->filename,
589 "cache_timeout");
591 cache_free_data_once (cdata);
592 cdata = xcalloc (1, sizeof (struct cache_data_s));
593 cdata->doc = client->crypto->plaintext;
594 cdata->size = client->crypto->plaintext_size;
595 cdata->pubkey = strv_dup(client->crypto->pubkey);
596 cdata->sigkey = client->crypto->sigkey ? str_dup(client->crypto->sigkey) : NULL;
597 client->crypto->plaintext = NULL;
598 client->crypto->plaintext_size = 0;
600 if (cached) // wont increment the refcount
602 /* Prevent using another FD to update the checksum for a
603 * cached data file. The validity has already been
604 * verified. */
605 xfree (client->crc);
606 client->crc = xmalloc (crclen);
607 memcpy (client->crc, crc, crclen);
608 xfree (cdata->crc);
609 cdata->crc = xmalloc (crclen);
610 memcpy (cdata->crc, crc, crclen);
612 rc = cache_set_data (client->filename, cdata);
613 /* The cache entry may have been removed and cache_set_data()
614 * already sent STATUS_CACHE. */
615 if (!cache_iscached (client->filename, NULL, 0, 0))
616 rc = send_status (ctx, STATUS_CACHE, NULL);
618 else
619 rc = cache_add_file (client->filename, cdata, timeout);
624 pthread_cleanup_pop (1);
625 xfree (crc);
627 if (!rc && !(client->flags & FLAG_NEW) && !cached)
628 rc = update_checksum (client);
630 if (!rc)
632 client->flags |= FLAG_OPEN;
634 if (client->flags & FLAG_NEW)
635 rc = send_status (ctx, STATUS_NEWFILE, NULL);
637 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
638 rc = do_lock (client, 0);
641 if (rc)
643 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
645 if (client->flags & FLAG_NEW)
646 cache_clear (NULL, client->filename, 1);
648 crypto_free (client->crypto);
649 client->crypto = NULL;
650 client->flags &= ~FLAG_OPEN;
652 else
653 crypto_free_non_keys (client->crypto);
655 return send_error (ctx, rc);
658 /* If not the invoking_user or is an existing file, check that the list of user
659 * supplied key ID's are in the list of current key ID's obtained when
660 * decrypting the data file.
662 static gpg_error_t
663 permitted_to_save (struct client_s *client, const char **keys,
664 const char **value)
666 gpg_error_t rc = 0;
667 const char **v;
669 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
670 return 0;
672 rc = peer_is_invoker (client);
673 if (!rc)
674 return 0;
676 /* Empty match. */
677 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
678 return 0;
680 for (v = value; v && *v; v++)
682 const char **k, *pv = *v;
683 int match = 0;
685 if (*pv == '0' && *(pv+1) == 'x')
686 pv += 2;
688 for (k = keys; k && *k; k++)
690 const char *pk = *k;
692 if (*pk == '0' && *(pk+1) == 'x')
693 pk += 2;
695 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
696 if (rc)
697 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
699 if (!rc)
701 match = 1;
702 break;
706 if (!match)
707 return GPG_ERR_FORBIDDEN;
710 return rc;
713 /* Requires that the keyid be a fingerprint in 16 byte form. */
714 static gpg_error_t
715 parse_save_opt_keyid_common (struct client_s *client, const char **list,
716 const char *value, char ***dst)
718 gpg_error_t rc = 0;
719 char **keys = NULL;
721 if (value && *value)
723 keys = str_split (value, ",", 0);
724 if (!keys)
725 return GPG_ERR_ENOMEM;
728 rc = crypto_keyid_to_16b (keys);
729 if (!rc)
730 rc = permitted_to_save (client, list, (const char **)keys);
732 if (!rc)
733 *dst = keys;
734 else
735 strv_free (keys);
737 return rc;
740 static gpg_error_t
741 parse_save_opt_keyid (void *data, void *value)
743 struct client_s *client = data;
744 const char *str = value;
745 char **dst = NULL;
746 gpg_error_t rc;
748 rc = parse_save_opt_keyid_common (client,
749 (const char **)client->crypto->pubkey,
750 str, &dst);
751 if (rc)
752 return rc;
754 client->crypto->save.pubkey = dst;
755 return 0;
758 static gpg_error_t
759 parse_save_opt_sign_keyid (void *data, void *value)
761 struct client_s *client = data;
762 const char *str = value;
763 char **dst = NULL;
764 gpg_error_t rc;
765 char **tmp = NULL;
767 if (client->crypto->sigkey)
769 if (!strv_printf (&tmp, "%s", client->crypto->sigkey))
770 return GPG_ERR_ENOMEM;
773 rc = parse_save_opt_keyid_common (client, (const char **)tmp, str, &dst);
774 strv_free (tmp);
775 if (rc)
776 return rc;
778 if (!dst)
779 client->opts |= OPT_NO_SIGNER;
780 else
781 client->crypto->save.sigkey = str_dup (*dst);
783 strv_free (dst);
784 return 0;
787 static gpg_error_t
788 parse_save_opt_inquire (struct client_s *client, unsigned opt)
790 if (opt == OPT_INQUIRE && !(client->flags & FLAG_NEW))
792 gpg_error_t rc = peer_is_invoker (client);
794 if (rc)
795 return rc;
798 client->opts |= opt;
799 return 0;
802 static gpg_error_t
803 parse_save_opt_inquire_keyparam (void *data, void *value)
805 (void)value;
806 return parse_save_opt_inquire (data, OPT_INQUIRE);
809 static gpg_error_t
810 parse_save_opt_inquire_keyid (void *data, void *value)
812 (void)value;
813 return parse_save_opt_inquire (data, OPT_INQUIRE_KEYID);
816 static gpg_error_t
817 parse_save_opt_symmetric (void *data, void *value)
819 struct client_s *client = data;
821 (void)value;
822 client->opts |= OPT_SYMMETRIC;
823 return 0;
826 static gpg_error_t
827 parse_save_opt_userid (void *data, void *value)
829 struct client_s *client = data;
831 if (!(client->flags & FLAG_NEW))
833 gpg_error_t rc = peer_is_invoker (client);
835 if (rc)
836 return rc;
839 client->crypto->save.userid = str_dup (value);
840 return client->crypto->save.userid ? 0 : GPG_ERR_ENOMEM;
843 static gpg_error_t
844 parse_save_opt_algo (void *data, void *value)
846 struct client_s *client = data;
848 client->crypto->save.algo = str_dup (value);
849 return client->crypto->save.algo ? 0 : GPG_ERR_ENOMEM;
852 static gpg_error_t
853 parse_save_opt_expire (void *data, void *value)
855 struct client_s *client = data;
856 gpg_error_t rc = 0;
857 char *p = NULL;
858 unsigned long t;
860 errno = 0;
861 t = strtoul (value, &p, 10);
863 if (!errno && p && *p)
864 rc = GPG_ERR_INV_VALUE;
865 else if (t == ULONG_MAX)
866 rc = GPG_ERR_INV_VALUE;
867 else if (errno)
868 rc = gpg_error_from_syserror ();
869 else
870 client->crypto->save.expire = t;
872 return rc;
875 static gpg_error_t
876 parse_save_opt_no_passphrase (void *data, void *value)
878 struct client_s *client = data;
880 (void)value;
881 client->crypto->save.flags |= GPGME_CREATE_NOPASSWD;
882 return 0;
885 /* Tests that the keys in new_keys are also in old_keys. */
886 static gpg_error_t
887 compare_keys (char **new_keys, char **old_keys)
889 char **o;
891 if (!old_keys || !*old_keys)
892 return 0;
894 crypto_keyid_to_16b (new_keys);
896 for (o = old_keys; *o; o++)
898 char **n;
900 for (n = new_keys; *n; n++)
902 if (!strcmp (*n, *o))
903 break;
906 if (!*n)
907 return GPG_ERR_NOT_FOUND;
910 return 0;
913 static gpg_error_t
914 inquire_keyid (struct client_s *client, unsigned opt)
916 gpg_error_t rc;
917 unsigned char *result = NULL;
918 size_t len;
919 const char *s;
920 char ***orig;
921 char ***save;
923 if (opt == OPT_INQUIRE_KEYID)
925 s = "KEYID";
926 orig = &client->crypto->pubkey;
927 save = &client->crypto->save.pubkey;
930 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
931 if (!rc)
933 char **dst = NULL;
935 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
936 (char *)result, &dst);
937 if (!rc)
938 *save = dst;
941 xfree (result);
942 return rc;
945 /* The caching test of gpg-agent is both a blessing and a curse. When a key
946 * lookup in its cache fails it tries the last successful key to be unlocked.
947 * This prevents pwmd from successfully clearing a signing key since the
948 * previous key, which more than likely belongs to the same keypair as the
949 * encryption/decryption key, will have the passphrase cached and therefore the
950 * signing key also cached. So we need to clear both the signing and encryption
951 * keys to get the effect of requiring a passphrase when generating a new
952 * keypair for an existing data file, or when the "require_save_key"
953 * configuration parameter is set. The "require_save_key" parameter is mostly a
954 * failsafe of the gpg-agent option --ignore-cache-for-signing since
955 * some/most/all users may fail to set it.
957 static gpg_error_t
958 save_command (assuan_context_t ctx, char *line)
960 struct client_s *client = assuan_get_pointer (ctx);
961 struct cache_data_s *cdata = NULL;
962 gpg_error_t rc = 0, cached = 0;
963 int defer = 0;
964 struct argv_s *args[] = {
965 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
966 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
967 parse_save_opt_inquire_keyid },
968 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
969 parse_save_opt_sign_keyid},
970 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
971 parse_save_opt_inquire_keyparam },
972 &(struct argv_s) {"userid", OPTION_TYPE_ARG,
973 parse_save_opt_userid},
974 &(struct argv_s) {"expire", OPTION_TYPE_ARG,
975 parse_save_opt_expire},
976 &(struct argv_s) {"algo", OPTION_TYPE_ARG,
977 parse_save_opt_algo},
978 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
979 parse_save_opt_no_passphrase},
980 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
981 parse_save_opt_symmetric },
982 NULL
985 crypto_free_save (&client->crypto->save);
987 if (!(client->flags & FLAG_NEW))
989 rc = crypto_is_symmetric (client->filename);
990 if (!rc || rc == GPG_ERR_BAD_DATA)
992 if (!rc)
993 client->opts |= OPT_SYMMETRIC;
995 rc = 0; // PKI
999 if (rc)
1000 return send_error (ctx, rc);
1002 rc = parse_options (&line, args, client, 0);
1003 if (rc)
1004 return send_error (ctx, rc);
1007 if (config_get_boolean (client->filename, "require_save_key")
1008 || (client->opts & OPT_SYMMETRIC))
1009 client->opts |= OPT_ASK;
1011 rc = open_check_file (client->filename, NULL, NULL, 1);
1012 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
1014 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
1015 return send_error (ctx, rc);
1018 if (!rc)
1019 cached = rc = cache_iscached (client->filename, &defer, 0, 1);
1021 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1022 rc = 0;
1023 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1024 rc = 0;
1026 if (rc)
1027 return send_error (ctx, rc);
1029 /* Specifying both a recipient and symmetric encryption is an error. */
1030 if (client->opts & OPT_INQUIRE_KEYID && client->opts & OPT_SYMMETRIC)
1032 return send_error (ctx, GPG_ERR_CONFLICT);
1034 else if ((client->opts & OPT_INQUIRE || client->crypto->save.userid) && client->opts & OPT_SYMMETRIC)
1036 return send_error (ctx, GPG_ERR_CONFLICT);
1038 /* Existing file with a recipient and wanting symmetric is an error. */
1039 else if (client->opts & OPT_SYMMETRIC && client->crypto->save.pubkey)
1041 return send_error (ctx, GPG_ERR_CONFLICT);
1043 else if (client->opts & OPT_INQUIRE_KEYID)
1045 if ((client->opts & OPT_INQUIRE) || (client->crypto->save.userid))
1046 return send_error (ctx, GPG_ERR_CONFLICT);
1048 if (client->opts & OPT_INQUIRE_KEYID)
1049 rc = inquire_keyid (client, OPT_INQUIRE_KEYID);
1051 else if ((client->crypto->save.pubkey || client->crypto->save.sigkey)
1052 && (client->opts & OPT_INQUIRE || client->crypto->save.userid))
1053 return send_error (ctx, GPG_ERR_CONFLICT);
1055 if (!rc)
1057 client->crypto->keyfile = config_get_string (client->filename,
1058 "passphrase_file");
1059 rc = crypto_init_ctx (client->crypto, (client->flags & FLAG_NO_PINENTRY),
1060 client->crypto->keyfile);
1063 if (!rc && (client->opts & OPT_INQUIRE || client->crypto->save.userid))
1065 /* Require a passphrase when generating a new key pair for an existing
1066 * file.
1068 if (!(client->flags & FLAG_NEW))
1070 rc = cache_clear_agent_keys (client->filename, 1, 1);
1071 if (!rc)
1073 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1074 client->opts &= ~OPT_ASK;
1078 if (!rc)
1080 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1082 if (client->crypto->save.userid)
1083 rc = crypto_genkey (client, client->crypto, NULL);
1084 else
1086 unsigned char *params = NULL;
1087 size_t len;
1089 rc = assuan_inquire (client->ctx, "KEYPARAM", &params, &len, 0);
1090 if (!rc)
1092 pthread_cleanup_push ((void *)xfree, params);
1093 rc = crypto_genkey (client, client->crypto, params);
1094 pthread_cleanup_pop (1);
1099 else if (!rc && (client->flags & FLAG_NEW))
1101 if (!client->crypto->save.pubkey && !client->crypto->save.sigkey
1102 && !(client->opts & OPT_SYMMETRIC))
1104 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1106 if (client->crypto->save.userid)
1107 rc = crypto_genkey (client, client->crypto, NULL);
1108 else
1110 char *params = crypto_default_key_params ();
1112 if (!params)
1113 rc = GPG_ERR_ENOMEM;
1115 if (!rc)
1117 pthread_cleanup_push ((void *)xfree, params);
1118 rc = crypto_genkey (client, client->crypto,
1119 (unsigned char *)params);
1120 pthread_cleanup_pop (1);
1124 else
1126 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1127 && !(client->opts & OPT_SYMMETRIC))
1128 rc = GPG_ERR_NO_PUBKEY;
1131 else if (!rc)
1133 cdata = cache_get_data (client->filename);
1134 if (cdata)
1136 if (client->crypto->save.pubkey)
1137 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1139 /* Always allow a signer for symmetric data files. */
1140 if (!rc && client->crypto->save.sigkey
1141 && !(client->opts & OPT_SYMMETRIC))
1142 rc = !strcmp (client->crypto->save.sigkey, cdata->sigkey)
1143 ? 0 : GPG_ERR_NOT_FOUND;
1145 /* Prevent saving to a recipient who is not in the original recipient
1146 * list without a passphrase. */
1147 if (rc || (client->crypto->sigkey && client->opts & OPT_NO_SIGNER))
1148 client->opts |= OPT_ASK;
1150 if (rc == GPG_ERR_NOT_FOUND)
1152 rc = peer_is_invoker (client);
1153 if (rc == GPG_ERR_EACCES)
1154 rc = GPG_ERR_FORBIDDEN;
1157 if (!client->crypto->save.pubkey
1158 && !(client->opts & OPT_SYMMETRIC))
1159 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1161 if (!rc && !client->crypto->save.sigkey && cdata->sigkey
1162 && !(client->opts & OPT_NO_SIGNER))
1163 client->crypto->save.sigkey = str_dup (cdata->sigkey);
1164 else if (!rc && !client->crypto->save.sigkey
1165 && (client->opts & OPT_NO_SIGNER)
1166 && !(client->opts & OPT_SYMMETRIC))
1167 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1169 else
1171 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1172 client->crypto->save.sigkey = str_dup (client->crypto->sigkey);
1176 if (!rc && !(client->flags & FLAG_NEW))
1178 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1179 if (client->opts & OPT_SYMMETRIC)
1180 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1182 if (client->opts & OPT_ASK)
1184 rc = cache_clear_agent_keys (client->filename, 1, 1);
1185 if (!rc)
1186 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1190 if (!rc && client->opts & OPT_SYMMETRIC)
1191 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1193 if (!rc)
1194 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1196 if (!rc)
1198 int size;
1200 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1202 if (size > 0)
1203 client->crypto->plaintext_size = (size_t) size;
1204 else
1205 rc = GPG_ERR_ENOMEM;
1207 if (!rc)
1209 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1210 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1211 client->crypto->flags |= !(client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_PASSWD_SIGN : 0;
1212 rc = crypto_encrypt (client, client->crypto);
1213 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1216 if (!rc)
1218 rc = crypto_write_file (client->crypto);
1219 if (!rc)
1221 if (!cached) // no error
1222 cdata = cache_get_data (client->filename);
1225 if (!rc)
1227 rc = cache_encrypt (client->crypto);
1228 if (rc)
1230 cache_clear (NULL, client->filename, 1);
1231 strv_free (client->crypto->pubkey);
1232 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1233 xfree (client->crypto->sigkey);
1234 client->crypto->sigkey = str_dup (client->crypto->save.sigkey);
1235 client->flags &= ~(FLAG_NEW);
1239 if (!rc)
1241 int timeout = config_get_integer (client->filename,
1242 "cache_timeout");
1244 cache_free_data_once (cdata);
1245 cdata = xcalloc (1, sizeof (struct cache_data_s));
1246 cdata->doc = client->crypto->plaintext;
1247 client->crypto->plaintext = NULL;
1248 cdata->size = client->crypto->plaintext_size;
1249 client->crypto->plaintext_size = 0;
1250 cdata->pubkey = client->crypto->save.pubkey;
1251 client->crypto->save.pubkey = NULL;
1252 cdata->sigkey = client->crypto->save.sigkey;
1253 client->crypto->save.sigkey = NULL;
1255 /* Update in case the cache entry expires the next SAVE may not
1256 * have any known keys. */
1257 strv_free (client->crypto->pubkey);
1258 client->crypto->pubkey = strv_dup (cdata->pubkey);
1259 xfree (client->crypto->sigkey);
1260 client->crypto->sigkey = NULL;
1261 if (cdata->sigkey)
1262 client->crypto->sigkey = str_dup (cdata->sigkey);
1264 if (!cached) // no error and wont increment refcount
1265 rc = cache_set_data (client->filename, cdata);
1266 else
1267 rc = cache_add_file (client->filename, cdata, timeout);
1269 if (!rc && (cached || (client->flags & FLAG_NEW)))
1270 send_status_all (STATUS_CACHE, NULL);
1272 if (!rc)
1274 rc = update_checksum (client);
1275 client->flags &= ~(FLAG_NEW);
1281 crypto_free_non_keys (client->crypto);
1282 return send_error (ctx, rc);
1285 static gpg_error_t
1286 parse_genkey_opt_usage (void *data, void *v)
1288 struct client_s *client = data;
1289 char *value = v;
1291 if (!value || !*value)
1292 return GPG_ERR_INV_VALUE;
1293 else if (!strcmp (value, "sign"))
1294 client->crypto->save.flags |= GPGME_CREATE_SIGN;
1295 else if (!strcmp (value, "encrypt"))
1296 client->crypto->save.flags |= GPGME_CREATE_ENCR;
1297 else if (!strcmp (value, "default"))
1298 client->crypto->save.flags &= ~(GPGME_CREATE_ENCR|GPGME_CREATE_SIGN);
1299 else
1300 return GPG_ERR_INV_VALUE;
1302 return 0;
1305 static gpg_error_t
1306 genkey_command (assuan_context_t ctx, char *line)
1308 struct client_s *client = assuan_get_pointer (ctx);
1309 struct crypto_s *crypto, *orig;
1310 gpg_error_t rc = 0;
1311 struct argv_s *args[] = {
1312 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
1313 parse_save_opt_inquire_keyparam },
1314 &(struct argv_s) {"userid", OPTION_TYPE_ARG,
1315 parse_save_opt_userid},
1316 &(struct argv_s) {"expire", OPTION_TYPE_ARG,
1317 parse_save_opt_expire},
1318 &(struct argv_s) {"algo", OPTION_TYPE_ARG,
1319 parse_save_opt_algo},
1320 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1321 parse_save_opt_no_passphrase},
1322 &(struct argv_s) {"usage", OPTION_TYPE_ARG,
1323 parse_genkey_opt_usage},
1324 NULL
1327 orig = client->crypto;
1328 rc = crypto_init (&crypto, ctx, client->filename,
1329 client->flags & FLAG_NO_PINENTRY, NULL);
1330 if (rc)
1331 return send_error (ctx, rc);
1333 client->crypto = crypto;
1334 rc = parse_options (&line, args, client, 0);
1335 if (rc)
1336 goto fail;
1338 if (!(client->opts & OPT_INQUIRE) && !client->crypto->save.userid)
1340 rc = GPG_ERR_SYNTAX;
1341 goto fail;
1344 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1346 if (client->crypto->save.userid)
1347 rc = crypto_genkey (client, client->crypto, NULL);
1348 else
1350 unsigned char *params = NULL;
1351 size_t len;
1353 rc = assuan_inquire (client->ctx, "KEYPARAM", &params, &len, 0);
1354 if (!rc)
1356 pthread_cleanup_push ((void *)xfree, params);
1357 rc = crypto_genkey (client, client->crypto, params);
1358 pthread_cleanup_pop (1);
1362 fail:
1363 crypto_free (crypto);
1364 client->crypto = orig;
1365 return send_error (ctx, rc);
1368 static gpg_error_t
1369 do_delete (assuan_context_t ctx, char *line)
1371 struct client_s *client = assuan_get_pointer (ctx);
1372 struct xml_request_s *req;
1373 xmlNodePtr n;
1374 gpg_error_t rc;
1376 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1377 if (rc)
1378 return rc;
1380 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1381 xml_free_request (req);
1382 if (rc)
1383 return rc;
1385 rc = xml_is_element_owner (client, n);
1386 if (!rc)
1387 rc = xml_unlink_node (client, n);
1389 return rc;
1392 static gpg_error_t
1393 delete_command (assuan_context_t ctx, char *line)
1395 struct client_s *client = assuan_get_pointer (ctx);
1396 gpg_error_t rc;
1397 struct argv_s *args[] = {
1398 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1399 NULL
1402 rc = parse_options (&line, args, client, 1);
1403 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1404 rc = GPG_ERR_SYNTAX;
1405 if (rc)
1406 return send_error (ctx, rc);
1408 if (client->opts & OPT_INQUIRE)
1410 unsigned char *result;
1411 size_t len;
1413 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1414 if (rc)
1415 return send_error (ctx, rc);
1417 pthread_cleanup_push ((void *)xfree, result);
1418 rc = do_delete (ctx, (char *)result);
1419 pthread_cleanup_pop (1);
1421 else
1422 rc = do_delete (ctx, line);
1424 return send_error (ctx, rc);
1427 static gpg_error_t
1428 update_element_expirey (struct client_s *client, xmlNodePtr n)
1430 gpg_error_t rc = 0;
1431 xmlChar *expire, *incr;
1432 char *p;
1433 time_t e, e_orig, i;
1434 time_t now = time (NULL);
1436 expire = xml_attribute_value (n, (xmlChar *)"expire");
1437 if (!expire)
1438 return 0;
1440 errno = 0;
1441 e = strtoul ((char *)expire, &p, 10);
1442 if (errno || *p || e == ULONG_MAX || *expire == '-')
1444 xmlFree (expire);
1445 rc = GPG_ERR_ERANGE;
1446 goto fail;
1449 xmlFree (expire);
1450 incr = xml_attribute_value (n, (xmlChar *)"expire_increment");
1451 if (!incr)
1452 return 0;
1454 i = strtoul ((char *)incr, &p, 10);
1455 if (errno || *p || i == ULONG_MAX || *incr == '-')
1457 xmlFree (incr);
1458 rc = GPG_ERR_ERANGE;
1459 goto fail;
1462 xmlFree (incr);
1463 e_orig = e;
1464 e = now + i;
1465 p = str_asprintf ("%lu", e);
1466 if (!p)
1468 rc = GPG_ERR_ENOMEM;
1469 goto fail;
1472 rc = xml_add_attribute (client, n, "expire", p);
1473 xfree (p);
1474 if (!rc)
1475 rc = send_status (client->ctx, STATUS_EXPIRE, "%lu %lu", e_orig, e);
1477 fail:
1478 return rc;
1481 static gpg_error_t
1482 store_command (assuan_context_t ctx, char *line)
1484 struct client_s *client = assuan_get_pointer (ctx);
1485 gpg_error_t rc;
1486 size_t len;
1487 unsigned char *result;
1488 xmlNodePtr n, parent;
1489 int has_content;
1490 char *content = NULL;
1491 struct xml_request_s *req;
1493 if (line && *line)
1494 return send_error (ctx, GPG_ERR_SYNTAX);
1496 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1497 if (rc)
1498 return send_error (ctx, rc);
1500 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1501 xfree (result);
1502 if (rc)
1503 return send_error (ctx, rc);
1505 /* Prevent passing the element content around to save some memory. */
1506 len = strv_length (req->args);
1507 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1508 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1510 xml_free_request (req);
1511 return send_error (ctx, GPG_ERR_INV_VALUE);
1514 if (has_content || !*req->args[len-1])
1516 has_content = 1;
1517 content = req->args[len-1];
1518 req->args[len-1] = NULL;
1521 if (strv_length (req->args) > 1)
1523 rc = xml_check_recursion (client, req);
1524 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1525 goto fail;
1528 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1530 if (!rc && len > 1)
1532 rc = xml_is_element_owner (client, parent);
1533 if (!rc)
1535 n = xml_find_text_node (parent->children);
1536 if (n)
1537 xmlNodeSetContent (n, (xmlChar *) content);
1538 else
1539 xmlNodeAddContent (parent, (xmlChar *) content);
1541 (void)xml_update_element_mtime (client, parent);
1542 (void)update_element_expirey (client, parent);
1546 fail:
1547 xfree (content);
1548 xml_free_request (req);
1549 return send_error (ctx, rc);
1552 static gpg_error_t
1553 xfer_data (assuan_context_t ctx, const char *line, int total)
1555 struct client_s *client = assuan_get_pointer (ctx);
1556 int to_send;
1557 int sent = 0;
1558 gpg_error_t rc = 0;
1559 int progress = config_get_integer ("global", "xfer_progress");
1560 int flush = 0;
1562 if (!(client->flags & FLAG_LOCK_CMD))
1563 rc = unlock_file_mutex (client, 0);
1564 if (rc && rc != GPG_ERR_NOT_LOCKED)
1565 return rc;
1567 progress =
1568 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1569 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1570 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1572 if (rc)
1573 return rc;
1575 again:
1578 if (sent + to_send > total)
1579 to_send = total - sent;
1581 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1582 flush ? 0 : to_send);
1583 if (!rc)
1585 sent += flush ? 0 : to_send;
1587 if ((progress && !(sent % progress) && sent != total) ||
1588 (sent == total && flush))
1589 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1591 if (!flush && !rc && sent == total)
1593 flush = 1;
1594 goto again;
1598 while (!rc && sent < total);
1600 return rc;
1603 static gpg_error_t
1604 do_get (assuan_context_t ctx, char *line)
1606 struct client_s *client = assuan_get_pointer (ctx);
1607 gpg_error_t rc;
1608 struct xml_request_s *req;
1609 xmlNodePtr n;
1611 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1612 if (rc)
1613 return rc;
1615 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1616 if (!rc)
1618 if (n && n->children)
1620 xmlNodePtr tmp = n;
1622 n = xml_find_text_node (n->children);
1623 if (!n || !n->content || !*n->content)
1624 rc = GPG_ERR_NO_DATA;
1625 else
1627 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1628 if (!rc)
1630 xmlChar *expire = xml_attribute_value (tmp,
1631 (xmlChar *)"expire");
1632 if (expire)
1634 time_t now = time (NULL);
1635 time_t e;
1636 char *p;
1638 errno = 0;
1639 e = strtoul ((char *)expire, &p, 10);
1640 if (errno || *p || e == ULONG_MAX || *expire == '-')
1641 log_write (_("invalid expire attribute value: %s"),
1642 expire);
1643 else if (now >= e)
1644 rc = send_status (ctx, STATUS_EXPIRE, "%lu 0", e);
1646 xmlFree (expire);
1651 else
1652 rc = GPG_ERR_NO_DATA;
1655 xml_free_request (req);
1656 return rc;
1659 static gpg_error_t
1660 get_command (assuan_context_t ctx, char *line)
1662 struct client_s *client = assuan_get_pointer (ctx);
1663 gpg_error_t rc;
1664 struct argv_s *args[] = {
1665 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1666 NULL
1669 rc = parse_options (&line, args, client, 1);
1670 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1671 rc = GPG_ERR_SYNTAX;
1672 if (rc)
1673 return send_error (ctx, rc);
1675 if (client->opts & OPT_INQUIRE)
1677 unsigned char *result;
1678 size_t len;
1680 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1681 if (rc)
1682 return send_error (ctx, rc);
1684 pthread_cleanup_push ((void *)xfree, result);
1685 rc = do_get (ctx, (char *)result);
1686 pthread_cleanup_pop (1);
1688 else
1689 rc = do_get (ctx, line);
1691 return send_error (ctx, rc);
1694 static void list_command_free1 (void *arg);
1695 static gpg_error_t
1696 realpath_command (assuan_context_t ctx, char *line)
1698 gpg_error_t rc;
1699 char **realpath = NULL;
1700 struct client_s *client = assuan_get_pointer (ctx);
1701 struct argv_s *args[] = {
1702 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1703 NULL
1706 rc = parse_options (&line, args, client, 1);
1707 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1708 rc = GPG_ERR_SYNTAX;
1709 if (rc)
1710 return send_error (ctx, rc);
1712 if (client->opts & OPT_INQUIRE)
1714 unsigned char *result;
1715 size_t len;
1717 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1718 if (rc)
1719 return send_error (ctx, rc);
1721 pthread_cleanup_push ((void *)xfree, result);
1722 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1723 pthread_cleanup_pop (1);
1725 else
1726 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1727 &realpath, &rc);
1729 if (!rc)
1731 char *tmp = strv_join ((char *)"\t", realpath);
1733 strv_free (realpath);
1734 if (!tmp)
1735 return send_error (ctx, GPG_ERR_ENOMEM);
1737 pthread_cleanup_push ((void *)xfree, tmp);
1738 rc = xfer_data (ctx, tmp, strlen (tmp));
1739 pthread_cleanup_pop (1);
1742 return send_error (ctx, rc);
1745 static void
1746 list_command_free1 (void *arg)
1748 if (arg)
1749 string_free ((struct string_s *) arg, 1);
1752 static gpg_error_t
1753 parse_list_opt_recurse (void *data, void *value)
1755 struct client_s *client = data;
1757 (void)value;
1758 client->opts |= OPT_LIST_RECURSE;
1759 return 0;
1762 static gpg_error_t
1763 parse_opt_verbose (void *data, void *value)
1765 struct client_s *client = data;
1767 (void)value;
1768 client->opts |= OPT_VERBOSE;
1769 return 0;
1772 static gpg_error_t
1773 list_path_once (struct client_s *client, char *line,
1774 struct element_list_s *elements, struct string_s *result)
1776 gpg_error_t rc;
1778 rc = xml_create_path_list (client, client->doc, NULL, elements, line, 0);
1779 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1780 rc = 0;
1782 if (!rc)
1784 int total = slist_length (elements->list);
1786 if (total)
1788 int i;
1790 for (i = 0; i < total; i++)
1792 char *tmp = slist_nth_data (elements->list, i);
1794 string_append_printf (result, "%s%s", tmp,
1795 i + 1 == total ? "" : "\n");
1798 else
1799 rc = GPG_ERR_NO_DATA;
1802 return rc;
1805 static gpg_error_t
1806 do_list (assuan_context_t ctx, char *line)
1808 struct client_s *client = assuan_get_pointer (ctx);
1809 gpg_error_t rc = GPG_ERR_NO_DATA;
1810 struct element_list_s *elements = NULL;
1812 if (!line || !*line)
1814 struct string_s *str = string_new (NULL);
1815 xmlNodePtr n;
1817 if (!str)
1818 return GPG_ERR_ENOMEM;
1820 pthread_cleanup_push ((void *)list_command_free1, str);
1821 n = xmlDocGetRootElement (client->doc);
1822 for (n = n->children; n; n = n->next)
1824 xmlChar *name;
1826 if (n->type != XML_ELEMENT_NODE)
1827 continue;
1829 name = xmlGetProp (n, (xmlChar *)"_name");
1830 if (!name)
1832 rc = GPG_ERR_ENOMEM;
1833 break;
1836 elements = xcalloc (1, sizeof (struct element_list_s));
1837 if (!elements)
1839 xmlFree (name);
1840 rc = GPG_ERR_ENOMEM;
1841 break;
1844 elements->prefix = string_new (NULL);
1845 if (!elements->prefix)
1847 xmlFree (name);
1848 xml_free_element_list (elements);
1849 rc = GPG_ERR_ENOMEM;
1850 break;
1853 elements->recurse = client->opts & OPT_LIST_RECURSE;
1854 elements->root_only = !elements->recurse;
1855 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1856 rc = list_path_once (client, (char *)name, elements, str);
1857 xmlFree (name);
1858 pthread_cleanup_pop (1);
1859 if (rc)
1860 break;
1862 if (n->next)
1863 string_append (str, "\n");
1866 if (!rc)
1867 rc = xfer_data (ctx, str->str, str->len);
1869 pthread_cleanup_pop (1);
1870 return rc;
1873 elements = xcalloc (1, sizeof (struct element_list_s));
1874 if (!elements)
1875 return GPG_ERR_ENOMEM;
1877 elements->prefix = string_new (NULL);
1878 if (!elements->prefix)
1880 xml_free_element_list (elements);
1881 return GPG_ERR_ENOMEM;
1884 elements->recurse = client->opts & OPT_LIST_RECURSE;
1885 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1886 struct string_s *str = string_new (NULL);
1887 pthread_cleanup_push ((void *)list_command_free1, str);
1888 rc = list_path_once (client, line, elements, str);
1889 if (!rc)
1890 rc = xfer_data (ctx, str->str, str->len);
1892 pthread_cleanup_pop (1);
1893 pthread_cleanup_pop (1);
1894 return rc;
1897 static gpg_error_t
1898 list_command (assuan_context_t ctx, char *line)
1900 struct client_s *client = assuan_get_pointer (ctx);
1901 gpg_error_t rc;
1902 struct argv_s *args[] = {
1903 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
1904 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1905 /* These are deprecated but kept for backward compatibility with older
1906 * clients. */
1907 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
1908 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
1909 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
1910 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
1911 NULL
1914 if (disable_list_and_dump == 1)
1915 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1917 rc = parse_options (&line, args, client, 1);
1918 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1919 rc = GPG_ERR_SYNTAX;
1920 if (rc)
1921 return send_error (ctx, rc);
1923 if (client->opts & OPT_INQUIRE)
1925 unsigned char *result;
1926 size_t len;
1928 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1929 if (rc)
1930 return send_error (ctx, rc);
1932 pthread_cleanup_push ((void *)xfree, result);
1933 rc = do_list (ctx, (char *)result);
1934 pthread_cleanup_pop (1);
1936 else
1937 rc = do_list (ctx, line);
1939 return send_error (ctx, rc);
1942 #define RESUMABLE_ERROR(rc) (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES \
1943 || rc == GPG_ERR_ELEMENT_NOT_FOUND || !rc)
1945 * args[0] - element path
1947 static gpg_error_t
1948 attribute_list (assuan_context_t ctx, char **args)
1950 struct client_s *client = assuan_get_pointer (ctx);
1951 char **attrlist = NULL;
1952 int i = 0;
1953 int target = 0;
1954 xmlAttrPtr a;
1955 xmlNodePtr n, an, r;
1956 char *line;
1957 gpg_error_t rc;
1958 struct xml_request_s *req;
1960 if (!args || !args[0] || !*args[0])
1961 return GPG_ERR_SYNTAX;
1963 rc = xml_new_request (client, args[0], XML_CMD_ATTR_LIST, &req);
1964 if (rc)
1965 return rc;
1967 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1968 xml_free_request (req);
1969 if (rc)
1970 return rc;
1972 again:
1973 for (a = n->properties; a; a = a->next)
1975 char **pa;
1977 if (target && xml_reserved_attribute ((char *)a->name))
1978 continue;
1980 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
1981 if (!pa)
1983 if (attrlist)
1984 strv_free (attrlist);
1986 log_write ("%s(%i): %s", __FILE__, __LINE__,
1987 pwmd_strerror (GPG_ERR_ENOMEM));
1988 return GPG_ERR_ENOMEM;
1991 attrlist = pa;
1992 an = a->children;
1993 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
1994 ? (char *)an->content : "");
1996 if (!attrlist[i])
1998 strv_free (attrlist);
1999 log_write ("%s(%i): %s", __FILE__, __LINE__,
2000 pwmd_strerror (GPG_ERR_ENOMEM));
2001 return GPG_ERR_ENOMEM;
2004 attrlist[++i] = NULL;
2007 if (!attrlist)
2008 return GPG_ERR_NO_DATA;
2010 if (!target)
2012 r = xml_resolve_path (client, client->doc, (xmlChar *)args[0], NULL, &rc);
2013 if (!RESUMABLE_ERROR (rc))
2015 strv_free (attrlist);
2016 return rc;
2018 else if (!rc && r != n)
2020 target = 1;
2021 n = r;
2022 goto again;
2025 rc = 0;
2028 line = strv_join ("\n", attrlist);
2029 if (!line)
2031 log_write ("%s(%i): %s", __FILE__, __LINE__,
2032 pwmd_strerror (GPG_ERR_ENOMEM));
2033 strv_free (attrlist);
2034 return GPG_ERR_ENOMEM;
2037 pthread_cleanup_push ((void *)xfree, line);
2038 pthread_cleanup_push ((void *)req_free, attrlist);
2039 rc = xfer_data (ctx, line, strlen (line));
2040 pthread_cleanup_pop (1);
2041 pthread_cleanup_pop (1);
2042 return rc;
2046 * args[0] - attribute
2047 * args[1] - element path
2049 static gpg_error_t
2050 attribute_delete (struct client_s *client, char **args)
2052 gpg_error_t rc;
2053 xmlNodePtr n;
2055 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2056 return GPG_ERR_SYNTAX;
2058 if (!strcmp (args[0], "_name") || !strcmp (args[0], "target"))
2059 return GPG_ERR_INV_ATTR;
2061 if (!xml_reserved_attribute (args[0]))
2062 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2063 else
2065 struct xml_request_s *req;
2067 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2068 if (rc)
2069 return rc;
2071 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2072 xml_free_request (req);
2075 if (!rc)
2076 rc = xml_is_element_owner (client, n);
2078 if (!rc)
2079 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
2081 return rc;
2085 * Creates the "target" attribute. When other commands encounter an element
2086 * with this attribute they follow the "target" after appending remaining
2087 * elements from the original element path to the target. The exception is the
2088 * ATTR command that operates on the element itself (for reserved attribute
2089 * names) and not the target.
2091 * If the source element path doesn't exist when using 'ATTR SET target', it is
2092 * created, but the destination element path must exist. This is simliar to the
2093 * ls(1) command: ln -s src dst.
2095 * args[0] - source element path
2096 * args[1] - destination element path
2098 static gpg_error_t
2099 set_target_attribute (struct client_s *client, char **args)
2101 struct xml_request_s *req = NULL;
2102 char **src, **dst;
2103 gpg_error_t rc;
2104 xmlNodePtr n;
2106 if (!args || !args[0] || !args[1])
2107 return GPG_ERR_SYNTAX;
2109 src = str_split (args[0], "\t", 0);
2110 if (!src)
2111 return GPG_ERR_SYNTAX;
2113 if (!xml_valid_element_path (src, 0))
2115 strv_free (src);
2116 return GPG_ERR_INV_VALUE;
2119 dst = str_split (args[1], "\t", 0);
2120 if (!dst)
2122 strv_free (src);
2123 return GPG_ERR_SYNTAX;
2126 // Be sure the destination element path exists. */
2127 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2128 if (rc)
2129 goto fail;
2131 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2132 if (rc && rc != GPG_ERR_EACCES)
2133 goto fail;
2135 xml_free_request (req);
2136 req = NULL;
2138 if (!strcmp (args[0], args[1]))
2140 rc = GPG_ERR_EEXIST;
2141 goto fail;
2144 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
2145 if (rc)
2146 goto fail;
2148 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2149 if (rc && rc != GPG_ERR_EACCES)
2150 goto fail;
2152 if (!rc)
2154 rc = xml_add_attribute (client, n, "target", args[1]);
2155 if (!rc)
2156 rc = xml_unlink_node (client, n->children);
2159 fail:
2160 strv_free (src);
2161 strv_free (dst);
2162 xml_free_request (req);
2163 return rc;
2167 * args[0] - attribute
2168 * args[1] - element path
2170 static gpg_error_t
2171 attribute_get (assuan_context_t ctx, char **args)
2173 struct client_s *client = assuan_get_pointer (ctx);
2174 xmlNodePtr n;
2175 xmlChar *a;
2176 gpg_error_t rc;
2177 struct xml_request_s *req;
2179 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2180 return GPG_ERR_SYNTAX;
2182 if (!xml_reserved_attribute (args[0]))
2183 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2184 else
2186 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2187 if (rc)
2188 return rc;
2190 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2191 xml_free_request (req);
2194 if (rc)
2195 return rc;
2197 a = xmlGetProp (n, (xmlChar *) args[0]);
2198 if (!a)
2199 return GPG_ERR_NOT_FOUND;
2201 pthread_cleanup_push ((void *)xmlFree, a);
2203 if (*a)
2204 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2205 else
2206 rc = GPG_ERR_NO_DATA;
2208 pthread_cleanup_pop (1);
2209 return rc;
2213 * args[0] - attribute
2214 * args[1] - element path
2215 * args[2] - value
2217 static gpg_error_t
2218 attribute_set (struct client_s *client, char **args)
2220 struct xml_request_s *req;
2221 gpg_error_t rc;
2222 xmlNodePtr n;
2224 if (!args || !args[0] || !args[1])
2225 return GPG_ERR_SYNTAX;
2228 * Reserved attribute names.
2230 if (!strcmp (args[0], "_name")) // Use the RENAME command instead
2231 return GPG_ERR_INV_ATTR;
2232 else if (!strcmp (args[0], "target"))
2233 return set_target_attribute (client, args + 1);
2234 else if (!xml_valid_attribute (args[0]))
2235 return GPG_ERR_INV_VALUE;
2237 if (!xml_valid_attribute_value (args[2]))
2238 return GPG_ERR_INV_VALUE;
2240 if (!xml_reserved_attribute (args[0]))
2242 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2243 if (!rc)
2245 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2246 if (!rc)
2248 rc = xml_check_recursion (client, req);
2249 xml_free_request (req);
2253 else
2255 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2256 if (rc)
2257 return rc;
2259 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2260 xml_free_request (req);
2263 if (!rc)
2264 rc = xml_is_element_owner (client, n);
2266 if (!rc)
2267 rc = xml_add_attribute (client, n, args[0], args[2]);
2269 return rc;
2273 * req[0] - command
2274 * req[1] - attribute name or element path if command is LIST
2275 * req[2] - element path
2276 * req[2] - element path or value
2279 static gpg_error_t
2280 do_attr (assuan_context_t ctx, char *line)
2282 struct client_s *client = assuan_get_pointer (ctx);
2283 gpg_error_t rc = 0;
2284 char **req;
2286 req = str_split (line, " ", 4);
2287 if (!req || !req[0] || !req[1])
2289 strv_free (req);
2290 return GPG_ERR_SYNTAX;
2293 pthread_cleanup_push ((void *)req_free, req);
2295 if (strcasecmp (req[0], "SET") == 0)
2296 rc = attribute_set (client, req + 1);
2297 else if (strcasecmp (req[0], "GET") == 0)
2298 rc = attribute_get (ctx, req + 1);
2299 else if (strcasecmp (req[0], "DELETE") == 0)
2300 rc = attribute_delete (client, req + 1);
2301 else if (strcasecmp (req[0], "LIST") == 0)
2302 rc = attribute_list (ctx, req + 1);
2303 else
2304 rc = GPG_ERR_SYNTAX;
2306 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2307 pthread_cleanup_pop (1);
2308 return rc;
2311 static gpg_error_t
2312 attr_command (assuan_context_t ctx, char *line)
2314 struct client_s *client = assuan_get_pointer (ctx);
2315 gpg_error_t rc;
2316 struct argv_s *args[] = {
2317 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2318 NULL
2321 rc = parse_options (&line, args, client, 1);
2322 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2323 rc = GPG_ERR_SYNTAX;
2324 if (rc)
2325 return send_error (ctx, rc);
2327 if (client->opts & OPT_INQUIRE)
2329 unsigned char *result;
2330 size_t len;
2332 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2333 if (rc)
2334 return send_error (ctx, rc);
2336 pthread_cleanup_push ((void *)xfree, result);
2337 rc = do_attr (ctx, (char *)result);
2338 pthread_cleanup_pop (1);
2340 else
2341 rc = do_attr (ctx, line);
2343 return send_error (ctx, rc);
2346 static gpg_error_t
2347 parse_iscached_opt_lock (void *data, void *value)
2349 struct client_s *client = data;
2351 (void) value;
2352 client->opts |= OPT_LOCK;
2353 return 0;
2356 static gpg_error_t
2357 parse_iscached_opt_agent (void *data, void *value)
2359 struct client_s *client = data;
2361 (void) value;
2362 client->opts |= OPT_CACHE_AGENT;
2363 return 0;
2366 static gpg_error_t
2367 parse_iscached_opt_sign (void *data, void *value)
2369 struct client_s *client = data;
2371 (void) value;
2372 client->opts |= OPT_CACHE_SIGN;
2373 return 0;
2376 static gpg_error_t
2377 iscached_command (assuan_context_t ctx, char *line)
2379 struct client_s *client = assuan_get_pointer (ctx);
2380 gpg_error_t rc;
2381 int defer = 0;
2382 struct argv_s *args[] = {
2383 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2384 &(struct argv_s) {"agent", OPTION_TYPE_NOARG, parse_iscached_opt_agent},
2385 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_iscached_opt_sign},
2386 NULL
2389 if (!line || !*line)
2390 return send_error (ctx, GPG_ERR_SYNTAX);
2392 rc = parse_options (&line, args, client, 1);
2393 if (rc)
2394 return send_error (ctx, rc);
2395 else if (!valid_filename (line))
2396 return send_error (ctx, GPG_ERR_INV_VALUE);
2398 if (!(client->flags & FLAG_OPEN)
2399 && ((client->opts & OPT_CACHE_AGENT) || (client->opts & OPT_CACHE_SIGN)))
2400 return send_error (ctx, GPG_ERR_INV_STATE);
2402 rc = cache_iscached (line, &defer, (client->opts & OPT_CACHE_AGENT),
2403 (client->opts & OPT_CACHE_SIGN));
2404 if (!rc && defer)
2405 rc = GPG_ERR_NO_DATA;
2407 if (!rc)
2409 struct cache_data_s *cdata = cache_get_data (line);
2411 if (cdata)
2413 rc = validate_checksum (client, line, cdata, NULL, NULL);
2414 if (rc == GPG_ERR_CHECKSUM)
2415 rc = GPG_ERR_NO_DATA;
2419 if (client->opts & OPT_LOCK
2420 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2422 gpg_error_t trc = rc;
2424 if (strcmp (line, client->filename))
2425 reset_client (client);
2427 xfree (client->filename);
2428 client->filename = str_dup (line);
2429 rc = do_lock (client, 1);
2430 if (!rc)
2431 rc = trc;
2434 return send_error (ctx, rc);
2437 static gpg_error_t
2438 clearcache_command (assuan_context_t ctx, char *line)
2440 struct client_s *client = assuan_get_pointer (ctx);
2441 gpg_error_t rc = 0, all_rc = 0;
2442 int i;
2443 int t;
2444 int all = 0;
2445 struct client_thread_s *once = NULL;
2446 unsigned count;
2448 cache_lock ();
2449 pthread_cleanup_push (cache_release_mutex, NULL);
2450 count = cache_file_count ();
2451 MUTEX_LOCK (&cn_mutex);
2452 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
2454 if (!line || !*line)
2455 all = 1;
2457 t = slist_length (cn_thread_list);
2459 for (i = 0; i < t; i++)
2461 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2462 assuan_peercred_t peer;
2464 if (!thd->cl)
2465 continue;
2467 /* Lock each connected clients' file mutex to prevent any other client
2468 * from accessing the cache entry (the file mutex is locked upon
2469 * command startup). The cache for the entry is not cleared if the
2470 * file mutex is locked by another client to prevent this function
2471 * from blocking. Rather, it returns an error.
2473 if (all)
2475 if (thd->cl->filename)
2477 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2478 /* The current client doesn't have permission to open the other
2479 * filename do to "access" configuration parameter in a filename
2480 * section. Since we are clearning all cache entries the error
2481 * will be returned later during cache_clear(). */
2482 if (rc)
2484 rc = 0;
2485 continue;
2488 else // Idle client without opened file?
2489 continue;
2491 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2492 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2494 /* The current client owns the lock. */
2495 if (pthread_equal (pthread_self (), thd->tid))
2496 rc = 0;
2497 else
2499 if (cache_iscached (thd->cl->filename, NULL, 0, 0)
2500 == GPG_ERR_NO_DATA)
2502 rc = 0;
2503 continue;
2506 /* The cache entry will be cleared when the other client
2507 * disconnects and cache_timer_thread() does its thing. */
2508 cache_defer_clear (thd->cl->filename);
2511 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2513 rc = 0;
2514 continue;
2517 if (!rc)
2519 rc = cache_clear (NULL, thd->cl->filename, 1);
2520 cache_unlock_mutex (thd->cl->filename, 0);
2523 if (rc)
2524 all_rc = rc;
2526 rc = 0;
2528 else
2530 /* A single data filename was specified. Lock only this data file
2531 * mutex and free the cache entry. */
2532 rc = do_validate_peer (ctx, line, &peer);
2533 if (rc == GPG_ERR_FORBIDDEN)
2534 rc = peer_is_invoker (client);
2536 if (rc == GPG_ERR_EACCES)
2537 rc = GPG_ERR_FORBIDDEN;
2539 if (!rc && thd->cl->filename && !strcmp (thd->cl->filename , line))
2541 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2542 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2544 /* The current client owns the lock. */
2545 if (pthread_equal (pthread_self (), thd->tid))
2546 rc = 0;
2549 if (!rc)
2551 once = thd;
2552 rc = cache_clear (NULL, thd->cl->filename, 1);
2553 cache_unlock_mutex (thd->cl->filename, 0);
2555 else
2556 cache_defer_clear (thd->cl->filename);
2558 /* Found a client with the opened file. The cache entry has been
2559 * either cleared (self) or defered to be cleared. */
2560 break;
2565 /* Only connected clients' cache entries have been cleared. Now clear any
2566 * remaining cache entries without clients but only if there wasn't an
2567 * error from above since this would defeat the locking check of the
2568 * remaining entries. */
2569 if (all && !all_rc && cache_file_count ())
2571 rc = cache_clear (client, NULL, 1);
2572 if (rc == GPG_ERR_EACCES)
2573 rc = GPG_ERR_FORBIDDEN;
2576 /* No clients are using the specified file. */
2577 else if (!all_rc && !rc && !once)
2578 rc = cache_clear (NULL, line, 1);
2580 /* Release the connection mutex. */
2581 pthread_cleanup_pop (1);
2583 if (!rc || (cache_file_count () && count != cache_file_count ()))
2584 send_status_all (STATUS_CACHE, NULL);
2586 /* Release the cache mutex. */
2587 pthread_cleanup_pop (1);
2589 /* One or more files were locked while clearing all cache entries. */
2590 if (all_rc)
2591 rc = all_rc;
2593 return send_error (ctx, rc);
2596 static gpg_error_t
2597 cachetimeout_command (assuan_context_t ctx, char *line)
2599 struct client_s *client = assuan_get_pointer (ctx);
2600 int timeout;
2601 char **req = str_split (line, " ", 0);
2602 char *p;
2603 gpg_error_t rc = 0;
2604 assuan_peercred_t peer;
2606 if (!req || !*req || !req[1])
2608 strv_free (req);
2609 return send_error (ctx, GPG_ERR_SYNTAX);
2612 errno = 0;
2613 timeout = (int) strtol (req[1], &p, 10);
2614 if (errno != 0 || *p || timeout < -1)
2616 strv_free (req);
2617 return send_error (ctx, GPG_ERR_SYNTAX);
2620 rc = do_validate_peer (ctx, req[0], &peer);
2621 if (rc == GPG_ERR_FORBIDDEN)
2623 rc = peer_is_invoker (client);
2624 if (rc == GPG_ERR_EACCES)
2625 rc = GPG_ERR_FORBIDDEN;
2628 if (!rc)
2630 rc = cache_set_timeout (req[0], timeout);
2631 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2633 rc = 0;
2634 MUTEX_LOCK (&rcfile_mutex);
2635 config_set_int_param (&global_config, req[0], "cache_timeout",
2636 req[1]);
2637 MUTEX_UNLOCK (&rcfile_mutex);
2641 strv_free (req);
2642 return send_error (ctx, rc);
2645 static gpg_error_t
2646 dump_command (assuan_context_t ctx, char *line)
2648 xmlChar *xml;
2649 int len;
2650 struct client_s *client = assuan_get_pointer (ctx);
2651 gpg_error_t rc;
2653 if (disable_list_and_dump == 1)
2654 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2656 if (line && *line)
2657 return send_error (ctx, GPG_ERR_SYNTAX);
2659 rc = peer_is_invoker(client);
2660 if (rc)
2661 return send_error (ctx, rc);
2663 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2665 if (!xml)
2667 log_write ("%s(%i): %s", __FILE__, __LINE__,
2668 pwmd_strerror (GPG_ERR_ENOMEM));
2669 return send_error (ctx, GPG_ERR_ENOMEM);
2672 pthread_cleanup_push ((void *)xmlFree, xml);
2673 rc = xfer_data (ctx, (char *) xml, len);
2674 pthread_cleanup_pop (1);
2675 return send_error (ctx, rc);
2678 static gpg_error_t
2679 getconfig_command (assuan_context_t ctx, char *line)
2681 struct client_s *client = assuan_get_pointer (ctx);
2682 gpg_error_t rc = 0;
2683 char filename[255] = { 0 }, param[747] = { 0 };
2684 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2686 if (!line || !*line)
2687 return send_error (ctx, GPG_ERR_SYNTAX);
2689 if (strchr (line, ' '))
2691 int ret = sscanf (line, " %254[^ ] %746c", filename, param);
2693 if (ret <= 0)
2694 return send_error (ctx, gpg_error_from_syserror());
2695 paramp = param;
2696 fp = filename;
2699 if (fp && !valid_filename (fp))
2700 return send_error (ctx, GPG_ERR_INV_VALUE);
2702 paramp = str_down (paramp);
2703 p = config_get_value (fp ? fp : "global", paramp);
2704 if (!p)
2705 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2707 tmp = expand_homedir (p);
2708 xfree (p);
2709 if (!tmp)
2711 log_write ("%s(%i): %s", __FILE__, __LINE__,
2712 pwmd_strerror (GPG_ERR_ENOMEM));
2713 return send_error (ctx, GPG_ERR_ENOMEM);
2716 p = tmp;
2717 pthread_cleanup_push ((void *)xfree, p);
2718 rc = xfer_data (ctx, p, strlen (p));
2719 pthread_cleanup_pop (1);
2720 return send_error (ctx, rc);
2723 struct xpath_s
2725 xmlXPathContextPtr xp;
2726 xmlXPathObjectPtr result;
2727 xmlBufferPtr buf;
2728 char **req;
2731 static void
2732 xpath_command_free (void *arg)
2734 struct xpath_s *xpath = arg;
2736 if (!xpath)
2737 return;
2739 req_free (xpath->req);
2741 if (xpath->buf)
2742 xmlBufferFree (xpath->buf);
2744 if (xpath->result)
2745 xmlXPathFreeObject (xpath->result);
2747 if (xpath->xp)
2748 xmlXPathFreeContext (xpath->xp);
2751 static gpg_error_t
2752 do_xpath (assuan_context_t ctx, char *line)
2754 gpg_error_t rc;
2755 struct client_s *client = assuan_get_pointer (ctx);
2756 struct xpath_s _x = { 0 };
2757 struct xpath_s *xpath = &_x;
2759 if (!line || !*line)
2760 return GPG_ERR_SYNTAX;
2762 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2764 if (strv_printf (&xpath->req, "%s", line) == 0)
2765 return GPG_ERR_ENOMEM;
2768 xpath->xp = xmlXPathNewContext (client->doc);
2769 if (!xpath->xp)
2771 rc = GPG_ERR_BAD_DATA;
2772 goto fail;
2775 xpath->result =
2776 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2777 if (!xpath->result)
2779 rc = GPG_ERR_BAD_DATA;
2780 goto fail;
2783 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2785 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2786 goto fail;
2789 rc = xml_recurse_xpath_nodeset (client, client->doc,
2790 xpath->result->nodesetval,
2791 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2792 NULL);
2793 if (rc)
2794 goto fail;
2795 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2797 rc = GPG_ERR_NO_DATA;
2798 goto fail;
2800 else if (xpath->req[1])
2802 rc = 0;
2803 goto fail;
2806 pthread_cleanup_push ((void *)xpath_command_free, &xpath);
2807 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2808 xmlBufferLength (xpath->buf));
2809 pthread_cleanup_pop (0);
2810 fail:
2811 xpath_command_free (xpath);
2812 return rc;
2815 static gpg_error_t
2816 xpath_command (assuan_context_t ctx, char *line)
2818 struct client_s *client = assuan_get_pointer (ctx);
2819 gpg_error_t rc;
2820 struct argv_s *args[] = {
2821 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2822 NULL
2825 if (disable_list_and_dump == 1)
2826 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2828 rc = peer_is_invoker(client);
2829 if (rc)
2830 return send_error (ctx, rc);
2832 rc = parse_options (&line, args, client, 1);
2833 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2834 rc = GPG_ERR_SYNTAX;
2835 if (rc)
2836 return send_error (ctx, rc);
2838 if (client->opts & OPT_INQUIRE)
2840 unsigned char *result;
2841 size_t len;
2843 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2844 if (rc)
2845 return send_error (ctx, rc);
2847 pthread_cleanup_push ((void *)xfree, result);
2848 rc = do_xpath (ctx, (char *)result);
2849 pthread_cleanup_pop (1);
2851 else
2852 rc = do_xpath (ctx, line);
2854 return send_error (ctx, rc);
2857 static gpg_error_t
2858 do_xpathattr (assuan_context_t ctx, char *line)
2860 struct client_s *client = assuan_get_pointer (ctx);
2861 gpg_error_t rc;
2862 char **req = NULL;
2863 int cmd = 0; //SET
2864 struct xpath_s _x = { 0 };
2865 struct xpath_s *xpath = &_x;
2867 if (!line || !*line)
2868 return GPG_ERR_SYNTAX;
2870 if ((req = str_split (line, " ", 3)) == NULL)
2871 return GPG_ERR_ENOMEM;
2873 if (!req[0])
2875 rc = GPG_ERR_SYNTAX;
2876 goto fail;
2879 if (!strcasecmp (req[0], "SET"))
2880 cmd = 0;
2881 else if (!strcasecmp (req[0], "DELETE"))
2882 cmd = 1;
2883 else
2885 rc = GPG_ERR_SYNTAX;
2886 goto fail;
2889 if (!req[1] || !req[2])
2891 rc = GPG_ERR_SYNTAX;
2892 goto fail;
2895 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2897 rc = GPG_ERR_ENOMEM;
2898 goto fail;
2901 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2903 rc = GPG_ERR_SYNTAX;
2904 goto fail;
2907 xpath->xp = xmlXPathNewContext (client->doc);
2908 if (!xpath->xp)
2910 rc = GPG_ERR_BAD_DATA;
2911 goto fail;
2914 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2915 if (!xpath->result)
2917 rc = GPG_ERR_BAD_DATA;
2918 goto fail;
2921 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2923 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2924 goto fail;
2927 rc = xml_recurse_xpath_nodeset (client, client->doc,
2928 xpath->result->nodesetval,
2929 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2930 (xmlChar *) req[1]);
2932 fail:
2933 xpath_command_free (xpath);
2934 strv_free (req);
2935 return rc;
2938 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2939 static gpg_error_t
2940 xpathattr_command (assuan_context_t ctx, char *line)
2942 struct client_s *client = assuan_get_pointer (ctx);
2943 gpg_error_t rc;
2944 struct argv_s *args[] = {
2945 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2946 NULL
2949 if (disable_list_and_dump == 1)
2950 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2952 rc = peer_is_invoker(client);
2953 if (rc)
2954 return send_error (ctx, rc);
2956 rc = parse_options (&line, args, client, 1);
2957 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2958 rc = GPG_ERR_SYNTAX;
2959 if (rc)
2960 return send_error (ctx, rc);
2962 if (client->opts & OPT_INQUIRE)
2964 unsigned char *result;
2965 size_t len;
2967 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2968 if (rc)
2969 return send_error (ctx, rc);
2971 pthread_cleanup_push ((void *)xfree, result);
2972 rc = do_xpathattr (ctx, (char *)result);
2973 pthread_cleanup_pop (1);
2975 else
2976 rc = do_xpathattr (ctx, line);
2978 return send_error (ctx, rc);
2981 static gpg_error_t
2982 do_import (struct client_s *client, const char *root_element,
2983 unsigned char *content)
2985 xmlDocPtr doc = NULL;
2986 xmlNodePtr n = NULL, root;
2987 gpg_error_t rc;
2988 struct string_s *str = NULL, *tstr = NULL;
2989 struct xml_request_s *req = NULL;
2991 if (!content || !*content)
2992 return GPG_ERR_SYNTAX;
2994 if (root_element)
2996 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
2997 if (rc)
2999 xfree (content);
3000 return rc;
3003 if (!xml_valid_element_path (req->args, 0))
3005 xml_free_request (req);
3006 xfree (content);
3007 return GPG_ERR_INV_VALUE;
3011 str = string_new_content ((char *)content);
3012 tstr = string_prepend (str, "<pwmd>");
3013 if (tstr)
3015 str = tstr;
3016 tstr = string_append (str, "</pwmd>");
3017 if (!tstr)
3018 rc = GPG_ERR_ENOMEM;
3020 else
3021 rc = GPG_ERR_ENOMEM;
3023 if (rc)
3024 goto fail;
3026 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3027 string_free (str, 1);
3028 if (!doc)
3030 rc = GPG_ERR_BAD_DATA;
3031 goto fail;
3034 root = xmlDocGetRootElement (doc);
3035 root = root->children;
3036 if (root->type != XML_ELEMENT_NODE)
3038 rc = GPG_ERR_BAD_DATA;
3039 goto fail;
3042 rc = xml_validate_import (client, root);
3043 if (rc)
3044 goto fail;
3046 if (req)
3048 /* Create the new specified root element path, if needed. */
3049 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3050 &rc);
3051 if (rc)
3052 goto fail;
3054 /* Overwrite the children of the specified root element path. */
3055 (void)xml_unlink_node (client, n->children);
3056 n->children = NULL;
3058 else
3059 n = xmlDocGetRootElement (client->doc);
3061 if (n)
3063 xmlNodePtr copy;
3064 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
3066 if (!name)
3067 rc = GPG_ERR_BAD_DATA;
3068 else if (!req)
3070 /* No --root argument passed. Overwrite the current documents' root
3071 * element matching the root element of the imported data. */
3072 xml_free_request (req);
3073 req = NULL;
3074 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
3075 xmlFree (name);
3076 if (!rc)
3078 xmlNodePtr tmp;
3080 tmp = xml_find_elements (client, req,
3081 xmlDocGetRootElement (req->doc), &rc);
3082 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3083 goto fail;
3085 if (!rc)
3086 (void)xml_unlink_node (client, tmp);
3088 rc = 0;
3092 if (!rc)
3094 copy = xmlCopyNodeList (root);
3095 if (!copy)
3096 rc = GPG_ERR_ENOMEM;
3097 else
3099 n = xmlAddChildList (n, copy);
3100 if (!n)
3101 rc = GPG_ERR_ENOMEM;
3106 if (!rc && n && n->parent)
3107 rc = xml_update_element_mtime (client, n->parent);
3109 fail:
3110 xml_free_request (req);
3112 if (doc)
3113 xmlFreeDoc (doc);
3115 return rc;
3118 static gpg_error_t
3119 parse_import_opt_root (void *data, void *value)
3121 struct client_s *client = data;
3123 client->import_root = str_dup (value);
3124 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3127 static gpg_error_t
3128 import_command (assuan_context_t ctx, char *line)
3130 gpg_error_t rc;
3131 struct client_s *client = assuan_get_pointer (ctx);
3132 unsigned char *result;
3133 size_t len;
3134 struct argv_s *args[] = {
3135 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3136 NULL
3139 xfree (client->import_root);
3140 client->import_root = NULL;
3141 rc = parse_options (&line, args, client, 0);
3142 if (rc)
3143 return send_error (ctx, rc);
3145 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3146 if (rc)
3148 xfree (client->import_root);
3149 client->import_root = NULL;
3150 return send_error (ctx, rc);
3153 rc = do_import (client, client->import_root, result);
3154 xfree (client->import_root);
3155 client->import_root = NULL;
3156 return send_error (ctx, rc);
3159 static gpg_error_t
3160 do_lock (struct client_s *client, int add)
3162 gpg_error_t rc = lock_file_mutex (client, add);
3164 if (!rc)
3165 client->flags |= FLAG_LOCK_CMD;
3167 return rc;
3170 static gpg_error_t
3171 lock_command (assuan_context_t ctx, char *line)
3173 struct client_s *client = assuan_get_pointer (ctx);
3174 gpg_error_t rc;
3176 if (line && *line)
3177 return send_error (ctx, GPG_ERR_SYNTAX);
3179 rc = do_lock (client, 0);
3180 return send_error (ctx, rc);
3183 static gpg_error_t
3184 unlock_command (assuan_context_t ctx, char *line)
3186 struct client_s *client = assuan_get_pointer (ctx);
3187 gpg_error_t rc;
3189 if (line && *line)
3190 return send_error (ctx, GPG_ERR_SYNTAX);
3192 rc = unlock_file_mutex (client, 0);
3193 return send_error (ctx, rc);
3196 static void
3197 get_set_env (const char *name, const char *value)
3199 if (value && *value)
3200 setenv (name, value, 1);
3201 else
3202 unsetenv (name);
3205 static gpg_error_t
3206 option_command (assuan_context_t ctx, char *line)
3208 struct client_s *client = assuan_get_pointer (ctx);
3209 gpg_error_t rc = 0;
3210 char namebuf[255] = { 0 };
3211 char *name = namebuf;
3212 char *value = NULL, *p, *tmp = NULL;
3214 p = strchr (line, '=');
3215 if (!p)
3217 strncpy (namebuf, line, sizeof(namebuf));
3218 namebuf[sizeof(namebuf)-1] = 0;
3220 else
3222 strncpy (namebuf, line, strlen (line)-strlen (p));
3223 namebuf[sizeof(namebuf)-1] = 0;
3224 value = p+1;
3227 log_write2 ("OPTION name='%s' value='%s'", name, value);
3229 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3231 long n = 0;
3233 if (value)
3235 n = strtol (value, &tmp, 10);
3236 if (tmp && *tmp)
3237 return send_error (ctx, GPG_ERR_INV_VALUE);
3240 client->lock_timeout = n;
3242 else if (strcasecmp (name, (char *) "client-state") == 0)
3244 long n = 0;
3246 if (value)
3248 n = strtol (value, &tmp, 10);
3249 if ((tmp && *tmp) || (n < 0 || n > 1))
3250 return send_error (ctx, GPG_ERR_INV_VALUE);
3251 client->client_state = n;
3253 else
3254 client->client_state = 0;
3256 else if (strcasecmp (name, (char *) "NAME") == 0)
3258 if (value && strchr (value, ' '))
3259 rc = GPG_ERR_INV_VALUE;
3260 else
3262 tmp = pthread_getspecific (thread_name_key);
3263 pthread_setspecific (thread_name_key, NULL);
3264 xfree (tmp);
3266 MUTEX_LOCK (&cn_mutex);
3267 xfree (client->thd->name);
3268 client->thd->name = NULL;
3269 if (value && *value)
3271 pthread_setspecific (thread_name_key, str_dup (value));
3272 client->thd->name = str_dup (value);
3274 MUTEX_UNLOCK (&cn_mutex);
3277 else if (strcasecmp (name, "disable-pinentry") == 0)
3279 int n = 1;
3281 if (value && *value)
3283 n = (int) strtol (value, &tmp, 10);
3284 if (*tmp || n < 0 || n > 1)
3285 return send_error (ctx, GPG_ERR_INV_VALUE);
3288 if (n)
3289 client->flags |= FLAG_NO_PINENTRY;
3290 else
3291 client->flags &= ~FLAG_NO_PINENTRY;
3293 else if (strcasecmp (name, "ttyname") == 0)
3295 get_set_env ("GPG_TTY", value);
3297 else if (strcasecmp (name, "ttytype") == 0)
3299 get_set_env ("TERM", value);
3301 else if (strcasecmp (name, "display") == 0)
3303 get_set_env ("DISPLAY", value);
3305 else if (strcasecmp (name, "lc_messages") == 0)
3308 else if (strcasecmp (name, "lc_ctype") == 0)
3311 else if (strcasecmp (name, "desc") == 0)
3314 else if (strcasecmp (name, "pinentry-timeout") == 0)
3317 else
3318 rc = GPG_ERR_UNKNOWN_OPTION;
3320 return send_error (ctx, rc);
3323 static gpg_error_t
3324 do_rename (assuan_context_t ctx, char *line)
3326 struct client_s *client = assuan_get_pointer (ctx);
3327 char **args, *p;
3328 xmlNodePtr src, dst;
3329 struct string_s *str = NULL, *tstr;
3330 struct xml_request_s *req;
3331 gpg_error_t rc;
3333 args = str_split (line, " ", 0);
3334 if (!args || strv_length (args) != 2)
3336 strv_free (args);
3337 return GPG_ERR_SYNTAX;
3340 if (!xml_valid_element ((xmlChar *) args[1]))
3342 strv_free (args);
3343 return GPG_ERR_INV_VALUE;
3346 rc = xml_new_request (client, args[0], XML_CMD_RENAME, &req);
3347 if (rc)
3349 strv_free (args);
3350 return rc;
3353 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3354 if (rc)
3355 goto fail;
3357 rc = xml_is_element_owner (client, src);
3358 if (rc)
3359 goto fail;
3361 xmlChar *a = xmlGetProp (src, (xmlChar *) "_name");
3362 if (!a)
3364 rc = GPG_ERR_ENOMEM;
3365 goto fail;
3368 /* To prevent unwanted effects:
3370 * <element _name="a"><element _name="b"/></element>
3372 * RENAME a<TAB>b b
3374 if (xmlStrEqual (a, (xmlChar *) args[1]))
3376 xmlFree (a);
3377 rc = GPG_ERR_EEXIST;
3378 goto fail;
3381 xmlFree (a);
3382 str = string_new (args[0]);
3383 if (!str)
3385 rc = GPG_ERR_ENOMEM;
3386 goto fail;
3389 p = strrchr (str->str, '\t');
3390 if (p)
3391 tstr = string_truncate (str, strlen (str->str)-strlen (p));
3392 else
3393 tstr = string_truncate (str, 0);
3395 if (!tstr)
3397 string_free (str, 1);
3398 rc = GPG_ERR_ENOMEM;
3399 goto fail;
3402 str = tstr;
3403 tstr = string_append_printf (str, "%s%s", str->len ? "\t" : "", args[1]);
3404 if (!tstr)
3406 string_free (str, 1);
3407 rc = GPG_ERR_ENOMEM;
3408 goto fail;
3411 str = tstr;
3412 xml_free_request (req);
3413 rc = xml_new_request (client, str->str, XML_CMD_RENAME, &req);
3414 string_free (str, 1);
3415 if (rc)
3417 req = NULL;
3418 goto fail;
3421 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3422 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3423 goto fail;
3425 rc = 0;
3427 /* Target may exist:
3429 * <element _name="a"/>
3430 * <element _name="b" target="a"/>
3432 * RENAME b a
3434 if (src == dst)
3436 rc = GPG_ERR_EEXIST;
3437 goto fail;
3440 if (dst)
3442 rc = xml_is_element_owner (client, dst);
3443 if (rc)
3444 goto fail;
3446 rc = xml_add_attribute (client, src, "_name", args[1]);
3447 if (!rc)
3448 xml_unlink_node (client, dst);
3450 else
3451 rc = xml_add_attribute (client, src, "_name", args[1]);
3453 fail:
3454 xml_free_request (req);
3455 strv_free (args);
3456 return rc;
3459 static gpg_error_t
3460 rename_command (assuan_context_t ctx, char *line)
3462 struct client_s *client = assuan_get_pointer (ctx);
3463 gpg_error_t rc;
3464 struct argv_s *args[] = {
3465 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3466 NULL
3469 rc = parse_options (&line, args, client, 1);
3470 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3471 rc = GPG_ERR_SYNTAX;
3472 if (rc)
3473 return send_error (ctx, rc);
3475 if (client->opts & OPT_INQUIRE)
3477 unsigned char *result;
3478 size_t len;
3480 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3481 if (rc)
3482 return send_error (ctx, rc);
3484 pthread_cleanup_push ((void *)xfree, result);
3485 rc = do_rename (ctx, (char *)result);
3486 pthread_cleanup_pop (1);
3488 else
3489 rc = do_rename (ctx, line);
3491 return send_error (ctx, rc);
3494 static gpg_error_t
3495 do_copy (assuan_context_t ctx, char *line)
3497 struct client_s *client = assuan_get_pointer (ctx);
3498 char **args, **targs;
3499 xmlNodePtr src, dst, tree = NULL;
3500 struct xml_request_s *req;
3501 gpg_error_t rc;
3503 args = str_split (line, " ", 0);
3504 if (!args || strv_length (args) != 2)
3506 strv_free (args);
3507 return GPG_ERR_SYNTAX;
3510 targs = str_split (args[1], "\t", 0);
3511 if (!targs)
3513 strv_free (args);
3514 return GPG_ERR_SYNTAX;
3517 if (!xml_valid_element_path (targs, 0))
3519 strv_free (args);
3520 strv_free (targs);
3521 return GPG_ERR_INV_VALUE;
3523 strv_free (targs);
3525 rc = xml_new_request (client, args[0], XML_CMD_NONE, &req);
3526 if (rc)
3528 strv_free (args);
3529 return rc;
3532 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3533 if (rc)
3534 goto fail;
3536 tree = xmlCopyNodeList (src);
3537 if (!tree)
3539 rc = GPG_ERR_ENOMEM;
3540 goto fail;
3543 xml_free_request (req);
3544 /* Create the destination element path if it does not exist. */
3545 rc = xml_new_request (client, args[1], XML_CMD_STORE, &req);
3546 if (rc)
3548 req = NULL;
3549 goto fail;
3552 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3553 if (rc)
3554 goto fail;
3556 rc = xml_is_element_owner (client, dst);
3557 if (rc)
3558 goto fail;
3560 rc = xml_validate_target (client, req->doc, args[1], src);
3561 if (rc || src == dst)
3563 rc = rc ? rc : GPG_ERR_EEXIST;
3564 goto fail;
3567 /* Merge any attributes from the src node to the initial dst node. */
3568 for (xmlAttrPtr attr = tree->properties; attr; attr = attr->next)
3570 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3571 continue;
3573 xmlAttrPtr a = xmlHasProp (dst, attr->name);
3574 if (a)
3575 xmlRemoveProp (a);
3577 xmlChar *tmp = xmlNodeGetContent (attr->children);
3578 xmlNewProp (dst, attr->name, tmp);
3579 xmlFree (tmp);
3580 /* Create the default attributes. */
3581 rc = xml_add_attribute (client, dst, NULL, NULL);
3584 xmlNodePtr n = dst->children;
3585 (void)xml_unlink_node (client, n);
3586 dst->children = NULL;
3588 if (tree->children)
3590 n = xmlCopyNodeList (tree->children);
3591 if (!n)
3593 rc = GPG_ERR_ENOMEM;
3594 goto fail;
3597 n = xmlAddChildList (dst, n);
3598 if (!n)
3600 rc = GPG_ERR_ENOMEM;
3601 goto fail;
3604 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc)
3605 == dst->parent ? dst : dst->parent);
3608 fail:
3609 if (tree)
3610 (void)xml_unlink_node (client, tree);
3612 xml_free_request (req);
3613 strv_free (args);
3614 return rc;
3617 static gpg_error_t
3618 copy_command (assuan_context_t ctx, char *line)
3620 struct client_s *client = assuan_get_pointer (ctx);
3621 gpg_error_t rc;
3622 struct argv_s *args[] = {
3623 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3624 NULL
3627 rc = parse_options (&line, args, client, 1);
3628 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3629 rc = GPG_ERR_SYNTAX;
3630 if (rc)
3631 return send_error (ctx, rc);
3633 if (client->opts & OPT_INQUIRE)
3635 unsigned char *result;
3636 size_t len;
3638 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3639 if (rc)
3640 return send_error (ctx, rc);
3642 pthread_cleanup_push ((void *)xfree, result);
3643 rc = do_copy (ctx, (char *)result);
3644 pthread_cleanup_pop (1);
3646 else
3647 rc = do_copy (ctx, line);
3649 return send_error (ctx, rc);
3652 static gpg_error_t
3653 do_move (assuan_context_t ctx, char *line)
3655 struct client_s *client = assuan_get_pointer (ctx);
3656 char **args;
3657 xmlNodePtr src, dst;
3658 struct xml_request_s *req;
3659 gpg_error_t rc;
3661 args = str_split (line, " ", 0);
3662 if (!args || strv_length (args) != 2)
3664 strv_free (args);
3665 return GPG_ERR_SYNTAX;
3668 if (*args[1])
3670 char **targs = str_split (args[1], "\t", 0);
3671 if (!targs)
3673 strv_free (args);
3674 return GPG_ERR_ENOMEM;
3677 if (!xml_valid_element_path (targs, 0))
3679 strv_free (targs);
3680 strv_free (args);
3681 return GPG_ERR_INV_VALUE;
3684 strv_free (targs);
3687 rc = xml_new_request (client, args[0], XML_CMD_MOVE, &req);
3688 if (rc)
3690 strv_free (args);
3691 return rc;
3694 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3695 if (rc)
3696 goto fail;
3698 rc = xml_is_element_owner (client, src);
3699 if (rc)
3700 goto fail;
3702 xml_free_request (req);
3703 req = NULL;
3704 if (*args[1])
3706 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
3707 if (rc)
3708 goto fail;
3710 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3711 &rc);
3713 else
3714 dst = xmlDocGetRootElement (client->doc);
3716 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3717 goto fail;
3719 rc = 0;
3721 for (xmlNodePtr n = dst; n; n = n->parent)
3723 if (n == src)
3725 rc = GPG_ERR_EEXIST;
3726 goto fail;
3730 if (dst)
3732 xmlChar *a = xml_attribute_value (src, (xmlChar *) "_name");
3733 xmlNodePtr dup = xml_find_element (client, dst->children, (char *) a, &rc);
3735 xmlFree (a);
3736 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3737 goto fail;
3739 rc = 0;
3741 if (dup)
3743 if (dup == src)
3745 rc = GPG_ERR_EEXIST;
3746 goto fail;
3749 if (dst == xmlDocGetRootElement (client->doc))
3751 xmlNodePtr n = src;
3752 int match = 0;
3754 while (n->parent && n->parent != dst)
3755 n = n->parent;
3757 a = xml_attribute_value (n, (xmlChar *) "_name");
3758 xmlChar *b = xml_attribute_value (src, (xmlChar *) "_name");
3760 if (xmlStrEqual (a, b))
3762 match = 1;
3763 xmlUnlinkNode (src);
3764 (void)xml_unlink_node (client, n);
3767 xmlFree (a);
3768 xmlFree (b);
3770 if (!match)
3771 (void)xml_unlink_node (client, dup);
3773 else
3774 xmlUnlinkNode (dup);
3778 if (!dst && *req->args)
3780 struct xml_request_s *nreq = NULL;
3781 xmlChar *name = xml_attribute_value (src, (xmlChar *) "_name");
3783 if (src->parent == xmlDocGetRootElement (client->doc)
3784 && !strcmp ((char *) name, *req->args))
3786 xmlFree (name);
3787 rc = GPG_ERR_EEXIST;
3788 goto fail;
3791 xmlFree (name);
3792 rc = xml_new_request (client, args[1], XML_CMD_STORE, &nreq);
3793 if (!rc)
3795 dst = xml_find_elements (client, nreq,
3796 xmlDocGetRootElement (nreq->doc), &rc);
3797 xml_free_request (nreq);
3800 if (rc)
3801 goto fail;
3804 xml_update_element_mtime (client, src->parent);
3805 xmlUnlinkNode (src);
3807 dst = xmlAddChildList (dst, src);
3808 if (!dst)
3809 rc = GPG_ERR_ENOMEM;
3810 else
3811 xml_update_element_mtime (client, dst->parent);
3813 fail:
3814 xml_free_request (req);
3815 strv_free (args);
3816 return rc;
3819 static gpg_error_t
3820 move_command (assuan_context_t ctx, char *line)
3822 struct client_s *client = assuan_get_pointer (ctx);
3823 gpg_error_t rc;
3824 struct argv_s *args[] = {
3825 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3826 NULL
3829 rc = parse_options (&line, args, client, 1);
3830 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3831 rc = GPG_ERR_SYNTAX;
3832 if (rc)
3833 return send_error (ctx, rc);
3835 if (client->opts & OPT_INQUIRE)
3837 unsigned char *result;
3838 size_t len;
3840 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3841 if (rc)
3842 return send_error (ctx, rc);
3844 pthread_cleanup_push ((void *)xfree, result);
3845 rc = do_move (ctx, (char *)result);
3846 pthread_cleanup_pop (1);
3848 else
3849 rc = do_move (ctx, line);
3851 return send_error (ctx, rc);
3854 static gpg_error_t
3855 ls_command (assuan_context_t ctx, char *line)
3857 gpg_error_t rc;
3858 char *tmp;
3859 char *dir;
3860 DIR *d;
3861 char *list = NULL;
3862 #ifdef HAVE_READDIR_R
3863 size_t len;
3864 struct dirent *cur = NULL, *p;
3865 #else
3866 struct dirent *cur = NULL;
3867 #endif
3869 if (line && *line)
3870 return send_error (ctx, GPG_ERR_SYNTAX);
3872 tmp = str_asprintf ("%s/data", homedir);
3873 dir = expand_homedir (tmp);
3874 xfree (tmp);
3875 if (!dir)
3876 return send_error (ctx, GPG_ERR_ENOMEM);
3878 d = opendir (dir);
3879 rc = gpg_error_from_errno (errno);
3881 if (!d)
3883 xfree (dir);
3884 return send_error (ctx, rc);
3887 #ifdef HAVE_READDIR_R
3888 len = offsetof (struct dirent, d_name) + pathconf (dir, _PC_NAME_MAX) + 1;
3889 p = xmalloc (len);
3890 if (!p)
3892 xfree (dir);
3893 closedir (d);
3894 return send_error (ctx, GPG_ERR_ENOMEM);
3896 pthread_cleanup_push (xfree, p);
3897 #endif
3899 pthread_cleanup_push ((void *)closedir, d);
3900 xfree (dir);
3901 rc = 0;
3903 #ifdef HAVE_READDIR_R
3904 while (!readdir_r (d, p, &cur) && cur)
3905 #else
3906 while ((cur = readdir (d)))
3907 #endif
3909 rc = open_check_file (cur->d_name, NULL, NULL, 1);
3910 if (rc)
3911 continue;
3913 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3914 if (!tmp)
3916 if (list)
3917 xfree (list);
3919 rc = GPG_ERR_ENOMEM;
3920 break;
3923 xfree (list);
3924 list = tmp;
3927 pthread_cleanup_pop (1); // closedir (d)
3928 #ifdef HAVE_READDIR_R
3929 pthread_cleanup_pop (1); // xfree (p)
3930 #endif
3932 if (rc)
3933 return send_error (ctx, rc);
3935 if (!list)
3936 return send_error (ctx, GPG_ERR_NO_DATA);
3938 list[strlen (list) - 1] = 0;
3939 pthread_cleanup_push (xfree, list);
3940 rc = xfer_data (ctx, list, strlen (list));
3941 pthread_cleanup_pop (1);
3942 return send_error (ctx, rc);
3945 static gpg_error_t
3946 bye_notify (assuan_context_t ctx, char *line)
3948 struct client_s *cl = assuan_get_pointer (ctx);
3949 gpg_error_t ret = 0;
3951 (void)line;
3952 update_client_state (cl, CLIENT_STATE_DISCON);
3954 #ifdef WITH_GNUTLS
3955 cl->disco = 1;
3956 if (cl->thd->remote)
3958 int rc;
3962 struct timeval tv = { 0, 50000 };
3964 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3965 if (rc == GNUTLS_E_AGAIN)
3966 select (0, NULL, NULL, NULL, &tv);
3968 while (rc == GNUTLS_E_AGAIN);
3970 #endif
3972 /* This will let assuan_process_next() return. */
3973 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
3975 cl->last_rc = gpg_error_from_errno (errno);
3976 ret = cl->last_rc;
3979 cl->last_rc = 0; // BYE command result
3980 return ret;
3983 static gpg_error_t
3984 reset_notify (assuan_context_t ctx, char *line)
3986 struct client_s *client = assuan_get_pointer (ctx);
3988 (void)line;
3989 if (client)
3990 reset_client (client);
3992 return 0;
3996 * This is called before every Assuan command.
3998 static gpg_error_t
3999 command_startup (assuan_context_t ctx, const char *name)
4001 struct client_s *client = assuan_get_pointer (ctx);
4002 gpg_error_t rc;
4003 struct command_table_s *cmd = NULL;
4005 log_write2 ("command='%s'", name);
4006 client->last_rc = client->opts = 0;
4008 for (int i = 0; command_table[i]; i++)
4010 if (!strcasecmp (name, command_table[i]->name))
4012 if (command_table[i]->ignore_startup)
4013 return 0;
4014 cmd = command_table[i];
4015 break;
4019 if (!cmd)
4020 return GPG_ERR_UNKNOWN_COMMAND;
4022 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4023 if (!rc)
4024 update_client_state (client, CLIENT_STATE_COMMAND);
4026 return rc;
4030 * This is called after every Assuan command.
4032 static void
4033 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4035 struct client_s *client = assuan_get_pointer (ctx);
4037 if (!(client->flags & FLAG_LOCK_CMD))
4038 unlock_file_mutex (client, 0);
4040 unlock_flock (&client->flock_fd);
4041 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4042 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
4043 #ifdef WITH_GNUTLS
4044 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4045 #endif
4046 if (client->thd->state != CLIENT_STATE_DISCON)
4047 update_client_state (client, CLIENT_STATE_IDLE);
4050 static gpg_error_t
4051 parse_help_opt_html (void *data, void *value)
4053 struct client_s *client = data;
4055 (void) value;
4056 client->opts |= OPT_HTML;
4057 return 0;
4060 static gpg_error_t
4061 help_command (assuan_context_t ctx, char *line)
4063 gpg_error_t rc;
4064 int i;
4065 struct client_s *client = assuan_get_pointer (ctx);
4066 struct argv_s *args[] = {
4067 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
4068 NULL
4071 rc = parse_options (&line, args, client, 1);
4072 if (rc)
4073 return send_error (ctx, rc);
4075 if (!line || !*line)
4077 char *tmp;
4078 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
4079 "For commands that take an element path as an argument, each element is "
4080 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4081 "@*@*COMMANDS:"));
4083 for (i = 0; command_table[i]; i++)
4085 if (!command_table[i]->help)
4086 continue;
4088 /* @npxref{} won't put a "See " or "see " in front of the command.
4089 * It's not a texinfo command but needed for --html. */
4090 tmp = str_asprintf ("%s %s%s%s", help,
4091 client->opts & OPT_HTML ? "@npxref{" : "",
4092 command_table[i]->name,
4093 client->opts & OPT_HTML ? "}" : "");
4094 xfree (help);
4095 help = tmp;
4098 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
4099 xfree (help);
4100 pthread_cleanup_push ((void *)xfree, tmp);
4101 rc = xfer_data (ctx, tmp, strlen (tmp));
4102 pthread_cleanup_pop (1);
4103 return send_error (ctx, rc);
4106 for (i = 0; command_table[i]; i++)
4108 if (!strcasecmp (line, command_table[i]->name))
4110 char *help, *tmp;
4112 if (!command_table[i]->help)
4113 break;
4115 help = strip_texi_and_wrap (command_table[i]->help,
4116 client->opts & OPT_HTML);
4117 tmp = str_asprintf ("%s%s",
4118 (client->opts & OPT_HTML) ? "" : _("Usage: "),
4119 help);
4120 xfree (help);
4121 pthread_cleanup_push ((void *)xfree, tmp);
4122 rc = xfer_data (ctx, tmp, strlen (tmp));
4123 pthread_cleanup_pop (1);
4124 return send_error (ctx, rc);
4128 return send_error (ctx, GPG_ERR_INV_NAME);
4131 static void
4132 new_command (const char *name, int ignore, int unlock, int flock_type,
4133 gpg_error_t (*handler) (assuan_context_t, char *),
4134 const char *help)
4136 int i = 0;
4137 struct command_table_s **tmp;
4139 if (command_table)
4140 for (i = 0; command_table[i]; i++);
4142 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4143 assert (tmp);
4144 command_table = tmp;
4145 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4146 command_table[i]->name = name;
4147 command_table[i]->handler = handler;
4148 command_table[i]->ignore_startup = ignore;
4149 command_table[i]->unlock = unlock;
4150 command_table[i]->flock_type = flock_type;
4151 command_table[i++]->help = help;
4152 command_table[i] = NULL;
4155 void
4156 deinit_commands ()
4158 int i;
4160 for (i = 0; command_table[i]; i++)
4161 xfree (command_table[i]);
4163 xfree (command_table);
4166 static int
4167 sort_commands (const void *arg1, const void *arg2)
4169 struct command_table_s *const *a = arg1;
4170 struct command_table_s *const *b = arg2;
4172 if (!*a || !*b)
4173 return 0;
4174 else if (*a && !*b)
4175 return 1;
4176 else if (!*a && *b)
4177 return -1;
4179 return strcmp ((*a)->name, (*b)->name);
4182 static gpg_error_t
4183 passwd_command (assuan_context_t ctx, char *line)
4185 struct client_s *client = assuan_get_pointer (ctx);
4186 gpg_error_t rc;
4188 (void)line;
4189 rc = peer_is_invoker (client);
4190 if (rc == GPG_ERR_EACCES)
4191 return send_error (ctx, GPG_ERR_FORBIDDEN);
4192 else if (rc)
4193 return send_error (ctx, rc);
4195 if (client->flags & FLAG_NEW)
4196 return send_error (ctx, GPG_ERR_INV_STATE);
4198 client->crypto->keyfile = config_get_string (client->filename,
4199 "passphrase_file");
4200 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY,
4201 client->crypto->keyfile);
4202 if (rc)
4203 return send_error (ctx, rc);
4205 if (!rc)
4206 rc = crypto_passwd (client, client->crypto);
4208 crypto_free_non_keys (client->crypto);
4209 return send_error (ctx, rc);
4212 static gpg_error_t
4213 parse_opt_data (void *data, void *value)
4215 struct client_s *client = data;
4217 (void) value;
4218 client->opts |= OPT_DATA;
4219 return 0;
4222 static gpg_error_t
4223 send_client_list (assuan_context_t ctx)
4225 struct client_s *client = assuan_get_pointer (ctx);
4226 gpg_error_t rc = 0;
4228 if (client->opts & OPT_VERBOSE)
4230 unsigned i, t;
4231 char **list = NULL;
4232 char *line;
4234 MUTEX_LOCK (&cn_mutex);
4235 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4236 t = slist_length (cn_thread_list);
4238 for (i = 0; i < t; i++)
4240 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4241 char *tmp;
4243 if (thd->state == CLIENT_STATE_UNKNOWN)
4244 continue;
4246 tmp = build_client_info_line (thd, 0);
4247 if (tmp)
4249 char **l = strv_cat (list, tmp);
4250 if (!l)
4251 rc = GPG_ERR_ENOMEM;
4252 else
4253 list = l;
4255 else
4256 rc = GPG_ERR_ENOMEM;
4258 if (rc)
4260 strv_free (list);
4261 break;
4265 pthread_cleanup_pop (1);
4266 if (rc)
4267 return rc;
4269 line = strv_join ("\n", list);
4270 strv_free (list);
4271 pthread_cleanup_push ((void *)xfree, line);
4272 rc = xfer_data (ctx, line, strlen (line));
4273 pthread_cleanup_pop (1);
4274 return rc;
4277 if (client->opts & OPT_DATA)
4279 char buf[ASSUAN_LINELENGTH];
4281 MUTEX_LOCK (&cn_mutex);
4282 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4283 MUTEX_UNLOCK (&cn_mutex);
4284 rc = xfer_data (ctx, buf, strlen (buf));
4286 else
4287 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4289 return rc;
4292 static gpg_error_t
4293 getinfo_command (assuan_context_t ctx, char *line)
4295 struct client_s *client = assuan_get_pointer (ctx);
4296 gpg_error_t rc;
4297 char buf[ASSUAN_LINELENGTH];
4298 struct argv_s *args[] = {
4299 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4300 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4301 NULL
4304 rc = parse_options (&line, args, client, 1);
4305 if (rc)
4306 return send_error (ctx, rc);
4308 if (!strcasecmp (line, "clients"))
4310 rc = send_client_list (ctx);
4312 else if (!strcasecmp (line, "cache"))
4314 if (client->opts & OPT_DATA)
4316 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4317 rc = xfer_data (ctx, buf, strlen (buf));
4319 else
4320 rc = send_status (ctx, STATUS_CACHE, NULL);
4322 else if (!strcasecmp (line, "pid"))
4324 pid_t pid = getpid ();
4326 snprintf (buf, sizeof (buf), "%u", pid);
4327 rc = xfer_data (ctx, buf, strlen (buf));
4329 else if (!strcasecmp (line, "version"))
4331 char *tmp = str_asprintf ("0x%06x %s", VERSION_HEX,
4332 #ifdef WITH_GNUTLS
4333 "GNUTLS "
4334 #endif
4335 #ifdef WITH_LIBACL
4336 "ACL "
4337 #endif
4338 "");
4339 pthread_cleanup_push (xfree, tmp);
4340 rc = xfer_data (ctx, tmp, strlen (tmp));
4341 pthread_cleanup_pop (1);
4343 else if (!strcasecmp (line, "last_error"))
4345 if (client->last_error)
4346 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4347 else
4348 rc = GPG_ERR_NO_DATA;
4350 else if (!strcasecmp (line, "user"))
4352 char *user = NULL;
4354 #ifdef WITH_GNUTLS
4355 if (client->thd->remote)
4356 user = str_asprintf ("#%s", client->thd->tls->fp);
4357 else
4358 user = get_username (client->thd->peer->uid);
4359 #else
4360 user = get_username (client->thd->peer->uid);
4361 #endif
4362 if (user)
4364 pthread_cleanup_push ((void *)xfree, user);
4365 rc = xfer_data (ctx, user, strlen (user));
4366 pthread_cleanup_pop (1);
4368 else
4369 rc = GPG_ERR_NO_DATA;
4371 else
4372 rc = gpg_error (GPG_ERR_SYNTAX);
4374 return send_error (ctx, rc);
4377 static gpg_error_t
4378 parse_listkeys_opt_secret_only (void *data, void *value)
4380 struct client_s *client = data;
4382 (void) value;
4383 client->opts |= OPT_SECRET_ONLY;
4384 return 0;
4387 static gpg_error_t
4388 parse_keyinfo_opt_learn (void *data, void *value)
4390 struct client_s *client = data;
4392 (void)value;
4393 client->opts |= OPT_KEYINFO_LEARN;
4394 return 0;
4397 static gpg_error_t
4398 keyinfo_command (assuan_context_t ctx, char *line)
4400 struct client_s *client = assuan_get_pointer (ctx);
4401 gpg_error_t rc = 0;
4402 char **keys = NULL, **p = NULL;
4403 int sym = 0;
4404 struct argv_s *args[] = {
4405 &(struct argv_s) {"learn", OPTION_TYPE_NOARG, parse_keyinfo_opt_learn},
4406 NULL
4409 rc = parse_options (&line, args, client, 0);
4410 if (rc)
4411 return send_error (ctx, rc);
4413 if (line && *line)
4414 return send_error (ctx, GPG_ERR_SYNTAX);
4416 if (!(client->flags & FLAG_OPEN))
4417 return send_error (ctx, GPG_ERR_INV_STATE);
4419 if (client->opts & OPT_KEYINFO_LEARN)
4421 rc = cache_agent_command ("LEARN");
4422 return send_error (ctx, rc);
4425 if (client->flags & FLAG_NEW)
4426 return send_error (ctx, GPG_ERR_NO_DATA);
4428 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
4429 if (rc)
4430 return send_error (ctx, rc);
4432 rc = crypto_is_symmetric (client->filename);
4433 unlock_flock (&client->flock_fd);
4434 if (!rc)
4435 sym = 1;
4436 else if (rc != GPG_ERR_BAD_DATA)
4437 return send_error (ctx, rc);
4439 rc = 0;
4440 if (!sym)
4442 p = strv_catv (keys, client->crypto->pubkey);
4443 if (!p)
4444 rc = GPG_ERR_ENOMEM;
4445 else
4446 keys = p;
4449 if (!rc && client->crypto->sigkey)
4451 if (!strv_printf (&keys, "S%s", client->crypto->sigkey))
4453 strv_free (keys);
4454 return send_error (ctx, GPG_ERR_ENOMEM);
4458 if (!rc)
4460 if (keys)
4462 line = strv_join ("\n", keys);
4463 strv_free (keys);
4464 pthread_cleanup_push ((void *)xfree, line);
4465 if (line)
4466 rc = xfer_data (ctx, line, strlen (line));
4467 else
4468 rc = GPG_ERR_ENOMEM;
4470 pthread_cleanup_pop (1);
4472 else
4473 rc = GPG_ERR_NO_DATA;
4475 else
4476 strv_free (keys);
4478 return send_error (ctx, rc);
4481 static gpg_error_t
4482 kill_command (assuan_context_t ctx, char *line)
4484 struct client_s *client = assuan_get_pointer (ctx);
4485 gpg_error_t rc;
4486 unsigned i, t;
4488 if (!line || !*line)
4489 return send_error (ctx, GPG_ERR_SYNTAX);
4491 MUTEX_LOCK (&cn_mutex);
4492 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4493 t = slist_length (cn_thread_list);
4494 rc = GPG_ERR_ESRCH;
4496 for (i = 0; i < t; i++)
4498 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4499 char *tmp = str_asprintf ("%p", thd->tid);
4501 if (strcmp (line, tmp))
4503 xfree (tmp);
4504 continue;
4507 xfree (tmp);
4508 rc = peer_is_invoker (client);
4509 if (!rc)
4511 #ifdef HAVE_PTHREAD_CANCEL
4512 pthread_cancel (thd->tid);
4513 #else
4514 pthread_kill (thd->tid, SIGUSR2);
4515 #endif
4516 break;
4518 else if (rc == GPG_ERR_EACCES)
4519 rc = GPG_ERR_FORBIDDEN;
4520 else if (rc)
4521 break;
4523 if (config_get_boolean ("global", "strict_kill"))
4524 break;
4526 #ifdef WITH_GNUTLS
4527 if (client->thd->remote && thd->remote)
4529 if (!thd->tls || !thd->tls->fp)
4531 rc = GPG_ERR_INV_STATE;
4532 break;
4534 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
4536 #ifdef HAVE_PTHREAD_CANCEL
4537 pthread_cancel (thd->tid);
4538 #else
4539 pthread_kill (thd->tid, SIGUSR2);
4540 #endif
4541 break;
4544 else if (!client->thd->remote && !thd->remote)
4545 #endif
4547 if (client->thd->peer->uid == thd->peer->uid)
4549 #ifdef HAVE_PTHREAD_CANCEL
4550 pthread_cancel (thd->tid);
4551 #else
4552 pthread_kill (thd->tid, SIGUSR2);
4553 #endif
4556 break;
4559 pthread_cleanup_pop (1);
4560 return send_error (ctx, rc);
4563 static gpg_error_t
4564 listkeys_command (assuan_context_t ctx, char *line)
4566 struct client_s *client = assuan_get_pointer (ctx);
4567 struct crypto_s *crypto = NULL;
4568 char **pattern = NULL;
4569 gpgme_key_t *keys = NULL;
4570 char **result = NULL;
4571 gpg_error_t rc;
4572 struct argv_s *args[] = {
4573 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG,
4574 parse_listkeys_opt_secret_only },
4575 NULL
4578 rc = parse_options (&line, args, client, 1);
4579 if (rc)
4580 return send_error (ctx, rc);
4582 rc = crypto_init (&crypto, client->ctx, client->filename,
4583 client->flags & FLAG_NO_PINENTRY, NULL);
4584 if (rc)
4585 return send_error (ctx, rc);
4587 pthread_cleanup_push ((void *)crypto_free, crypto);
4588 pattern = str_split (line, ",", 0);
4589 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
4590 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET_ONLY,
4591 &keys);
4592 pthread_cleanup_pop (1);
4593 pthread_cleanup_pop (1);
4594 if (!rc)
4596 int i;
4598 for (i = 0; keys[i]; i++)
4600 char *p = crypto_key_info (keys[i]);
4601 char **r;
4603 if (!p)
4605 rc = GPG_ERR_ENOMEM;
4606 break;
4609 r = strv_cat (result, p);
4610 if (!r)
4612 rc = GPG_ERR_ENOMEM;
4613 break;
4616 result = r;
4619 if (!i)
4620 rc = GPG_ERR_NO_DATA;
4622 crypto_free_key_list (keys);
4625 if (!rc)
4627 line = strv_join ("\n", result);
4628 strv_free (result);
4629 pthread_cleanup_push ((void *)xfree, line);
4630 if (!line)
4631 rc = GPG_ERR_ENOMEM;
4632 else
4633 rc = xfer_data (ctx, line, strlen (line));
4635 pthread_cleanup_pop (1);
4637 else
4638 strv_free (result);
4640 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
4641 || gpg_err_code (rc) == GPG_ERR_NO_SECKEY)
4642 rc = GPG_ERR_NO_DATA;
4644 return send_error (ctx, rc);
4647 void
4648 init_commands ()
4650 /* !BEGIN-HELP-TEXT!
4652 * This comment is used as a marker to generate the offline documentation
4653 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4654 * script to determine where commands begin and end.
4656 new_command("HELP", 1, 1, 0, help_command, _(
4657 "HELP [--html] [<COMMAND>]\n"
4658 "Show available commands or command specific help text."
4659 "@*@*"
4660 "The @option{--html} option will output the help text in HTML format."
4663 new_command("KILL", 1, 0, 0, kill_command, _(
4664 "KILL <thread_id>\n"
4665 "Terminates the client identified by @var{thread_id} and releases any file "
4666 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
4667 "for details about listing connected clients. An @code{invoking_user} "
4668 "(@pxref{Configuration}) may kill any client while others may only kill "
4669 "clients of the same @code{UID} or @abbr{TLS} fingerprint."
4672 new_command("LISTKEYS", 0, 0, 0, listkeys_command, _(
4673 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n"
4674 "Returns a new line separated list of key information matching a comma "
4675 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
4676 "specified, only keys matching @var{pattern} that also have a secret key "
4677 "available will be returned."
4680 new_command("KEYINFO", 1, 0, 0, keyinfo_command, _(
4681 "KEYINFO [--learn]\n"
4682 "Returns a new line separated list of key ID's that the currently opened "
4683 "data file has recipients and signers for. If the key is a signing key it "
4684 "will be prefixed with an @code{S}. If the file is a new one, or has no "
4685 "signers in the case of being symmetrically encrypted, the error code "
4686 "@code{GPG_ERR_NO_DATA} is returned."
4687 "@*@*"
4688 "When the @option{--learn} option is passed, keys on a smartcard will be "
4689 "imported."
4692 new_command("GETINFO", 1, 1, 0, getinfo_command, _(
4693 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4694 "Get server and other information. The information is returned via a status "
4695 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
4696 "is specified."
4697 "@*@*"
4698 "@var{CACHE} returns the number of cached documents."
4699 "@*@*"
4700 "@var{CLIENTS} returns the number of "
4701 "connected clients via a status message or a list of connected clients when "
4702 "the @option{--verbose} parameter is used (implies @option{--data}). A "
4703 "verbose line of a client list contains "
4704 "space delimited "
4705 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4706 "IP address if remote, file lock status, whether the current client is self "
4707 "or not, client state (see below), "
4708 "user ID or TLS fingerprint of the connected client, username if the "
4709 "client is a local one else @code{-}, and finally the time stamp of when the "
4710 "client connected."
4711 "@*@*"
4712 "Client state @code{0} is an unknown client state, state @code{1} indicates "
4713 "the client has connected but hasn't completed initializing, state @code{2} "
4714 "indicates that the client is idle, state @code{3} means the "
4715 "client is in a command and state @code{4} means the client is disconnecting. "
4716 "@*@*"
4717 "@var{PID} returns the process ID number of the server via a data response."
4718 "@*@*"
4719 "@var{VERSION} returns the server version number and compile-time features "
4720 "via a data response with each being space delimited."
4721 "@*@*"
4722 "@var{LAST_ERROR} returns a detailed description of the last failed command "
4723 "via a data response, when available."
4724 "@*@*"
4725 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
4726 "via a data response."
4729 new_command("PASSWD", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
4730 "PASSWD\n"
4731 "Changes the passphrase of the secret key required to open the current "
4732 "data file. If the data file is symmetrically encrypted, the error "
4733 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted, "
4734 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
4735 "this command saving any unwanted changes to the @abbr{XML} document."
4736 "@*@*"
4737 "This command is not available to non-invoking clients "
4738 "(@pxref{Access Control})."
4741 new_command("OPEN", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
4742 "OPEN [--lock] <filename>\n"
4743 "Opens @var{filename}. When the @var{filename} is not found on the "
4744 "file-system then a new in-memory document will be created. If the file is "
4745 "found, it is looked for in the file cache and when found no passphrase will "
4746 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
4747 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
4748 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
4749 "@emph{INQUIRE} the client for the passphrase."
4750 "@*@*"
4751 "When the @option{--lock} option is passed then the file mutex will be "
4752 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4753 "file had been opened."
4756 new_command("GENKEY", 1, 1, 0, genkey_command, _(
4757 "GENKEY --inquire-keyparam | --userid=\"str\" [--expire=N] [--algo=\"str\"] [--no-passphrase] [--usage=\"default|sign|encrypt\"\n"
4758 "Generates a new key based on option arguments. One of "
4759 "@option{--inquire-keyparam} or @option{--userid} is required."
4762 new_command("SAVE", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
4763 "SAVE [--symmetric] [--inquire-keyparam | --userid=\"str\" [--expire=N] [--algo=\"str\"] [--no-passphrase]] [--keyid=<fpr>[,..] | [--inquire-keyid]] [--sign-keyid=<fpr>]\n"
4764 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
4765 "file that was opened using the @code{OPEN} command (@pxref{OPEN}). If the "
4766 "file is a new one or the option @option{--inquire-keyparam} was passed, a "
4767 "new keypair will be generated and @cite{pinentry(1)} will be used to prompt "
4768 "for the passphrase of the secret key to be used for signing."
4769 "@*@*"
4770 "The @option{--inquire-keyparam} option will send an "
4771 "@emph{INQUIRE} to the client to obtain the key parameters to use for "
4772 "generating a new keypair. The inquired data is expected to be in "
4773 "@cite{gnupg} @abbr{XML} format. See the @cite{gnupg} documentation for "
4774 "details. The @option{--userid} option will also generate a new keypair using "
4775 "the optional @option{--algo} algorithm with an optional expiration "
4776 "specified with @option{--expire}. The @option{--no-passphrase} will prevent "
4777 "requiring a passphrase for the newly generated key when used with "
4778 "@option{--userid}. Note that when either "
4779 "@option{--inquire-keyparam} or @option{--userid} is specified a new keypair "
4780 "will be "
4781 "generated reguardless if the file is a new one and that the passphrase for "
4782 "the current file will be required before generating the new keypair. This "
4783 "option is available to non-invoking clients (@pxref{Access Control}) only "
4784 "when the file is a new one."
4785 "@*@*"
4786 "You can encrypt the data file to a recipient other than the one that it "
4787 "was encrypted with by passing the @option{--keyid} or "
4788 "@option{--inquire-keyid} option with a comma separated list of "
4789 "public encryption key fingerprints as its argument. Use the "
4790 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
4791 "pattern. The @option{--sign-keyid} option may also be used to sign the data "
4792 "file with an alternate key by specifying the fingerprint of a signing key. "
4793 "Only one signing key is supported unlike the @option{--keyid} option. "
4794 "A passphrase to decrypt the data file "
4795 "will be required when one or more of the original encryption keys or signing "
4796 "key are not found in either of these two options' arguments or when the data "
4797 "file is symmetrically encrypted, reguardless of the @code{require_save_key} "
4798 "configuration parameter. The original encryption keys and signing key will be "
4799 "used when either of these options are not specified."
4800 "@*@*"
4801 "The @option{--keyid} and @option{--sign-keyid} options are not available "
4802 "to non-invoking clients "
4803 "(@pxref{Access Control}) when the recipients or signer do not match those "
4804 "that were used when the file was @code{OPEN}'ed."
4805 "@*@*"
4806 "The @option{--symmetric} option specifies that a new data file be "
4807 "conventionally encrypted. These types of data files do not use a recipient "
4808 "public key but may be signed by using the @option{--sign-keyid} option. "
4809 "To remove the signing key from a symmtrically encrypted data file, leave the "
4810 "option value empty."
4811 "@*@*"
4812 "Note that you cannot change encryption schemes once a data file has been "
4813 "saved."
4816 new_command("ISCACHED", 1, 0, 0, iscached_command, _(
4817 "ISCACHED [--lock] [--agent [--sign]] <filename>\n"
4818 "Determines the file cache status of the specified @var{filename}. "
4819 "The default is to test whether the filename is cached in memory. Passing "
4820 "option @option{--agent} will test the @command{gpg-agent} cache for at most "
4821 "one cached key used for opening the data file (@pxref{OPEN}). To test if "
4822 "a signing key is cached, pass @option{--sign} along with @option{--agent}. "
4823 "Both the @option{--agent} and @option{--sign} options require an opened data "
4824 "file."
4825 "@*@*"
4826 "An @emph{OK} response is returned if the specified @var{filename} is found "
4827 "in the cache. If not found in the cache but exists on the filesystem "
4828 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4829 "returned."
4830 "@*@*"
4831 "The @option{--lock} option will lock the file mutex of @var{filename} when "
4832 "the file exists; it does not need to be opened nor cached. The lock will be "
4833 "released when the client exits or sends the @code{UNLOCK} command "
4834 "(@pxref{UNLOCK}). When this option is passed the current data file is closed."
4837 new_command("CLEARCACHE", 1, 1, 0, clearcache_command, _(
4838 "CLEARCACHE [<filename>]\n"
4839 "Clears a file cache entry for all or the specified @var{filename}. Note that "
4840 "this will also clear any @command{gpg-agent} cached keys which may cause "
4841 "problems if another data file shares the same keys as @var{filename}."
4842 "@*@*"
4843 "When clearing all cache entries a permissions test is done against the "
4844 "current client based on the @var{allowed} configuration parameter in a "
4845 "@var{filename} section. Both a cache entry may be cleared and an error "
4846 "returned depending on cached data files and client permissions."
4849 new_command("CACHETIMEOUT", 1, 1, 0, cachetimeout_command, _(
4850 "CACHETIMEOUT <filename> <seconds>\n"
4851 "The time in @var{seconds} until @var{filename} will be removed from the "
4852 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4853 "the passphrase for each @code{OPEN} command (@pxref{OPEN}) or @code{SAVE} "
4854 "(@pxref{SAVE}) command. @xref{Configuration}, and the @code{cache_timeout} "
4855 "parameter."
4858 new_command("LIST", 0, 1, 0, list_command, _(
4859 "LIST [--inquire] [--recurse] [element[<TAB>child[..]]]\n"
4860 "If no element path is given then a newline separated list of root elements "
4861 "is returned with a data response. If given, then children of the specified "
4862 "element path are returned."
4863 "@*@*"
4864 "Each element path "
4865 "returned will have zero or more flags appened to it. These flags are "
4866 "delimited from the element path by a single space character. A flag itself "
4867 "is a single character. Flag @code{P} indicates that access to the element "
4868 "is denied. Flag @code{+} indicates that there are child nodes of "
4869 "the current element path. Flag @code{E} indicates that an element of the "
4870 "element path contained in a @var{target} attribute could not be found. Flag "
4871 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4872 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
4873 "then an element path, is the element path of the @var{target} attribute "
4874 "contained in the current element."
4875 "@*@*"
4876 "When a specified element path contains an error, beit from the final "
4877 "element in the path or any previous element, the path is still shown but "
4878 "will contain the error flag for the element with the error. Determining "
4879 "the actual element which contains the error is up to the client. This can be "
4880 "done by traversing the final element up to parent elements that contain the "
4881 "same error flag."
4882 "@*@*"
4883 "The option @option{--recurse} may be used to list the entire element tree "
4884 "for a specified element path or the entire tree for all root elements."
4885 "@*@*"
4886 "When the @option{--inquire} option is passed then all remaining non-option "
4887 "arguments are retrieved via a server @emph{INQUIRE}."
4890 new_command("REALPATH", 0, 1, 0, realpath_command, _(
4891 "REALPATH [--inquire] element[<TAB>child[..]]\n"
4892 "Resolves all @code{target} attributes of the specified element path and "
4893 "returns the result with a data response. @xref{Target Attribute}, for details."
4894 "@*@*"
4895 "When the @option{--inquire} option is passed then all remaining non-option "
4896 "arguments are retrieved via a server @emph{INQUIRE}."
4899 new_command("STORE", 0, 1, 0, store_command, _(
4900 "STORE element[<TAB>child[..]]<TAB>[content]\n"
4901 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4902 "@*@*"
4903 "Creates a new element path or modifies the @var{content} of an existing "
4904 "element. If only a single element is specified then a new root element is "
4905 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4906 "set to the final @key{TAB} delimited element. If no @var{content} is "
4907 "specified after the final @key{TAB}, then the content of the existing "
4908 "element will be removed; or will be empty if creating a new element."
4909 "@*@*"
4910 "The only restriction of an element name is that it not contain whitespace "
4911 "characters. There is no other whitespace between the @key{TAB} delimited "
4912 "elements. It is recommended that the content of an element be base64 encoded "
4913 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
4914 "parsing and @command{pwmd} syntax errors."
4917 new_command("RENAME", 0, 1, 0, rename_command, _(
4918 "RENAME [--inquire] element[<TAB>child[..]] <value>\n"
4919 "Renames the specified @var{element} to the new @var{value}. If an element of "
4920 "the same name as the @var{value} already exists it will be overwritten."
4921 "@*@*"
4922 "When the @option{--inquire} option is passed then all remaining non-option "
4923 "arguments are retrieved via a server @emph{INQUIRE}."
4926 new_command("COPY", 0, 1, 0, copy_command, _(
4927 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n"
4928 "Copies the entire element tree starting from the child node of the source "
4929 "element, to the destination element path. If the destination element path "
4930 "does not exist then it will be created; otherwise it is overwritten."
4931 "@*@*"
4932 "Note that attributes from the source element are merged into the "
4933 "destination element when the destination element path exists. When an "
4934 "attribute of the same name exists in both the source and destination "
4935 "elements then the destination attribute will be updated to the source "
4936 "attribute value."
4937 "@*@*"
4938 "When the @option{--inquire} option is passed then all remaining non-option "
4939 "arguments are retrieved via a server @emph{INQUIRE}."
4942 new_command("MOVE", 0, 1, 0, move_command, _(
4943 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n"
4944 "Moves the source element path to the destination element path. If the "
4945 "destination is not specified then it will be moved to the root node of the "
4946 "document. If the destination is specified and exists then it will be "
4947 "overwritten; otherwise non-existing elements of the destination element "
4948 "path will be created."
4949 "@*@*"
4950 "When the @option{--inquire} option is passed then all remaining non-option "
4951 "arguments are retrieved via a server @emph{INQUIRE}."
4954 new_command("DELETE", 0, 1, 0, delete_command, _(
4955 "DELETE [--inquire] element[<TAB>child[..]]\n"
4956 "Removes the specified element path and all of its children. This may break "
4957 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4958 "refers to this element or any of its children."
4959 "@*@*"
4960 "When the @option{--inquire} option is passed then all remaining non-option "
4961 "arguments are retrieved via a server @emph{INQUIRE}."
4964 new_command("GET", 0, 1, 0, get_command, _(
4965 "GET [--inquire] element[<TAB>child[..]]\n"
4966 "Retrieves the content of the specified element. The content is returned "
4967 "with a data response."
4968 "@*@*"
4969 "When the @option{--inquire} option is passed then all remaining non-option "
4970 "arguments are retrieved via a server @emph{INQUIRE}."
4973 new_command("ATTR", 0, 1, 0, attr_command, _(
4974 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n"
4975 "@table @asis\n"
4976 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
4977 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4978 "element. When no @var{value} is specified any existing value will be removed."
4979 "@*@*"
4980 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
4981 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
4982 "or @code{target} an error is returned. Use the @command{DELETE} command "
4983 "(@pxref{DELETE}) instead."
4984 "@*@*"
4985 "@item ATTR LIST element[<TAB>child[..]]\n"
4986 " Retrieves a newline separated list of attributes names and values "
4987 "from the specified element. Each attribute name and value is space delimited."
4988 "@*@*"
4989 "@item ATTR GET attribute element[<TAB>child[..]]\n"
4990 " Retrieves the value of an @var{attribute} from an element."
4991 "@end table\n"
4992 "@*@*"
4993 "When the @option{--inquire} option is passed then all remaining non-option "
4994 "arguments are retrieved via a server @emph{INQUIRE}."
4995 "@*@*"
4996 "@xref{Target Attribute}, for details about this special attribute and also "
4997 "@pxref{Other Attributes} for other attributes that are handled specially "
4998 "by @command{pwmd}."
5001 new_command("XPATH", 0, 1, 0, xpath_command, _(
5002 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
5003 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5004 "specified it is assumed the expression is a request to return a result. "
5005 "Otherwise, the result is set to the @var{value} argument and the document is "
5006 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5007 "is assumed to be empty and the document is updated. For example:"
5008 "@sp 1\n"
5009 "@example\n"
5010 "XPATH //element[@@_name='password']@key{TAB}\n"
5011 "@end example\n"
5012 "@sp 1\n"
5013 "would clear the content of all @var{password} elements in the data file "
5014 "while leaving off the trailing @key{TAB} would return all @var{password} "
5015 "elements in @abbr{XML} format."
5016 "@*@*"
5017 "When the @option{--inquire} option is passed then all remaining non-option "
5018 "arguments are retrieved via a server @emph{INQUIRE}."
5019 "@*@*"
5020 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5021 "expression syntax."
5024 new_command("XPATHATTR", 0, 1, 0, xpathattr_command, _(
5025 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
5026 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5027 "attributes and does not return a result. For the @var{SET} operation the "
5028 "@var{value} is optional but the field is required. If not specified then "
5029 "the attribute value will be empty. For example:"
5030 "@sp 1\n"
5031 "@example\n"
5032 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5033 "@end example\n"
5034 "@sp 1\n"
5035 "would create a @var{password} attribute for each @var{password} element "
5036 "found in the document. The attribute value will be empty but still exist."
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 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5042 "expression syntax."
5045 new_command("IMPORT", 0, 1, 0, import_command, _(
5046 "IMPORT [--root=element[<TAB>child[..]]]\n"
5047 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5048 "@*@*"
5049 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5050 "argument is raw @abbr{XML} data. The content is created as a child of "
5051 "the element path specified with the @option{--root} option or at the "
5052 "document root when not specified. Existing elements of the same name will "
5053 "be overwritten."
5054 "@*@*"
5055 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5056 "for details."
5059 new_command("DUMP", 0, 1, 0, dump_command, _(
5060 "DUMP\n"
5061 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5062 "dumping a specific node."
5065 new_command("LOCK", 0, 0, 0, lock_command, _(
5066 "LOCK\n"
5067 "Locks the mutex associated with the opened file. This prevents other clients "
5068 "from sending commands to the same opened file until the client "
5069 "that sent this command either disconnects or sends the @code{UNLOCK} "
5070 "command. @xref{UNLOCK}."
5073 new_command("UNLOCK", 1, 0, 0, unlock_command, _(
5074 "UNLOCK\n"
5075 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5076 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5077 "@pxref{ISCACHED})."
5080 new_command("GETCONFIG", 1, 1, 0, getconfig_command, _(
5081 "GETCONFIG [filename] <parameter>\n"
5082 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5083 "data response. If no file has been opened then the value for @var{filename} "
5084 "or the default from the @var{global} section will be returned. If a file "
5085 "has been opened and no @var{filename} is specified, the value previously "
5086 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5089 new_command("OPTION", 1, 1, 0, option_command, _(
5090 "OPTION <NAME>=[<VALUE>]\n"
5091 "Sets a client option @var{name} to @var{value}. The value for an option is "
5092 "kept for the duration of the connection with the exception of the "
5093 "@command{pinentry} options which are defaults for all future connections "
5094 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
5095 "@*@*"
5096 "@table @asis\n"
5097 "@item DISABLE-PINENTRY\n"
5098 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
5099 "server inquire is sent to the client to obtain the passphrase. This option "
5100 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5101 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
5102 "to use a @command{pinentry}."
5103 "@*@*"
5104 "@item DISPLAY\n"
5105 "Set or unset the X11 display to use when prompting for a passphrase."
5106 "@*@*"
5107 "@item TTYNAME\n"
5108 "Set the terminal device path to use when prompting for a passphrase."
5109 "@*@*"
5110 "@item TTYTYPE\n"
5111 "Set the terminal type for use with @option{TTYNAME}."
5112 "@*@*"
5113 "@item NAME\n"
5114 "Associates the thread ID of the connection with the specified textual "
5115 "representation. Useful for debugging log messages. May not contain whitespace."
5116 "@*@*"
5117 "@item LOCK-TIMEOUT\n"
5118 "When not @code{0}, the duration in tenths of a second to wait for the file "
5119 "mutex which has been locked by another thread to be released before returning "
5120 "an error. When @code{-1} the error will be returned immediately."
5121 "@*@*"
5122 "@item CLIENT-STATE\n"
5123 "When set to @code{1} then client state status messages for other clients are "
5124 "sent to the current client. The default is @code{0}."
5125 "@end table\n"
5128 new_command("LS", 1, 1, 0, ls_command, _(
5129 "LS\n"
5130 "Returns a newline separated list of data files stored in the data directory "
5131 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response."
5134 new_command("RESET", 1, 1, 0, NULL, _(
5135 "RESET\n"
5136 "Closes the currently opened file but keeps any previously set client options "
5137 "(@pxref{OPTION})."
5140 new_command("NOP", 1, 1, 0, NULL, _(
5141 "NOP\n"
5142 "Does nothing. Always returns successfully."
5145 /* !END-HELP-TEXT! */
5146 new_command ("CANCEL", 1, 1, 0, NULL, NULL);
5147 new_command ("END", 1, 1, 0, NULL, NULL);
5148 new_command ("BYE", 1, 1, 0, NULL, NULL);
5150 int i;
5151 for (i = 0; command_table[i]; i++);
5152 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5153 sort_commands);
5156 gpg_error_t
5157 register_commands (assuan_context_t ctx)
5159 int i = 0, rc;
5161 for (; command_table[i]; i++)
5163 if (!command_table[i]->handler)
5164 continue;
5166 rc = assuan_register_command (ctx, command_table[i]->name,
5167 command_table[i]->handler,
5168 command_table[i]->help);
5169 if (rc)
5170 return rc;
5173 rc = assuan_register_bye_notify (ctx, bye_notify);
5174 if (rc)
5175 return rc;
5177 rc = assuan_register_reset_notify (ctx, reset_notify);
5178 if (rc)
5179 return rc;
5181 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5182 if (rc)
5183 return rc;
5185 return assuan_register_post_cmd_notify (ctx, command_finalize);