Update copyright year.
[pwmd.git] / src / commands.c
blob6ff670213077b58f5d1b50a6a5d14d6227b9a605
1 /*
2 Copyright (C) 2006-2019 Ben Kibbey <bjk@luxsci.net>
4 This file is part of pwmd.
6 Pwmd is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 2 of the License, or
9 (at your option) any later version.
11 Pwmd is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
19 #ifdef HAVE_CONFIG_H
20 #include <config.h>
21 #endif
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <err.h>
27 #include <errno.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 #include <ctype.h>
32 #include <dirent.h>
33 #include <pthread.h>
34 #include <stdint.h>
35 #include <assert.h>
36 #include <signal.h>
38 #include "pwmd-error.h"
39 #include <gcrypt.h>
41 #include "mem.h"
42 #include "xml.h"
43 #include "util-misc.h"
44 #include "common.h"
45 #include "rcfile.h"
46 #include "cache.h"
47 #include "commands.h"
48 #include "mutex.h"
49 #include "crypto.h"
50 #include "acl.h"
52 /* These are command option flags. */
53 #define OPT_INQUIRE 0x0001
54 #define OPT_NO_PASSPHRASE 0x0002
55 #define OPT_ASK 0x0004
56 #define OPT_LIST_RECURSE 0x0008
57 #define OPT_VERBOSE 0x0010
58 #define OPT_LOCK 0x0020
59 #define OPT_LOCK_ON_OPEN 0x0040
60 #define OPT_SIGN 0x0080
61 #define OPT_LIST_ALL 0x0100
62 #define OPT_DATA 0x0200
63 #define OPT_NO_AGENT 0x0400
64 #define OPT_SECRET 0x0800
65 #define OPT_INQUIRE_KEYID 0x1000
66 #define OPT_SYMMETRIC 0x4000
67 #define OPT_NO_SIGNER 0x8000
68 #define OPT_HTML 0x10000
69 #define OPT_CACHE_AGENT 0x20000
70 #define OPT_CACHE_SIGN 0x40000
71 #define OPT_KEYINFO_LEARN 0x80000
73 #define FLOCK_TYPE_NONE 0
74 #define FLOCK_TYPE_SH 0x0001
75 #define FLOCK_TYPE_EX 0x0002
76 #define FLOCK_TYPE_KEEP 0x0004
78 static char env_display[256];
79 static char env_gpg_tty[256];
80 static char env_term[256];
81 static struct command_table_s **command_table;
83 static gpg_error_t do_lock (struct client_s *client, int add);
84 static gpg_error_t validate_checksum (struct client_s *, const char *filename,
85 struct cache_data_s *, unsigned char **,
86 size_t *, int);
87 static gpg_error_t update_checksum (struct client_s *client,
88 unsigned char *from_crc, size_t crclen);
89 static gpg_error_t command_startup (assuan_context_t ctx, const char *name);
90 static void command_finalize (assuan_context_t ctx, gpg_error_t rc);
92 /* When 'status' is true the 'self' field of the status line will be false
93 * because we never send the STATE status message to the same client that
94 * initiated it. */
95 static char *
96 build_client_info_line (struct client_thread_s *thd, int status)
98 char *uid, *username = NULL;
99 char *line;
101 #ifdef WITH_GNUTLS
102 if (thd->remote)
103 uid = str_asprintf("#%s", thd->tls->fp);
104 else
106 uid = str_asprintf("%u", thd->peer->uid);
107 username = get_username (thd->peer->uid);
109 #else
110 uid = str_asprintf("%u", thd->peer->uid);
111 username = get_username (thd->peer->uid);
112 #endif
113 line = str_asprintf ("%p %s %s %s %u %u %u %s %s %u",
114 thd->tid,
115 thd->name ? thd->name : "-",
116 thd->cl && thd->cl->filename
117 && (thd->cl->flags & FLAG_OPEN)
118 ? thd->cl->filename : "/",
119 #ifdef WITH_GNUTLS
120 thd->remote ? thd->peeraddr : "-",
121 #else
122 "-",
123 #endif
124 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
125 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
126 thd->state, uid,
127 #ifdef WITH_GNUTLS
128 thd->remote ? "-" : username,
129 #else
130 username,
131 #endif
132 thd->conntime
135 xfree (username);
136 xfree (uid);
137 return line;
140 void
141 update_client_state (struct client_s *client, unsigned s)
143 MUTEX_LOCK (&cn_mutex);
144 client->thd->state = s;
145 MUTEX_UNLOCK (&cn_mutex);
147 if (client->thd->state != CLIENT_STATE_UNKNOWN)
149 char *line = build_client_info_line (client->thd, 1);
151 pthread_cleanup_push (xfree, line);
152 if (line)
153 send_status_all_not_self (STATUS_STATE, "%s", line);
154 pthread_cleanup_pop (1);
158 static gpg_error_t
159 unlock_file_mutex (struct client_s *client, int remove)
161 gpg_error_t rc = 0;
163 // OPEN: keep the lock for the same file being reopened.
164 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
165 return 0;
167 if (!(client->flags & FLAG_HAS_LOCK))
168 return GPG_ERR_NOT_LOCKED;
170 rc = cache_unlock_mutex (client->filename, remove);
171 if (rc)
172 rc = GPG_ERR_INV_STATE;
173 else
174 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
176 return rc;
179 static gpg_error_t
180 lock_file_mutex (struct client_s *client, int add)
182 gpg_error_t rc = 0;
183 long timeout = config_get_long (client->filename, "cache_timeout");
185 if (client->flags & FLAG_HAS_LOCK)
186 return 0;
188 rc = cache_lock_mutex (client->ctx, client->filename,
189 client->lock_timeout, add, timeout);
190 if (!rc)
191 client->flags |= FLAG_HAS_LOCK;
193 return rc;
196 static gpg_error_t
197 file_modified (struct client_s *client, struct command_table_s *cmd)
199 gpg_error_t rc = 0;
200 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
201 ? LOCK_SH : LOCK_EX;
203 if (!(client->flags & FLAG_OPEN))
204 return GPG_ERR_INV_STATE;
206 rc = lock_file_mutex (client, 0);
207 if (rc && rc != GPG_ERR_NO_DATA)
208 return rc;
210 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
211 if (!rc)
213 rc = validate_checksum (client, client->filename, NULL, NULL, NULL, 0);
214 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
215 rc = 0;
216 else if (rc)
217 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
219 else if (gpg_err_code (rc) == GPG_ERR_ENOENT)
220 rc = 0;
222 /* FLAG_HAS_LOCK may have been set by the LOCK command or OPEN --lock. */
223 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
224 unlock_file_mutex (client, 0);
226 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
227 unlock_flock (&client->flock_fd);
229 return rc;
232 static gpg_error_t
233 parse_xml (assuan_context_t ctx, int new)
235 struct client_s *client = assuan_get_pointer (ctx);
236 int cached = client->doc != NULL;
237 gpg_error_t rc = 0;
239 if (new)
241 client->doc = xml_new_document ();
242 if (client->doc)
244 xmlChar *result;
245 int len;
247 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
248 client->crypto->plaintext = result;
249 client->crypto->plaintext_size = len;
250 if (!client->crypto->plaintext)
252 xmlFreeDoc (client->doc);
253 client->doc = NULL;
254 rc = GPG_ERR_ENOMEM;
257 else
258 rc = GPG_ERR_ENOMEM;
260 else if (!cached)
261 rc = xml_parse_doc ((char *) client->crypto->plaintext,
262 client->crypto->plaintext_size,
263 (xmlDocPtr *)&client->doc);
265 return rc;
268 static void
269 free_client (struct client_s *client)
271 cache_plaintext_release (&client->doc);
272 xfree (client->crc);
273 xfree (client->filename);
274 xfree (client->last_error);
275 crypto_free (client->crypto);
276 client->crypto = NULL;
279 void
280 reset_client (struct client_s *client)
282 assuan_context_t ctx = client->ctx;
283 struct client_thread_s *thd = client->thd;
284 long lock_timeout = client->lock_timeout;
285 xmlErrorPtr xml_error = client->xml_error;
286 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
287 int flock_fd = client->flock_fd;
288 struct bulk_cmd_s *bulk_p = client->bulk_p;
290 unlock_file_mutex (client, client->flags & FLAG_NEW);
291 free_client (client);
292 memset (client, 0, sizeof (struct client_s));
293 client->flock_fd = flock_fd;
294 client->xml_error = xml_error;
295 client->ctx = ctx;
296 client->thd = thd;
297 client->lock_timeout = lock_timeout;
298 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
299 client->bulk_p = bulk_p;
302 static void
303 req_free (void *arg)
305 if (!arg)
306 return;
308 strv_free ((char **) arg);
311 static gpg_error_t
312 parse_open_opt_lock (void *data, void *value)
314 struct client_s *client = data;
316 (void)value;
317 client->opts |= OPT_LOCK_ON_OPEN;
318 return 0;
321 static gpg_error_t
322 parse_opt_inquire (void *data, void *value)
324 struct client_s *client = data;
326 (void) value;
327 client->opts |= OPT_INQUIRE;
328 return 0;
331 static gpg_error_t
332 update_checksum (struct client_s *client, unsigned char *from_crc,
333 size_t crclen)
335 unsigned char *crc;
336 size_t len;
337 struct cache_data_s *cdata;
338 gpg_error_t rc;
340 if (!from_crc)
342 rc = get_checksum (client->filename, &crc, &len);
343 if (rc)
344 return rc;
346 else
348 crc = from_crc;
349 len = crclen;
352 xfree (client->crc);
353 client->crc = xmalloc (len);
354 memcpy (client->crc, crc, len);
355 pthread_cleanup_push (xfree, crc);
356 cdata = cache_get_data (client->filename, NULL);
357 pthread_cleanup_pop (0);
358 if (cdata)
360 xfree (cdata->crc);
361 cdata->crc = xmalloc (len);
362 memcpy (cdata->crc, crc, len);
365 if (!from_crc)
366 xfree (crc);
367 return 0;
370 static gpg_error_t
371 validate_checksum (struct client_s *client, const char *filename,
372 struct cache_data_s *cdata, unsigned char **r_crc,
373 size_t *r_crclen, int from_cdata)
375 unsigned char *crc;
376 size_t len;
377 gpg_error_t rc;
378 int n = 0;
380 if (cdata && !cdata->crc)
381 return GPG_ERR_CHECKSUM;
383 rc = get_checksum (filename, &crc, &len);
384 if (rc)
385 return rc;
387 if (client->crc)
388 n = memcmp (client->crc, crc, len);
389 else if ((client->flags & FLAG_NEW) && cache_get_data (filename, NULL))
390 n = 1;
392 if ((!n && cdata) || (from_cdata && cdata && crc))
393 n = memcmp (cdata->crc, crc, len);
395 if (!n && r_crc)
397 *r_crc = crc;
398 *r_crclen = len;
400 else
401 xfree (crc);
403 return n ? GPG_ERR_CHECKSUM : 0;
406 static gpg_error_t
407 open_command (assuan_context_t ctx, char *line)
409 gpg_error_t rc;
410 struct client_s *client = assuan_get_pointer (ctx);
411 int same_file = 0;
412 assuan_peercred_t peer;
413 struct cache_data_s *cdata = NULL;
414 int cached = 0;
415 unsigned char *crc = NULL;
416 size_t crclen = 0;
417 int plaintext = 0;
418 struct argv_s *args[] = {
419 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
420 NULL
423 rc = parse_options (&line, args, client, 1);
424 if (rc)
425 return send_error (ctx, rc);
427 rc = do_validate_peer (ctx, line, &peer);
428 if (rc == GPG_ERR_FORBIDDEN)
430 rc = peer_is_invoker (client);
431 if (rc == GPG_ERR_EACCES)
432 rc = GPG_ERR_FORBIDDEN;
435 if (rc)
436 return send_error (ctx, rc);
438 if (!valid_filename (line))
439 return send_error (ctx, GPG_ERR_INV_VALUE);
441 /* This client may have locked a different file with ISCACHED --lock than
442 * the current filename. This will remove that lock. */
443 same_file = client->filename && !strcmp (line, client->filename);
444 if (client->flags & FLAG_OPEN ||
445 (client->flags & FLAG_HAS_LOCK && !same_file))
447 unsigned opts = client->opts;
448 unsigned flags = client->flags;
450 if (same_file)
451 client->flags |= FLAG_KEEP_LOCK;
453 /* Another client wrote to the same data file as currently opened. */
454 cdata = cache_get_data (client->filename, NULL);
455 if (cdata && cdata->crc)
456 flags &= ~FLAG_NEW;
457 /* Remove cache entry for the new file that hadn't been written. */
458 else if (client->flags & FLAG_NEW)
459 cache_clear (NULL, client->filename, 0, 0);
461 cdata = NULL;
462 reset_client (client);
463 client->opts = opts;
464 client->flags |= flags;
465 client->flags &= ~(FLAG_LOCK_CMD);
466 if (!same_file)
467 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
470 xfree (client->filename);
471 client->filename = str_dup (line);
472 if (!client->filename)
473 return send_error(ctx, GPG_ERR_ENOMEM);
475 /* Need to lock the mutex here because file_modified() cannot without
476 * knowing the filename. */
477 rc = lock_file_mutex (client, 1);
478 if (rc)
479 client->flags &= ~FLAG_OPEN;
481 if (!rc)
483 rc = lock_flock (ctx, client->filename, LOCK_SH, &client->flock_fd);
484 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
485 rc = 0;
488 if (!rc)
490 char *keyfile = config_get_string (client->filename, "passphrase_file");
492 rc = crypto_init (&client->crypto, client->ctx, client->filename,
493 client->flags & FLAG_NO_PINENTRY, keyfile);
494 if (rc)
495 xfree (keyfile);
496 else
497 rc = open_check_file (client->filename, NULL, NULL, 1);
500 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
502 int reload = 0;
503 int defer = 0;
505 if (rc) // new file
507 rc = 0;
509 if (config_get_boolean ("global", "strict_open"))
511 rc = peer_is_invoker (client);
512 if (rc == GPG_ERR_EACCES)
513 rc = GPG_ERR_FORBIDDEN;
516 if (!rc)
518 client->flags |= FLAG_NEW;
519 // data file disappeared. clear the cache entry.
520 cache_clear (NULL, client->filename, 1, 1);
521 cdata = NULL;
524 goto done;
527 cdata = cache_get_data (client->filename, &defer);
528 if (cdata && !defer
529 && !cache_plaintext_get (client->filename, &client->doc))
531 rc = validate_checksum (client, client->filename, cdata, &crc,
532 &crclen, 0);
533 if (rc)
535 log_write ("%s: %s", client->filename,
536 pwmd_strerror (rc));
537 cache_plaintext_release (&client->doc);
538 if (rc == GPG_ERR_CHECKSUM)
540 cache_clear (NULL, client->filename, 1, 1);
541 cdata = NULL;
542 goto decrypt;
546 #ifdef WITH_GNUTLS
547 if (!rc && client->thd->remote
548 && config_get_boolean (client->filename, "tcp_require_key")
549 && !(client->flags & FLAG_NEW))
551 rc = crypto_try_decrypt (client,
552 (client->flags & FLAG_NO_PINENTRY));
554 #endif
555 if (!rc)
557 strv_free (client->crypto->pubkey);
558 client->crypto->pubkey = NULL;
559 if (cdata->pubkey)
560 client->crypto->pubkey = strv_dup (cdata->pubkey);
562 xfree (client->crypto->sigkey);
563 client->crypto->sigkey = NULL;
564 if (cdata->sigkey)
565 client->crypto->sigkey = str_dup (cdata->sigkey);
567 cached = 1;
568 plaintext = 1;
571 else if (cdata && cdata->doc) // cached document
573 if (!rc && !(client->flags & FLAG_NEW))
575 rc = validate_checksum (client, client->filename, cdata, &crc,
576 &crclen, 0);
577 if (rc == GPG_ERR_CHECKSUM)
579 rc = 0;
580 reload = 1;
584 if (!rc)
586 rc = cache_iscached (client->filename, &defer, 0, 0);
587 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
589 rc = 0;
590 reload = 2;
594 if (!rc && reload)
596 if (reload == 1)
597 log_write ("%s: %s", client->filename,
598 pwmd_strerror (GPG_ERR_CHECKSUM));
599 cache_clear (NULL, client->filename, 1, 1);
600 cdata = NULL;
601 rc = crypto_decrypt (client, client->crypto);
603 #ifdef WITH_GNUTLS
604 else if (!rc)
606 if (client->thd->remote
607 && config_get_boolean (client->filename, "tcp_require_key")
608 && !(client->flags & FLAG_NEW))
609 rc = crypto_try_decrypt (client,
610 (client->flags & FLAG_NO_PINENTRY));
612 #endif
614 if (!rc && cdata)
616 client->crypto->plaintext = cdata->doc;
617 client->crypto->plaintext_size = cdata->size;
618 rc = cache_decrypt (client->crypto);
619 if (!rc)
621 cdata->doc = NULL;
622 cdata->size = 0;
624 strv_free (client->crypto->pubkey);
625 client->crypto->pubkey = NULL;
626 if (cdata->pubkey)
627 client->crypto->pubkey = strv_dup (cdata->pubkey);
629 xfree (client->crypto->sigkey);
630 client->crypto->sigkey = NULL;
631 if (cdata->sigkey)
632 client->crypto->sigkey = str_dup (cdata->sigkey);
634 cached = 1;
636 else
638 client->crypto->plaintext = NULL;
639 client->crypto->plaintext_size = 0;
643 else // existing file
645 decrypt:
646 cached = cdata != NULL;
647 rc = crypto_decrypt (client, client->crypto);
651 done:
652 if (!rc && !plaintext)
654 rc = parse_xml (ctx, client->flags & FLAG_NEW);
655 if (!rc)
657 rc = cache_encrypt (client->crypto);
658 if (rc)
659 cache_clear (NULL, client->filename, 1, 1);
660 else
662 long timeout = config_get_long (client->filename,
663 "cache_timeout");
665 cache_free_data_once (cdata);
666 cdata = xcalloc (1, sizeof (struct cache_data_s));
667 cdata->doc = client->crypto->plaintext;
668 cdata->size = client->crypto->plaintext_size;
669 cdata->pubkey = strv_dup(client->crypto->pubkey);
670 cdata->sigkey = client->crypto->sigkey ? str_dup(client->crypto->sigkey) : NULL;
671 client->crypto->plaintext = NULL;
672 client->crypto->plaintext_size = 0;
674 if (cached) // wont increment the refcount
676 if (crclen)
678 xfree (client->crc);
679 client->crc = NULL;
680 xfree (cdata->crc);
681 cdata->crc = xmalloc (crclen);
682 memcpy (cdata->crc, crc, crclen);
685 rc = cache_set_data (client->filename, cdata);
686 /* The cache entry may have been removed and cache_set_data()
687 * already sent STATUS_CACHE. */
688 if (!cache_iscached (client->filename, NULL, 0, 0))
689 rc = send_status (ctx, STATUS_CACHE, NULL);
691 else
692 rc = cache_add_file (client->filename, cdata, timeout);
694 if (!rc)
695 cache_plaintext_set (client->filename, client->doc, 0);
699 else if (!rc)
701 xfree (client->crc);
702 client->crc = NULL;
703 if (crc)
705 client->crc = xmalloc (crclen);
706 memcpy (client->crc, crc, crclen);
710 xfree (crc);
712 if (!rc && !(client->flags & FLAG_NEW) && !cached)
713 rc = update_checksum (client, NULL, 0);
715 if (!rc)
717 client->flags |= FLAG_OPEN;
719 if (client->flags & FLAG_NEW)
720 rc = send_status (ctx, STATUS_NEWFILE, NULL);
722 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
723 rc = do_lock (client, 0);
726 if (rc)
728 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
730 if (client->flags & FLAG_NEW)
731 cache_clear (NULL, client->filename, 1, 1);
733 crypto_free (client->crypto);
734 client->crypto = NULL;
735 client->flags &= ~FLAG_OPEN;
736 cache_plaintext_release (&client->doc);
738 else
739 crypto_free_non_keys (client->crypto);
741 return send_error (ctx, rc);
744 /* If not an invoking_user or is an existing file, check that the list of user
745 * supplied key ID's are in the list of current key ID's obtained when
746 * decrypting the data file.
748 static gpg_error_t
749 permitted_to_save (struct client_s *client, const char **keys,
750 const char **value)
752 gpg_error_t rc = 0;
753 const char **v;
755 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
756 return 0;
758 rc = peer_is_invoker (client);
759 if (!rc)
760 return 0;
761 else if (rc == GPG_ERR_EACCES)
762 rc = GPG_ERR_FORBIDDEN;
763 else if (rc)
764 return rc;
766 /* Empty match. */
767 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
768 return 0;
770 for (v = value; v && *v; v++)
772 const char **k, *pv = *v;
773 int match = 0;
775 if (*pv == '0' && *(pv+1) == 'x')
776 pv += 2;
778 for (k = keys; k && *k; k++)
780 const char *pk = *k;
782 if (*pk == '0' && *(pk+1) == 'x')
783 pk += 2;
785 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
786 if (rc)
787 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
789 if (!rc)
791 match = 1;
792 break;
796 if (!match)
797 return GPG_ERR_FORBIDDEN;
800 return rc;
803 /* Requires that the keyid be a fingerprint in 16 byte form. */
804 static gpg_error_t
805 parse_save_opt_keyid_common (struct client_s *client, const char **list,
806 const char *value, char ***dst)
808 gpg_error_t rc = 0;
809 char **keys = NULL;
811 if (value && *value)
813 keys = str_split (value, ",", 0);
814 if (!keys)
815 return GPG_ERR_ENOMEM;
818 rc = crypto_keyid_to_16b (keys);
819 if (!rc)
820 rc = permitted_to_save (client, list, (const char **)keys);
822 if (!rc)
823 *dst = keys;
824 else
825 strv_free (keys);
827 return rc;
830 static gpg_error_t
831 parse_save_opt_keyid (void *data, void *value)
833 struct client_s *client = data;
834 const char *str = value;
835 char **dst = NULL;
836 gpg_error_t rc;
838 rc = parse_save_opt_keyid_common (client,
839 (const char **)client->crypto->pubkey,
840 str, &dst);
841 if (rc)
842 return rc;
844 client->crypto->save.pubkey = dst;
845 return 0;
848 static gpg_error_t
849 parse_save_opt_sign_keyid (void *data, void *value)
851 struct client_s *client = data;
852 const char *str = value;
853 char **dst = NULL;
854 gpg_error_t rc;
855 char **tmp = NULL;
857 if (client->crypto->sigkey)
859 if (!strv_printf (&tmp, "%s", client->crypto->sigkey))
860 return GPG_ERR_ENOMEM;
863 rc = parse_save_opt_keyid_common (client, (const char **)tmp, str, &dst);
864 strv_free (tmp);
865 if (rc)
866 return rc;
868 if (!dst)
869 client->opts |= OPT_NO_SIGNER;
870 else
871 client->crypto->save.sigkey = str_dup (*dst);
873 strv_free (dst);
874 return 0;
877 static gpg_error_t
878 parse_save_opt_inquire_keyid (void *data, void *value)
880 struct client_s *client = data;
882 (void)value;
884 if (!(client->flags & FLAG_NEW))
886 gpg_error_t rc = peer_is_invoker (client);
888 if (rc)
889 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
892 client->opts |= OPT_INQUIRE_KEYID;
893 return 0;
896 static gpg_error_t
897 parse_save_opt_symmetric (void *data, void *value)
899 struct client_s *client = data;
901 (void)value;
902 client->opts |= OPT_SYMMETRIC;
903 return 0;
906 static gpg_error_t
907 parse_genkey_opt_userid (void *data, void *value)
909 struct client_s *client = data;
911 if (!(client->flags & FLAG_NEW))
913 gpg_error_t rc = peer_is_invoker (client);
915 if (rc)
916 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
919 client->crypto->save.userid = str_dup (value);
920 return client->crypto->save.userid ? 0 : GPG_ERR_ENOMEM;
923 static gpg_error_t
924 parse_genkey_opt_algo (void *data, void *value)
926 struct client_s *client = data;
928 client->crypto->save.algo = str_dup (value);
929 return client->crypto->save.algo ? 0 : GPG_ERR_ENOMEM;
932 static gpg_error_t
933 parse_genkey_opt_no_expire (void *data, void *value)
935 struct client_s *client = data;
937 client->crypto->save.flags |= GPGME_CREATE_NOEXPIRE;
938 return 0;
941 static gpg_error_t
942 parse_genkey_opt_expire (void *data, void *value)
944 struct client_s *client = data;
945 gpg_error_t rc = 0;
946 char *p = NULL;
947 unsigned long t;
949 errno = 0;
950 t = strtoul (value, &p, 10);
952 if (!errno && p && *p)
953 rc = GPG_ERR_INV_VALUE;
954 else if (t == ULONG_MAX)
955 rc = GPG_ERR_INV_VALUE;
956 else if (errno)
957 rc = gpg_error_from_syserror ();
958 else
959 client->crypto->save.expire = t;
961 return rc;
964 static gpg_error_t
965 parse_genkey_opt_no_passphrase (void *data, void *value)
967 struct client_s *client = data;
969 (void)value;
970 client->crypto->save.flags |= GPGME_CREATE_NOPASSWD;
971 return 0;
974 /* Tests that the keys in new_keys are also in old_keys. */
975 static gpg_error_t
976 compare_keys (char **new_keys, char **old_keys)
978 char **o;
980 if (!old_keys || !*old_keys)
981 return 0;
983 crypto_keyid_to_16b (new_keys);
985 for (o = old_keys; *o; o++)
987 char **n;
989 for (n = new_keys; *n; n++)
991 if (!strcmp (*n, *o))
992 break;
995 if (!*n)
996 return GPG_ERR_NOT_FOUND;
999 return 0;
1002 static gpg_error_t
1003 inquire_keyid (struct client_s *client)
1005 gpg_error_t rc;
1006 unsigned char *result = NULL;
1007 size_t len;
1008 const char *s = "KEYID";
1009 char ***orig;
1010 char ***save;
1012 orig = &client->crypto->pubkey;
1013 save = &client->crypto->save.pubkey;
1014 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
1015 if (!rc)
1017 char **dst = NULL;
1019 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
1020 (char *)result, &dst);
1021 if (!rc)
1022 *save = dst;
1025 xfree (result);
1026 return rc;
1030 /* When a key lookup in gpg-agent's cache fails, the agent tries the last
1031 * successful key to be unlocked. This prevents pwmd from successfully
1032 * clearing a signing key since the previous key, which more than likely
1033 * belongs to the same keypair as the encryption/decryption key, will have the
1034 * passphrase cached and therefore the signing key also cached. So we need to
1035 * clear both the signing and encryption keys to get the effect of requiring a
1036 * passphrase when generating a new keypair for an existing data file, or when
1037 * the "require_save_key" configuration parameter is set. This parameter is
1038 * mostly a failsafe of the gpg-agent option --ignore-cache-for-signing since
1039 * some/most/all users may fail to set it.
1041 static gpg_error_t
1042 save_command (assuan_context_t ctx, char *line)
1044 struct client_s *client = assuan_get_pointer (ctx);
1045 struct cache_data_s *cdata = NULL;
1046 int sym = 0;
1047 gpg_error_t rc = 0, cache_rc = 0;
1048 int defer = 0;
1049 struct argv_s *args[] = {
1050 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
1051 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
1052 parse_save_opt_inquire_keyid },
1053 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
1054 parse_save_opt_sign_keyid},
1055 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
1056 parse_save_opt_symmetric },
1057 NULL
1060 crypto_free_save (&client->crypto->save);
1061 client->crypto->save.expire = DEFAULT_EXPIRE;
1063 rc = crypto_is_symmetric (client->filename);
1064 if (!rc || rc == GPG_ERR_BAD_DATA || rc == GPG_ERR_ENOENT)
1066 if (!rc)
1068 client->opts |= OPT_SYMMETRIC;
1069 sym = 1;
1071 else if (rc == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1072 rc = 0; // New file
1073 else
1074 rc = 0; // PKI
1077 if (rc)
1078 return send_error (ctx, rc);
1080 rc = parse_options (&line, args, client, 0);
1081 if (rc)
1082 return send_error (ctx, rc);
1084 if (config_get_boolean (client->filename, "require_save_key")
1085 || (client->opts & OPT_SYMMETRIC))
1086 client->opts |= OPT_ASK;
1088 rc = open_check_file (client->filename, NULL, NULL, 1);
1089 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
1091 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
1092 return send_error (ctx, rc);
1095 if (!rc)
1096 cache_rc = rc = cache_iscached (client->filename, &defer, 0, 1);
1098 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1099 rc = 0;
1100 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1101 rc = 0;
1103 if (rc)
1104 return send_error (ctx, rc);
1106 /* Specifying both a recipient and symmetric encryption is an error. */
1107 if ((client->opts & OPT_INQUIRE_KEYID) && (client->opts & OPT_SYMMETRIC))
1108 return send_error (ctx, GPG_ERR_CONFLICT);
1109 /* Existing file with a recipient and wanting symmetric is an error. */
1110 else if ((client->opts & OPT_SYMMETRIC) && client->crypto->save.pubkey)
1111 return send_error (ctx, GPG_ERR_CONFLICT);
1112 else if (client->crypto->save.pubkey && (client->opts & OPT_INQUIRE_KEYID))
1113 return send_error (ctx, GPG_ERR_CONFLICT);
1114 else if (!sym && (client->opts & OPT_SYMMETRIC) && !(client->flags & FLAG_NEW))
1115 return send_error (ctx, GPG_ERR_CONFLICT);
1116 /* New file that is not symmetric without either a recipient or signer. */
1117 else if ((client->flags & FLAG_NEW) && !(client->opts & OPT_SYMMETRIC)
1118 && (!client->crypto->save.pubkey || !client->crypto->save.sigkey))
1119 return send_error (ctx, GPG_ERR_SYNTAX);
1120 else if (client->opts & OPT_INQUIRE_KEYID)
1121 rc = inquire_keyid (client);
1123 if (!rc)
1125 client->crypto->keyfile = config_get_string (client->filename,
1126 "passphrase_file");
1127 rc = crypto_init_ctx (client->crypto, (client->flags & FLAG_NO_PINENTRY),
1128 client->crypto->keyfile);
1131 if (!rc && (client->flags & FLAG_NEW))
1133 /* Require --keyid when --sign-keyid exists to keep KEYINFO
1134 * synchronized. */
1135 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1136 && !(client->opts & OPT_SYMMETRIC))
1137 rc = GPG_ERR_NO_PUBKEY;
1139 else if (!rc)
1141 cdata = cache_get_data (client->filename, NULL);
1142 if (cdata)
1144 if (client->crypto->save.pubkey)
1145 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1147 /* Always allow a signer for symmetric data files. */
1148 if (!rc && client->crypto->save.sigkey
1149 && !(client->opts & OPT_SYMMETRIC))
1150 rc = !strcmp (client->crypto->save.sigkey, cdata->sigkey)
1151 ? 0 : GPG_ERR_NOT_FOUND;
1153 /* Prevent saving to a recipient who is not in the original recipient
1154 * list without a passphrase. */
1155 if (rc || (client->crypto->sigkey && (client->opts & OPT_NO_SIGNER)))
1156 client->opts |= OPT_ASK;
1158 if (rc == GPG_ERR_NOT_FOUND)
1160 rc = peer_is_invoker (client);
1161 if (rc == GPG_ERR_EACCES)
1162 rc = GPG_ERR_FORBIDDEN;
1165 if (!client->crypto->save.pubkey
1166 && !(client->opts & OPT_SYMMETRIC))
1167 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1169 if (!rc && !client->crypto->save.sigkey && cdata->sigkey
1170 && !(client->opts & OPT_NO_SIGNER))
1171 client->crypto->save.sigkey = str_dup (cdata->sigkey);
1172 else if (!rc && !client->crypto->save.sigkey
1173 && (client->opts & OPT_NO_SIGNER)
1174 && !(client->opts & OPT_SYMMETRIC))
1175 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1177 else
1179 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1180 client->crypto->save.sigkey = str_dup (client->crypto->sigkey);
1184 if (!rc && !(client->flags & FLAG_NEW))
1186 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1187 if (client->opts & OPT_SYMMETRIC)
1188 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1190 if (client->opts & OPT_ASK)
1192 rc = cache_clear_agent_keys (client->filename, 1, 1);
1193 if (!rc)
1194 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1198 if (!rc && client->opts & OPT_SYMMETRIC)
1199 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1201 if (!rc)
1202 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1204 if (!rc)
1206 xmlNodePtr root = xmlDocGetRootElement (client->doc);
1208 rc = xml_add_attribute (client, root, "_version", PACKAGE_VERSION);
1211 if (!rc)
1213 int size;
1215 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1217 if (size > 0)
1218 client->crypto->plaintext_size = (size_t) size;
1219 else
1220 rc = GPG_ERR_ENOMEM;
1222 if (!rc)
1224 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1225 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1226 client->crypto->flags |= !(client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_PASSWD_SIGN : 0;
1227 rc = crypto_encrypt (client, client->crypto);
1228 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1231 if (!rc)
1233 unsigned char *crc = NULL;
1234 size_t crclen = 0;
1236 rc = crypto_write_file (client->crypto, &crc, &crclen);
1237 pthread_cleanup_push ((void *)xfree, crc);
1238 if (!rc)
1240 if (!cache_rc)
1241 cdata = cache_get_data (client->filename, NULL);
1242 else
1243 cdata = xcalloc (1, sizeof (struct cache_data_s));
1246 if (!rc)
1248 rc = cache_encrypt (client->crypto);
1249 if (rc)
1251 cache_clear (NULL, client->filename, 1, 1);
1252 client->flags &= ~(FLAG_NEW);
1254 strv_free (client->crypto->pubkey);
1255 client->crypto->pubkey = NULL;
1256 if (client->crypto->save.pubkey)
1257 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1259 xfree (client->crypto->sigkey);
1260 client->crypto->sigkey = NULL;
1261 if (client->crypto->save.sigkey)
1262 client->crypto->sigkey = str_dup (client->crypto->save.sigkey);
1266 if (!rc)
1268 long timeout = config_get_long (client->filename, "cache_timeout");
1269 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1271 if (!doc)
1272 rc = GPG_ERR_ENOMEM;
1274 if (!rc)
1276 cache_plaintext_release (&client->doc);
1277 strv_free (cdata->pubkey);
1278 cdata->pubkey = client->crypto->save.pubkey;
1279 client->crypto->save.pubkey = NULL;
1281 xfree (cdata->sigkey);
1282 cdata->sigkey = client->crypto->save.sigkey;
1283 client->crypto->save.sigkey = NULL;
1285 xfree (cdata->crc);
1286 cdata->crc = NULL;
1288 /* cache_encrypt() does in-place encryption */
1289 xfree (cdata->doc);
1290 cdata->doc = client->crypto->plaintext;
1291 client->crypto->plaintext = NULL;
1292 cdata->size = client->crypto->plaintext_size;
1293 client->crypto->plaintext_size = 0;
1295 client->doc = doc;
1296 cache_plaintext_set (client->filename, client->doc, 0);
1298 /* Update in case the cache entry expires the next SAVE may
1299 * not have any known keys. */
1300 strv_free (client->crypto->pubkey);
1301 client->crypto->pubkey = NULL;
1302 if (cdata->pubkey)
1303 client->crypto->pubkey = strv_dup (cdata->pubkey);
1305 xfree (client->crypto->sigkey);
1306 client->crypto->sigkey = NULL;
1307 if (cdata->sigkey)
1308 client->crypto->sigkey = str_dup (cdata->sigkey);
1310 if (!cache_rc) // wont increment refcount
1311 rc = cache_set_data (client->filename, cdata);
1312 else
1313 rc = cache_add_file (client->filename, cdata, timeout);
1316 if (!rc && (cache_rc || (client->flags & FLAG_NEW)))
1317 send_status_all (STATUS_CACHE, NULL);
1319 if (!rc)
1321 rc = update_checksum (client, crc, crclen);
1322 client->flags &= ~(FLAG_NEW);
1326 pthread_cleanup_pop (1);
1327 if (!rc)
1328 client->did_cow = 0;
1332 crypto_free_non_keys (client->crypto);
1333 return send_error (ctx, rc);
1336 static gpg_error_t
1337 parse_genkey_opt_usage (void *data, void *v)
1339 struct client_s *client = data;
1340 char *value = v;
1342 if (!value || !*value)
1343 return GPG_ERR_INV_VALUE;
1344 else if (!strcmp (value, "sign"))
1345 client->crypto->save.flags |= GPGME_CREATE_SIGN;
1346 else if (!strcmp (value, "encrypt"))
1347 client->crypto->save.flags |= GPGME_CREATE_ENCR;
1348 else if (!strcmp (value, "default"))
1349 client->crypto->save.flags &= ~(GPGME_CREATE_ENCR|GPGME_CREATE_SIGN);
1350 else
1351 return GPG_ERR_INV_VALUE;
1353 return 0;
1356 gpg_error_t
1357 parse_genkey_opt_subkey_of (void *data, void *v)
1359 gpg_error_t rc;
1360 struct client_s *client = data;
1361 char *value = v;
1362 char *tmp[] = { value, NULL };
1363 gpgme_key_t *keys = NULL;
1365 rc = peer_is_invoker (client);
1366 if (rc)
1367 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
1369 if (!value || !*value)
1370 return GPG_ERR_INV_VALUE;
1372 rc = crypto_list_keys (client->crypto, tmp, 1, &keys);
1373 if (rc)
1374 return rc;
1376 if (!keys || !*keys)
1378 crypto_free_key_list (keys);
1379 return GPG_ERR_NO_SECKEY;
1382 client->crypto->save.mainkey = keys;
1383 return 0;
1386 static gpg_error_t
1387 genkey_command (assuan_context_t ctx, char *line)
1389 struct client_s *client = assuan_get_pointer (ctx);
1390 struct crypto_s *crypto, *orig;
1391 gpg_error_t rc = 0;
1392 struct argv_s *args[] = {
1393 &(struct argv_s) {"userid", OPTION_TYPE_ARG,
1394 parse_genkey_opt_userid},
1395 &(struct argv_s) {"_expire", OPTION_TYPE_ARG,
1396 parse_genkey_opt_expire},
1397 &(struct argv_s) {"no-expire", OPTION_TYPE_NOARG,
1398 parse_genkey_opt_no_expire},
1399 &(struct argv_s) {"algo", OPTION_TYPE_ARG,
1400 parse_genkey_opt_algo},
1401 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1402 parse_genkey_opt_no_passphrase},
1403 &(struct argv_s) {"usage", OPTION_TYPE_ARG,
1404 parse_genkey_opt_usage},
1405 &(struct argv_s) {"subkey-of", OPTION_TYPE_ARG,
1406 parse_genkey_opt_subkey_of},
1407 NULL
1410 if (!(client->flags & FLAG_OPEN))
1411 return send_error (ctx, GPG_ERR_INV_STATE);
1413 rc = crypto_init (&crypto, ctx, client->filename,
1414 client->flags & FLAG_NO_PINENTRY, NULL);
1415 if (rc)
1416 return send_error (ctx, rc);
1418 pthread_cleanup_push ((void *)crypto_free, client->crypto);
1419 orig = client->crypto;
1420 client->crypto = crypto;
1421 rc = parse_options (&line, args, client, 0);
1422 if (!rc)
1424 if (!client->crypto->save.userid && !client->crypto->save.mainkey)
1425 rc = GPG_ERR_SYNTAX;
1426 else
1428 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1429 rc = crypto_genkey (client, client->crypto);
1433 pthread_cleanup_pop (0);
1434 crypto_free (crypto);
1435 client->crypto = orig;
1436 return send_error (ctx, rc);
1439 static gpg_error_t
1440 do_delete (assuan_context_t ctx, char *line)
1442 struct client_s *client = assuan_get_pointer (ctx);
1443 struct xml_request_s *req;
1444 xmlNodePtr n;
1445 gpg_error_t rc;
1447 if (!line || !*line)
1448 return GPG_ERR_SYNTAX;
1450 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1451 if (rc)
1452 return rc;
1454 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1455 xml_free_request (req);
1456 if (rc)
1457 return rc;
1459 rc = xml_is_element_owner (client, n);
1460 if (!rc)
1461 rc = xml_unlink_node (client, n);
1463 return rc;
1466 /* Won't update cdata->plaintext. Other clients are working on the original or
1467 * copy of the same document. The first client to SAVE wins and requires others
1468 * to reopen the data file do to a checksum error. */
1469 static gpg_error_t
1470 copy_on_write (struct client_s *client)
1472 struct cache_data_s *cdata;
1474 if (client->did_cow)
1475 return 0;
1477 cdata = cache_get_data (client->filename, NULL);
1478 if (cdata)
1480 gpg_error_t rc;
1481 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1483 if (!doc)
1484 return GPG_ERR_ENOMEM;
1486 rc = cache_plaintext_set (client->filename, doc, 1);
1487 if (rc)
1489 xmlFree (doc);
1490 return rc;
1493 (void)cache_plaintext_release (&client->doc);
1494 client->doc = doc;
1495 client->did_cow = 1;
1496 return 0;
1499 return GPG_ERR_NO_DATA;
1502 static gpg_error_t
1503 delete_command (assuan_context_t ctx, char *line)
1505 struct client_s *client = assuan_get_pointer (ctx);
1506 gpg_error_t rc;
1507 struct argv_s *args[] = {
1508 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1509 NULL
1512 rc = parse_options (&line, args, client, 1);
1513 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1514 rc = GPG_ERR_SYNTAX;
1515 if (rc)
1516 return send_error (ctx, rc);
1518 rc = copy_on_write (client);
1519 if (rc)
1520 return send_error (ctx, rc);
1522 if (client->opts & OPT_INQUIRE)
1524 unsigned char *result;
1525 size_t len;
1527 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1528 if (rc)
1529 return send_error (ctx, rc);
1531 pthread_cleanup_push ((void *)xfree, result);
1532 rc = do_delete (ctx, (char *)result);
1533 pthread_cleanup_pop (1);
1535 else
1536 rc = do_delete (ctx, line);
1538 return send_error (ctx, rc);
1541 static gpg_error_t
1542 update_element_expirey (struct client_s *client, xmlNodePtr n)
1544 gpg_error_t rc = 0;
1545 xmlChar *expire, *incr;
1546 char *p;
1547 time_t e, e_orig, i;
1548 time_t now = time (NULL);
1550 expire = xml_attribute_value (n, (xmlChar *)"_expire");
1551 if (!expire)
1552 return 0;
1554 errno = 0;
1555 e = strtoul ((char *)expire, &p, 10);
1556 if (errno || *p || e == ULONG_MAX || *expire == '-')
1558 xmlFree (expire);
1559 rc = GPG_ERR_ERANGE;
1560 goto fail;
1563 xmlFree (expire);
1564 incr = xml_attribute_value (n, (xmlChar *)"_age");
1565 if (!incr)
1566 return 0;
1568 i = strtoul ((char *)incr, &p, 10);
1569 if (errno || *p || i == ULONG_MAX || *incr == '-')
1571 xmlFree (incr);
1572 rc = GPG_ERR_ERANGE;
1573 goto fail;
1576 xmlFree (incr);
1577 e_orig = e;
1578 e = now + i;
1579 p = str_asprintf ("%lu", e);
1580 if (!p)
1582 rc = GPG_ERR_ENOMEM;
1583 goto fail;
1586 rc = xml_add_attribute (client, n, "_expire", p);
1587 xfree (p);
1588 if (!rc)
1589 rc = send_status (client->ctx, STATUS_EXPIRE, "%lu %lu", e_orig, e);
1591 fail:
1592 return rc;
1595 static gpg_error_t
1596 store_command (assuan_context_t ctx, char *line)
1598 struct client_s *client = assuan_get_pointer (ctx);
1599 gpg_error_t rc;
1600 size_t len;
1601 unsigned char *result;
1602 xmlNodePtr n, parent;
1603 int has_content;
1604 char *content = NULL;
1605 struct xml_request_s *req;
1607 if (!client->bulk_p && line && *line)
1608 return send_error (ctx, GPG_ERR_SYNTAX);
1610 rc = copy_on_write (client);
1611 if (rc)
1612 return send_error (ctx, rc);
1614 if (!client->bulk_p)
1616 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1617 if (rc)
1618 return send_error (ctx, rc);
1619 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1620 if (!result || !*result)
1622 xfree (result);
1623 return send_error (ctx, GPG_ERR_SYNTAX);
1626 len = strv_length (req->args);
1627 has_content = result[strlen ((char *)result) - 1] != '\t' && len > 1;
1628 xfree (result);
1630 else
1632 rc = xml_new_request (client, line, XML_CMD_STORE, &req);
1633 len = strv_length (req->args);
1634 has_content = line && line[strlen (line) - 1] != '\t' && len > 1;
1637 if (rc)
1638 return send_error (ctx, rc);
1640 /* Prevent passing the element content around to save some memory
1641 * (has_content). */
1642 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1644 xml_free_request (req);
1645 return send_error (ctx, GPG_ERR_INV_VALUE);
1648 if (has_content || !*req->args[len-1])
1650 content = req->args[len-1];
1651 req->args[len-1] = NULL;
1654 if (strv_length (req->args) > 1)
1656 rc = xml_check_recursion (client, req);
1657 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1658 goto fail;
1661 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1663 if (!rc && len > 1)
1665 rc = xml_is_element_owner (client, parent);
1666 if (!rc)
1668 n = xml_find_text_node (parent->children);
1669 if (n)
1670 xmlNodeSetContent (n, (xmlChar *) content);
1671 else
1672 xmlNodeAddContent (parent, (xmlChar *) content);
1674 (void)xml_update_element_mtime (client, parent);
1675 (void)update_element_expirey (client, parent);
1679 fail:
1680 xfree (content);
1681 xml_free_request (req);
1682 return send_error (ctx, rc);
1685 static gpg_error_t
1686 xfer_data (assuan_context_t ctx, const char *line, int total)
1688 struct client_s *client = assuan_get_pointer (ctx);
1689 int to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1690 int sent = 0;
1691 gpg_error_t rc = 0;
1693 if (!(client->flags & FLAG_LOCK_CMD))
1694 rc = unlock_file_mutex (client, 0);
1695 if (rc && rc != GPG_ERR_NOT_LOCKED)
1696 return rc;
1698 if (client->bulk_p)
1700 client->bulk_p->result = xmalloc (total+1);
1701 if (!client->bulk_p->result)
1702 return GPG_ERR_ENOMEM;
1703 memcpy (client->bulk_p->result, line, total);
1704 client->bulk_p->result[total] = 0;
1705 client->bulk_p->result_len = total;
1706 return 0;
1709 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1710 if (rc)
1711 return rc;
1715 if (sent + to_send > total)
1716 to_send = total - sent;
1718 rc = assuan_send_data (ctx, (char *) line + sent, to_send);
1719 if (!rc)
1720 sent += to_send;
1722 while (!rc && sent < total);
1724 return rc;
1727 static gpg_error_t
1728 do_get (assuan_context_t ctx, char *line)
1730 struct client_s *client = assuan_get_pointer (ctx);
1731 gpg_error_t rc;
1732 struct xml_request_s *req;
1733 xmlNodePtr n;
1735 if (!line || !*line)
1736 return GPG_ERR_SYNTAX;
1738 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1739 if (rc)
1740 return rc;
1742 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1743 if (!rc)
1745 if (n && n->children)
1747 xmlNodePtr tmp = n;
1749 n = xml_find_text_node (n->children);
1750 if (!n || !n->content || !*n->content)
1751 rc = GPG_ERR_NO_DATA;
1752 else
1754 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1755 if (!rc)
1757 xmlChar *expire = xml_attribute_value (tmp,
1758 (xmlChar *)"_expire");
1759 if (expire)
1761 time_t now = time (NULL);
1762 time_t e;
1763 char *p;
1765 errno = 0;
1766 e = strtoul ((char *)expire, &p, 10);
1767 if (errno || *p || e == ULONG_MAX || *expire == '-')
1768 log_write (_("invalid expire attribute value: %s"),
1769 expire);
1770 else if (now >= e)
1772 pthread_cleanup_push (xmlFree, expire);
1773 rc = send_status (ctx, STATUS_EXPIRE, "%lu 0", e);
1774 pthread_cleanup_pop (0);
1777 xmlFree (expire);
1782 else
1783 rc = GPG_ERR_NO_DATA;
1786 xml_free_request (req);
1787 return rc;
1790 static gpg_error_t
1791 get_command (assuan_context_t ctx, char *line)
1793 struct client_s *client = assuan_get_pointer (ctx);
1794 gpg_error_t rc;
1795 struct argv_s *args[] = {
1796 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1797 NULL
1800 rc = parse_options (&line, args, client, 1);
1801 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1802 rc = GPG_ERR_SYNTAX;
1803 if (rc)
1804 return send_error (ctx, rc);
1806 if (client->opts & OPT_INQUIRE)
1808 unsigned char *result;
1809 size_t len;
1811 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1812 if (rc)
1813 return send_error (ctx, rc);
1815 pthread_cleanup_push ((void *)xfree, result);
1816 rc = do_get (ctx, (char *)result);
1817 pthread_cleanup_pop (1);
1819 else
1820 rc = do_get (ctx, line);
1822 return send_error (ctx, rc);
1825 static void list_command_free1 (void *arg);
1826 static gpg_error_t
1827 realpath_command (assuan_context_t ctx, char *line)
1829 gpg_error_t rc;
1830 char **realpath = NULL;
1831 struct client_s *client = assuan_get_pointer (ctx);
1832 struct argv_s *args[] = {
1833 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1834 NULL
1837 rc = parse_options (&line, args, client, 1);
1838 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1839 rc = GPG_ERR_SYNTAX;
1840 if (rc)
1841 return send_error (ctx, rc);
1843 if (client->opts & OPT_INQUIRE)
1845 unsigned char *result;
1846 size_t len;
1848 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1849 if (rc)
1850 return send_error (ctx, rc);
1852 pthread_cleanup_push ((void *)xfree, result);
1853 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1854 pthread_cleanup_pop (1);
1856 else
1857 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1858 &realpath, &rc);
1860 if (!rc)
1862 char *tmp = strv_join ((char *)"\t", realpath);
1864 strv_free (realpath);
1865 if (!tmp)
1866 return send_error (ctx, GPG_ERR_ENOMEM);
1868 pthread_cleanup_push ((void *)xfree, tmp);
1869 rc = xfer_data (ctx, tmp, strlen (tmp));
1870 pthread_cleanup_pop (1);
1873 return send_error (ctx, rc);
1876 static void
1877 list_command_free1 (void *arg)
1879 if (arg)
1880 string_free ((struct string_s *) arg, 1);
1883 static gpg_error_t
1884 parse_list_opt_recurse (void *data, void *value)
1886 struct client_s *client = data;
1888 (void)value;
1889 client->opts |= OPT_LIST_RECURSE;
1890 return 0;
1893 static gpg_error_t
1894 parse_opt_verbose (void *data, void *value)
1896 struct client_s *client = data;
1898 (void)value;
1899 client->opts |= OPT_VERBOSE;
1900 return 0;
1903 static gpg_error_t
1904 list_path_once (struct client_s *client, char *line,
1905 struct element_list_s *elements, struct string_s *result)
1907 gpg_error_t rc;
1909 rc = xml_create_path_list (client, client->doc, NULL, elements, line, 0);
1910 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1911 rc = 0;
1913 if (!rc)
1915 int total = slist_length (elements->list);
1917 if (total)
1919 int i;
1921 for (i = 0; i < total; i++)
1923 char *tmp = slist_nth_data (elements->list, i);
1925 string_append_printf (result, "%s%s", tmp,
1926 i + 1 == total ? "" : "\n");
1929 else
1930 rc = GPG_ERR_NO_DATA;
1933 return rc;
1936 static gpg_error_t
1937 do_list (assuan_context_t ctx, char *line)
1939 struct client_s *client = assuan_get_pointer (ctx);
1940 gpg_error_t rc = GPG_ERR_NO_DATA;
1941 struct element_list_s *elements = NULL;
1943 if (!line || !*line)
1945 struct string_s *str = string_new (NULL);
1946 xmlNodePtr n;
1948 if (!str)
1949 return GPG_ERR_ENOMEM;
1951 pthread_cleanup_push ((void *)list_command_free1, str);
1952 n = xmlDocGetRootElement (client->doc);
1953 for (n = n->children; n; n = n->next)
1955 xmlChar *name;
1957 if (n->type != XML_ELEMENT_NODE)
1958 continue;
1960 name = xmlGetProp (n, (xmlChar *)"_name");
1961 if (!name)
1963 rc = GPG_ERR_ENOMEM;
1964 break;
1967 elements = xcalloc (1, sizeof (struct element_list_s));
1968 if (!elements)
1970 xmlFree (name);
1971 rc = GPG_ERR_ENOMEM;
1972 break;
1975 elements->prefix = string_new (NULL);
1976 if (!elements->prefix)
1978 xmlFree (name);
1979 xml_free_element_list (elements);
1980 rc = GPG_ERR_ENOMEM;
1981 break;
1984 elements->recurse = client->opts & OPT_LIST_RECURSE;
1985 elements->root_only = !elements->recurse;
1986 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1987 rc = list_path_once (client, (char *)name, elements, str);
1988 xmlFree (name);
1989 pthread_cleanup_pop (1);
1990 if (rc)
1991 break;
1993 if (n->next)
1994 string_append (str, "\n");
1997 if (!rc)
1998 rc = xfer_data (ctx, str->str, str->len);
2000 pthread_cleanup_pop (1);
2001 return rc;
2004 elements = xcalloc (1, sizeof (struct element_list_s));
2005 if (!elements)
2006 return GPG_ERR_ENOMEM;
2008 elements->prefix = string_new (NULL);
2009 if (!elements->prefix)
2011 xml_free_element_list (elements);
2012 return GPG_ERR_ENOMEM;
2015 elements->recurse = client->opts & OPT_LIST_RECURSE;
2016 pthread_cleanup_push ((void *)xml_free_element_list, elements);
2017 struct string_s *str = string_new (NULL);
2018 pthread_cleanup_push ((void *)list_command_free1, str);
2019 rc = list_path_once (client, line, elements, str);
2020 if (!rc)
2021 rc = xfer_data (ctx, str->str, str->len);
2023 pthread_cleanup_pop (1);
2024 pthread_cleanup_pop (1);
2025 return rc;
2028 static gpg_error_t
2029 list_command (assuan_context_t ctx, char *line)
2031 struct client_s *client = assuan_get_pointer (ctx);
2032 gpg_error_t rc;
2033 struct argv_s *args[] = {
2034 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2035 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2036 /* These are deprecated but kept for backward compatibility with older
2037 * clients. */
2038 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
2039 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
2040 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2041 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
2042 NULL
2045 if (disable_list_and_dump == 1)
2046 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2048 rc = parse_options (&line, args, client, 1);
2049 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2050 rc = GPG_ERR_SYNTAX;
2051 if (rc)
2052 return send_error (ctx, rc);
2054 if (client->opts & OPT_INQUIRE)
2056 unsigned char *result;
2057 size_t len;
2059 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2060 if (rc)
2061 return send_error (ctx, rc);
2063 pthread_cleanup_push ((void *)xfree, result);
2064 rc = do_list (ctx, (char *)result);
2065 pthread_cleanup_pop (1);
2067 else
2068 rc = do_list (ctx, line);
2070 return send_error (ctx, rc);
2073 #define RESUMABLE_ERROR(rc) (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES \
2074 || rc == GPG_ERR_ELEMENT_NOT_FOUND || !rc)
2076 * args[0] - element path
2078 static gpg_error_t
2079 attribute_list (assuan_context_t ctx, char **args)
2081 struct client_s *client = assuan_get_pointer (ctx);
2082 char **attrlist = NULL;
2083 int i = 0;
2084 int target = 0;
2085 xmlAttrPtr a;
2086 xmlNodePtr n, an, r;
2087 char *line;
2088 gpg_error_t rc;
2089 struct xml_request_s *req;
2091 if (!args || !args[0] || !*args[0])
2092 return GPG_ERR_SYNTAX;
2094 rc = xml_new_request (client, args[0], XML_CMD_ATTR_LIST, &req);
2095 if (rc)
2096 return rc;
2098 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2099 xml_free_request (req);
2100 if (rc)
2101 return rc;
2103 gpg_error_t acl_rc = 0;
2104 again:
2105 acl_rc = xml_acl_check (client, n);
2106 for (a = n->properties; a; a = a->next)
2108 char **pa;
2109 int reserved = xml_reserved_attribute ((char *)a->name);
2111 if (acl_rc == GPG_ERR_EACCES && !reserved)
2112 continue;
2113 else if (acl_rc && acl_rc != GPG_ERR_EACCES)
2115 rc = acl_rc;
2116 break;
2119 if (reserved && target)
2120 continue;
2122 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
2123 if (!pa)
2125 log_write ("%s(%i): %s", __FILE__, __LINE__,
2126 pwmd_strerror (GPG_ERR_ENOMEM));
2127 rc = GPG_ERR_ENOMEM;
2128 break;
2131 attrlist = pa;
2132 an = a->children;
2133 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
2134 ? (char *)an->content : "");
2136 if (!attrlist[i])
2138 log_write ("%s(%i): %s", __FILE__, __LINE__,
2139 pwmd_strerror (GPG_ERR_ENOMEM));
2140 rc = GPG_ERR_ENOMEM;
2141 break;
2144 attrlist[++i] = NULL;
2147 if (!rc && !attrlist)
2148 return GPG_ERR_NO_DATA;
2150 if (!rc && !target)
2152 r = xml_resolve_path (client, client->doc, (xmlChar *)args[0], NULL, &rc);
2153 if (RESUMABLE_ERROR (rc))
2155 rc = 0;
2156 if (r && r != n)
2158 target = 1;
2159 n = r;
2160 goto again;
2165 pthread_cleanup_push ((void *)req_free, attrlist);
2167 if (!rc)
2169 line = strv_join ("\n", attrlist);
2170 if (line)
2172 pthread_cleanup_push ((void *)xfree, line);
2173 rc = xfer_data (ctx, line, strlen (line));
2174 pthread_cleanup_pop (1);
2176 else
2178 log_write ("%s(%i): %s", __FILE__, __LINE__,
2179 pwmd_strerror (GPG_ERR_ENOMEM));
2180 rc = GPG_ERR_ENOMEM;
2184 pthread_cleanup_pop (1);
2185 return rc;
2189 * args[0] - attribute
2190 * args[1] - element path
2192 static gpg_error_t
2193 attribute_delete (struct client_s *client, char **args)
2195 gpg_error_t rc;
2196 xmlNodePtr n;
2198 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2199 return GPG_ERR_SYNTAX;
2201 rc = xml_protected_attr (args[0]);
2202 if (rc || !strcmp (args[0], "_target"))
2203 return rc ? rc : GPG_ERR_EPERM;
2205 rc = copy_on_write (client);
2206 if (rc)
2207 return rc;
2209 if (!xml_reserved_attribute (args[0]))
2210 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2211 else
2213 struct xml_request_s *req;
2215 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2216 if (rc)
2217 return rc;
2219 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2220 xml_free_request (req);
2223 if (!rc)
2224 rc = xml_is_element_owner (client, n);
2226 if (!rc)
2227 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
2229 return rc;
2233 * Creates the "_target" attribute. When other commands encounter an element
2234 * with this attribute they follow the "_target" after appending remaining
2235 * elements from the original element path to the target. The exception is the
2236 * ATTR command that operates on the element itself (for reserved attribute
2237 * names) and not the target.
2239 * If the source element path doesn't exist when using 'ATTR SET target', it is
2240 * created, but the destination element path must exist. This is simliar to the
2241 * ls(1) command: ln -s src dst.
2243 * args[0] - source element path
2244 * args[1] - destination element path
2246 static gpg_error_t
2247 set_target_attribute (struct client_s *client, char **args)
2249 struct xml_request_s *req = NULL;
2250 char **src, **dst;
2251 gpg_error_t rc;
2252 xmlNodePtr n;
2254 if (!args || !args[0] || !args[1])
2255 return GPG_ERR_SYNTAX;
2257 src = str_split (args[0], "\t", 0);
2258 if (!src)
2259 return GPG_ERR_SYNTAX;
2261 if (!xml_valid_element_path (src, 0))
2263 strv_free (src);
2264 return GPG_ERR_INV_VALUE;
2267 dst = str_split (args[1], "\t", 0);
2268 if (!dst)
2270 strv_free (src);
2271 return GPG_ERR_SYNTAX;
2274 rc = copy_on_write (client);
2275 if (rc)
2276 goto fail;
2278 // Be sure the destination element path exists. */
2279 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2280 if (rc)
2281 goto fail;
2283 (void)xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2284 if (rc && rc != GPG_ERR_EACCES)
2285 goto fail;
2287 xml_free_request (req);
2288 req = NULL;
2290 if (!strcmp (args[0], args[1]))
2292 rc = GPG_ERR_EEXIST;
2293 goto fail;
2296 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
2297 if (rc)
2298 goto fail;
2300 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2301 if (rc && rc != GPG_ERR_EACCES)
2302 goto fail;
2304 if (!rc)
2306 rc = xml_add_attribute (client, n, "_target", args[1]);
2307 if (!rc)
2309 rc = xml_remove_user_attributes (client, n);
2310 if (!rc)
2311 rc = xml_unlink_node (client, n->children);
2315 fail:
2316 strv_free (src);
2317 strv_free (dst);
2318 xml_free_request (req);
2319 return rc;
2323 * args[0] - attribute
2324 * args[1] - element path
2326 static gpg_error_t
2327 attribute_get (assuan_context_t ctx, char **args)
2329 struct client_s *client = assuan_get_pointer (ctx);
2330 xmlNodePtr n;
2331 xmlChar *a;
2332 gpg_error_t rc;
2333 struct xml_request_s *req;
2335 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2336 return GPG_ERR_SYNTAX;
2338 if (!xml_reserved_attribute (args[0]))
2339 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2340 else
2342 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2343 if (rc)
2344 return rc;
2346 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2347 xml_free_request (req);
2350 if (rc)
2351 return rc;
2353 a = xmlGetProp (n, (xmlChar *) args[0]);
2354 if (!a)
2355 return GPG_ERR_NOT_FOUND;
2357 pthread_cleanup_push ((void *)xmlFree, a);
2359 if (*a)
2360 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2361 else
2362 rc = GPG_ERR_NO_DATA;
2364 pthread_cleanup_pop (1);
2365 return rc;
2369 * args[0] - attribute
2370 * args[1] - element path
2371 * args[2] - value
2373 static gpg_error_t
2374 attribute_set (struct client_s *client, char **args)
2376 struct xml_request_s *req;
2377 gpg_error_t rc;
2378 xmlNodePtr n;
2380 if (!args || !args[0] || !args[1])
2381 return GPG_ERR_SYNTAX;
2384 * Reserved attribute names.
2386 if ((rc = xml_protected_attr (args[0])))
2387 return rc;
2388 else if (!strcmp (args[0], "_target"))
2389 return set_target_attribute (client, args + 1);
2390 else if (!xml_valid_attribute (args[0]))
2391 return GPG_ERR_INV_VALUE;
2393 if (!xml_valid_attribute_value (args[2]))
2394 return GPG_ERR_INV_VALUE;
2396 rc = copy_on_write (client);
2397 if (rc)
2398 return rc;
2400 if (!xml_reserved_attribute (args[0]))
2402 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2403 if (!rc)
2405 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2406 if (!rc)
2408 rc = xml_check_recursion (client, req);
2409 xml_free_request (req);
2413 else
2415 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2416 if (rc)
2417 return rc;
2419 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2420 xml_free_request (req);
2423 if (!rc)
2424 rc = xml_is_element_owner (client, n);
2426 if (!rc)
2427 rc = xml_add_attribute (client, n, args[0], args[2]);
2429 return rc;
2433 * req[0] - command
2434 * req[1] - attribute name or element path if command is LIST
2435 * req[2] - element path
2436 * req[2] - element path or value
2439 static gpg_error_t
2440 do_attr (assuan_context_t ctx, char *line)
2442 struct client_s *client = assuan_get_pointer (ctx);
2443 gpg_error_t rc = 0;
2444 char **req;
2446 if (!line || !*line)
2447 return GPG_ERR_SYNTAX;
2449 req = str_split (line, " ", 4);
2450 if (!req || !req[0] || !req[1])
2452 strv_free (req);
2453 return GPG_ERR_SYNTAX;
2456 pthread_cleanup_push ((void *)req_free, req);
2458 if (strcasecmp (req[0], "SET") == 0)
2459 rc = attribute_set (client, req + 1);
2460 else if (strcasecmp (req[0], "GET") == 0)
2461 rc = attribute_get (ctx, req + 1);
2462 else if (strcasecmp (req[0], "DELETE") == 0)
2463 rc = attribute_delete (client, req + 1);
2464 else if (strcasecmp (req[0], "LIST") == 0)
2465 rc = attribute_list (ctx, req + 1);
2466 else
2467 rc = GPG_ERR_SYNTAX;
2469 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2470 pthread_cleanup_pop (1);
2471 return rc;
2474 static gpg_error_t
2475 attr_command (assuan_context_t ctx, char *line)
2477 struct client_s *client = assuan_get_pointer (ctx);
2478 gpg_error_t rc;
2479 struct argv_s *args[] = {
2480 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2481 NULL
2484 rc = parse_options (&line, args, client, 1);
2485 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2486 rc = GPG_ERR_SYNTAX;
2487 if (rc)
2488 return send_error (ctx, rc);
2490 if (client->opts & OPT_INQUIRE)
2492 unsigned char *result;
2493 size_t len;
2495 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2496 if (rc)
2497 return send_error (ctx, rc);
2499 pthread_cleanup_push ((void *)xfree, result);
2500 rc = do_attr (ctx, (char *)result);
2501 pthread_cleanup_pop (1);
2503 else
2504 rc = do_attr (ctx, line);
2506 return send_error (ctx, rc);
2509 static gpg_error_t
2510 parse_iscached_opt_lock (void *data, void *value)
2512 struct client_s *client = data;
2514 (void) value;
2515 client->opts |= OPT_LOCK;
2516 return 0;
2519 static gpg_error_t
2520 parse_iscached_opt_agent (void *data, void *value)
2522 struct client_s *client = data;
2524 (void) value;
2525 client->opts |= OPT_CACHE_AGENT;
2526 return 0;
2529 static gpg_error_t
2530 parse_iscached_opt_sign (void *data, void *value)
2532 struct client_s *client = data;
2534 (void) value;
2535 client->opts |= OPT_CACHE_SIGN;
2536 return 0;
2539 static gpg_error_t
2540 iscached_command (assuan_context_t ctx, char *line)
2542 struct client_s *client = assuan_get_pointer (ctx);
2543 gpg_error_t rc;
2544 int defer = 0;
2545 struct argv_s *args[] = {
2546 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2547 &(struct argv_s) {"agent", OPTION_TYPE_NOARG, parse_iscached_opt_agent},
2548 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_iscached_opt_sign},
2549 NULL
2552 if (!line || !*line)
2553 return send_error (ctx, GPG_ERR_SYNTAX);
2555 rc = parse_options (&line, args, client, 1);
2556 if (rc)
2557 return send_error (ctx, rc);
2558 else if (!valid_filename (line))
2559 return send_error (ctx, GPG_ERR_INV_VALUE);
2561 if (!(client->flags & FLAG_OPEN)
2562 && ((client->opts & OPT_CACHE_AGENT) || (client->opts & OPT_CACHE_SIGN)))
2563 return send_error (ctx, GPG_ERR_INV_STATE);
2565 rc = cache_iscached (line, &defer, (client->opts & OPT_CACHE_AGENT),
2566 (client->opts & OPT_CACHE_SIGN));
2567 if (!rc && defer)
2568 rc = GPG_ERR_NO_DATA;
2570 if (!rc)
2572 struct cache_data_s *cdata = cache_get_data (line, NULL);
2574 if (cdata)
2576 rc = validate_checksum (client, line, cdata, NULL, NULL, 1);
2577 if (rc == GPG_ERR_CHECKSUM)
2578 rc = GPG_ERR_NO_DATA;
2582 if (client->opts & OPT_LOCK
2583 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA
2584 || gpg_err_code (rc) == GPG_ERR_ENOENT))
2586 gpg_error_t trc = rc;
2588 if (client->filename && strcmp (line, client->filename))
2589 reset_client (client);
2591 xfree (client->filename);
2592 client->filename = str_dup (line);
2593 rc = do_lock (client, 1);
2594 if (!rc)
2595 rc = trc;
2598 return send_error (ctx, rc);
2601 static gpg_error_t
2602 clearcache_command (assuan_context_t ctx, char *line)
2604 struct client_s *client = assuan_get_pointer (ctx);
2605 gpg_error_t rc = 0, all_rc = 0;
2606 int i;
2607 int t;
2608 int all = 0;
2609 struct client_thread_s *once = NULL;
2610 unsigned count;
2612 cache_lock ();
2613 pthread_cleanup_push (cache_release_mutex, NULL);
2614 count = cache_file_count ();
2615 MUTEX_LOCK (&cn_mutex);
2616 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
2618 if (!line || !*line)
2619 all = 1;
2621 t = slist_length (cn_thread_list);
2623 for (i = 0; i < t; i++)
2625 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2626 assuan_peercred_t peer;
2628 if (!thd->cl)
2629 continue;
2631 /* Lock each connected clients' file mutex to prevent any other client
2632 * from accessing the cache entry (the file mutex is locked upon
2633 * command startup). The cache for the entry is not cleared if the
2634 * file mutex is locked by another client to prevent this function
2635 * from blocking. Rather, it returns an error.
2637 if (all)
2639 if (thd->cl->filename)
2641 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2642 /* The current client doesn't have permission to open the other
2643 * filename do to "access" configuration parameter in a filename
2644 * section. Since we are clearning all cache entries the error
2645 * will be returned later during cache_clear(). */
2646 if (rc)
2648 rc = 0;
2649 continue;
2652 else // Idle client without opened file?
2653 continue;
2655 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2656 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2658 /* The current client owns the lock. */
2659 if (pthread_equal (pthread_self (), thd->tid))
2660 rc = 0;
2661 else
2663 if (cache_iscached (thd->cl->filename, NULL, 0, 0)
2664 == GPG_ERR_NO_DATA)
2666 rc = 0;
2667 continue;
2670 /* The cache entry will be cleared when the other client
2671 * disconnects and cache_timer_thread() does its thing. */
2672 cache_defer_clear (thd->cl->filename);
2675 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2677 rc = 0;
2678 continue;
2681 if (!rc)
2683 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2684 cache_unlock_mutex (thd->cl->filename, 0);
2687 if (rc)
2688 all_rc = rc;
2690 rc = 0;
2692 else
2694 /* A single data filename was specified. Lock only this data file
2695 * mutex and free the cache entry. */
2696 rc = do_validate_peer (ctx, line, &peer);
2697 if (rc == GPG_ERR_FORBIDDEN)
2698 rc = peer_is_invoker (client);
2700 if (rc == GPG_ERR_EACCES)
2701 rc = GPG_ERR_FORBIDDEN;
2703 if (!rc && thd->cl->filename && !strcmp (thd->cl->filename , line))
2705 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2706 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2708 /* The current client owns the lock. */
2709 if (pthread_equal (pthread_self (), thd->tid))
2710 rc = 0;
2713 if (!rc)
2715 once = thd;
2716 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2717 cache_unlock_mutex (thd->cl->filename, 0);
2719 else
2720 cache_defer_clear (thd->cl->filename);
2722 /* Found a client with the opened file. The cache entry has been
2723 * either cleared (self) or defered to be cleared. */
2724 break;
2729 /* Only connected clients' cache entries have been cleared. Now clear any
2730 * remaining cache entries without clients but only if there wasn't an
2731 * error from above since this would defeat the locking check of the
2732 * remaining entries. */
2733 if (all && !all_rc && cache_file_count ())
2735 rc = cache_clear (client, NULL, 1, 0);
2736 if (rc == GPG_ERR_EACCES)
2737 rc = GPG_ERR_FORBIDDEN;
2740 /* No clients are using the specified file. */
2741 else if (!all_rc && !rc && !once)
2742 rc = cache_clear (NULL, line, 1, 0);
2744 /* Release the connection mutex. */
2745 pthread_cleanup_pop (1);
2747 if (!rc || (cache_file_count () && count != cache_file_count ()))
2748 send_status_all (STATUS_CACHE, NULL);
2750 /* Release the cache mutex. */
2751 pthread_cleanup_pop (1);
2753 /* One or more files were locked while clearing all cache entries. */
2754 if (all_rc)
2755 rc = all_rc;
2757 return send_error (ctx, rc);
2760 static gpg_error_t
2761 cachetimeout_command (assuan_context_t ctx, char *line)
2763 struct client_s *client = assuan_get_pointer (ctx);
2764 long timeout;
2765 char **req = str_split (line, " ", 0);
2766 char *p;
2767 gpg_error_t rc = 0;
2769 if (!(client->flags & FLAG_OPEN))
2770 return send_error (ctx, GPG_ERR_INV_STATE);
2772 if (!req || !*req || strv_length (req) > 1)
2774 strv_free (req);
2775 return send_error (ctx, GPG_ERR_SYNTAX);
2778 errno = 0;
2779 timeout = strtol (req[0], &p, 10);
2780 if (errno != 0 || *p || timeout < (long)-1)
2781 rc = GPG_ERR_SYNTAX;
2783 if (!rc)
2785 rc = cache_set_timeout (client->filename, timeout);
2786 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2788 rc = 0;
2789 MUTEX_LOCK (&rcfile_mutex);
2790 config_set_long_param (&global_config, client->filename,
2791 "cache_timeout", req[0]);
2792 MUTEX_UNLOCK (&rcfile_mutex);
2796 strv_free (req);
2797 return send_error (ctx, rc);
2800 static gpg_error_t
2801 dump_command (assuan_context_t ctx, char *line)
2803 xmlChar *xml;
2804 int len;
2805 struct client_s *client = assuan_get_pointer (ctx);
2806 gpg_error_t rc;
2808 if (disable_list_and_dump == 1)
2809 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2811 if (line && *line)
2812 return send_error (ctx, GPG_ERR_SYNTAX);
2814 rc = peer_is_invoker(client);
2815 if (rc)
2816 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
2818 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2820 if (!xml)
2822 log_write ("%s(%i): %s", __FILE__, __LINE__,
2823 pwmd_strerror (GPG_ERR_ENOMEM));
2824 return send_error (ctx, GPG_ERR_ENOMEM);
2827 pthread_cleanup_push ((void *)xmlFree, xml);
2828 rc = xfer_data (ctx, (char *) xml, len);
2829 pthread_cleanup_pop (1);
2830 return send_error (ctx, rc);
2833 static gpg_error_t
2834 getconfig_command (assuan_context_t ctx, char *line)
2836 struct client_s *client = assuan_get_pointer (ctx);
2837 gpg_error_t rc = 0;
2838 char filename[255] = { 0 }, param[747] = { 0 };
2839 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2841 if (!line || !*line)
2842 return send_error (ctx, GPG_ERR_SYNTAX);
2844 if (strchr (line, ' '))
2846 int ret = sscanf (line, " %254[^ ] %746c", filename, param);
2848 if (ret <= 0)
2849 return send_error (ctx, gpg_error_from_syserror());
2850 paramp = param;
2851 fp = filename;
2854 if (fp && !valid_filename (fp))
2855 return send_error (ctx, GPG_ERR_INV_VALUE);
2857 paramp = str_down (paramp);
2858 p = config_get_value (fp ? fp : "global", paramp);
2859 if (!p)
2860 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2862 tmp = expand_homedir (p);
2863 xfree (p);
2864 if (!tmp)
2866 log_write ("%s(%i): %s", __FILE__, __LINE__,
2867 pwmd_strerror (GPG_ERR_ENOMEM));
2868 return send_error (ctx, GPG_ERR_ENOMEM);
2871 p = tmp;
2872 pthread_cleanup_push ((void *)xfree, p);
2873 rc = xfer_data (ctx, p, strlen (p));
2874 pthread_cleanup_pop (1);
2875 return send_error (ctx, rc);
2878 struct xpath_s
2880 xmlXPathContextPtr xp;
2881 xmlXPathObjectPtr result;
2882 xmlBufferPtr buf;
2883 char **req;
2886 static void
2887 xpath_command_free (void *arg)
2889 struct xpath_s *xpath = arg;
2891 if (!xpath)
2892 return;
2894 req_free (xpath->req);
2896 if (xpath->buf)
2897 xmlBufferFree (xpath->buf);
2899 if (xpath->result)
2900 xmlXPathFreeObject (xpath->result);
2902 if (xpath->xp)
2903 xmlXPathFreeContext (xpath->xp);
2906 static gpg_error_t
2907 do_xpath (assuan_context_t ctx, char *line)
2909 gpg_error_t rc;
2910 struct client_s *client = assuan_get_pointer (ctx);
2911 struct xpath_s _x = { 0 };
2912 struct xpath_s *xpath = &_x;
2914 if (!line || !*line)
2915 return GPG_ERR_SYNTAX;
2917 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2919 if (strv_printf (&xpath->req, "%s", line) == 0)
2920 return GPG_ERR_ENOMEM;
2923 if (xpath->req[1])
2925 rc = copy_on_write (client);
2926 if (rc)
2927 goto fail;
2930 xpath->xp = xmlXPathNewContext (client->doc);
2931 if (!xpath->xp)
2933 rc = GPG_ERR_BAD_DATA;
2934 goto fail;
2937 xpath->result =
2938 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2939 if (!xpath->result)
2941 rc = GPG_ERR_BAD_DATA;
2942 goto fail;
2945 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2947 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2948 goto fail;
2951 rc = xml_recurse_xpath_nodeset (client, client->doc,
2952 xpath->result->nodesetval,
2953 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2954 NULL);
2955 if (rc)
2956 goto fail;
2957 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2959 rc = GPG_ERR_NO_DATA;
2960 goto fail;
2962 else if (xpath->req[1])
2964 rc = 0;
2965 goto fail;
2968 pthread_cleanup_push ((void *)xpath_command_free, &xpath);
2969 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2970 xmlBufferLength (xpath->buf));
2971 pthread_cleanup_pop (0);
2972 fail:
2973 xpath_command_free (xpath);
2974 return rc;
2977 static gpg_error_t
2978 xpath_command (assuan_context_t ctx, char *line)
2980 struct client_s *client = assuan_get_pointer (ctx);
2981 gpg_error_t rc;
2982 struct argv_s *args[] = {
2983 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2984 NULL
2987 if (disable_list_and_dump == 1)
2988 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2990 rc = peer_is_invoker(client);
2991 if (rc)
2992 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
2994 rc = parse_options (&line, args, client, 1);
2995 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2996 rc = GPG_ERR_SYNTAX;
2997 if (rc)
2998 return send_error (ctx, rc);
3000 if (client->opts & OPT_INQUIRE)
3002 unsigned char *result;
3003 size_t len;
3005 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3006 if (rc)
3007 return send_error (ctx, rc);
3009 pthread_cleanup_push ((void *)xfree, result);
3010 rc = do_xpath (ctx, (char *)result);
3011 pthread_cleanup_pop (1);
3013 else
3014 rc = do_xpath (ctx, line);
3016 return send_error (ctx, rc);
3019 static gpg_error_t
3020 do_xpathattr (assuan_context_t ctx, char *line)
3022 struct client_s *client = assuan_get_pointer (ctx);
3023 gpg_error_t rc;
3024 char **req = NULL;
3025 int cmd = 0; //SET
3026 struct xpath_s _x = { 0 };
3027 struct xpath_s *xpath = &_x;
3029 if (!line || !*line)
3030 return GPG_ERR_SYNTAX;
3032 if ((req = str_split (line, " ", 3)) == NULL)
3033 return GPG_ERR_ENOMEM;
3035 if (!req[0])
3037 rc = GPG_ERR_SYNTAX;
3038 goto fail;
3041 if (!strcasecmp (req[0], "SET"))
3042 cmd = 0;
3043 else if (!strcasecmp (req[0], "DELETE"))
3044 cmd = 1;
3045 else
3047 rc = GPG_ERR_SYNTAX;
3048 goto fail;
3051 if (!req[1] || !req[2])
3053 rc = GPG_ERR_SYNTAX;
3054 goto fail;
3057 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
3059 rc = GPG_ERR_ENOMEM;
3060 goto fail;
3063 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
3065 rc = GPG_ERR_SYNTAX;
3066 goto fail;
3069 rc = copy_on_write (client);
3070 if (rc)
3071 goto fail;
3073 xpath->xp = xmlXPathNewContext (client->doc);
3074 if (!xpath->xp)
3076 rc = GPG_ERR_BAD_DATA;
3077 goto fail;
3080 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3081 if (!xpath->result)
3083 rc = GPG_ERR_BAD_DATA;
3084 goto fail;
3087 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3089 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3090 goto fail;
3093 rc = xml_recurse_xpath_nodeset (client, client->doc,
3094 xpath->result->nodesetval,
3095 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
3096 (xmlChar *) req[1]);
3098 fail:
3099 xpath_command_free (xpath);
3100 strv_free (req);
3101 return rc;
3104 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
3105 static gpg_error_t
3106 xpathattr_command (assuan_context_t ctx, char *line)
3108 struct client_s *client = assuan_get_pointer (ctx);
3109 gpg_error_t rc;
3110 struct argv_s *args[] = {
3111 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3112 NULL
3115 if (disable_list_and_dump == 1)
3116 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3118 rc = peer_is_invoker(client);
3119 if (rc)
3120 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
3122 rc = parse_options (&line, args, client, 1);
3123 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3124 rc = GPG_ERR_SYNTAX;
3125 if (rc)
3126 return send_error (ctx, rc);
3128 if (client->opts & OPT_INQUIRE)
3130 unsigned char *result;
3131 size_t len;
3133 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3134 if (rc)
3135 return send_error (ctx, rc);
3137 pthread_cleanup_push ((void *)xfree, result);
3138 rc = do_xpathattr (ctx, (char *)result);
3139 pthread_cleanup_pop (1);
3141 else
3142 rc = do_xpathattr (ctx, line);
3144 return send_error (ctx, rc);
3147 static gpg_error_t
3148 do_import (struct client_s *client, const char *root_element,
3149 unsigned char *content)
3151 xmlDocPtr doc = NULL;
3152 xmlNodePtr n = NULL, root;
3153 gpg_error_t rc = 0;
3154 struct string_s *str = NULL, *tstr = NULL;
3155 struct xml_request_s *req = NULL;
3157 if (!content || !*content)
3158 return GPG_ERR_SYNTAX;
3160 if (root_element)
3162 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
3163 if (rc)
3165 xfree (content);
3166 return rc;
3169 if (!xml_valid_element_path (req->args, 0))
3171 xml_free_request (req);
3172 xfree (content);
3173 return GPG_ERR_INV_VALUE;
3177 str = string_new_content ((char *)content);
3178 tstr = string_prepend (str, "<pwmd>");
3179 if (tstr)
3181 str = tstr;
3182 tstr = string_append (str, "</pwmd>");
3183 if (!tstr)
3184 rc = GPG_ERR_ENOMEM;
3185 else
3186 str = tstr;
3188 else
3189 rc = GPG_ERR_ENOMEM;
3191 if (rc)
3192 goto fail;
3194 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3195 string_free (str, 1);
3196 if (!doc)
3198 rc = GPG_ERR_BAD_DATA;
3199 goto fail;
3202 root = xmlDocGetRootElement (doc);
3203 root = root->children;
3204 if (root->type != XML_ELEMENT_NODE)
3206 rc = GPG_ERR_BAD_DATA;
3207 goto fail;
3210 rc = xml_validate_import (client, root);
3211 if (rc)
3212 goto fail;
3214 if (req)
3216 /* Create the new specified root element path, if needed. */
3217 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3218 &rc);
3219 if (rc)
3220 goto fail;
3222 /* Overwrite the children of the specified root element path. */
3223 (void)xml_unlink_node (client, n->children);
3224 n->children = NULL;
3226 else
3227 n = xmlDocGetRootElement (client->doc);
3229 if (n)
3231 xmlNodePtr copy;
3232 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
3234 if (!name)
3235 rc = GPG_ERR_BAD_DATA;
3236 else if (!req)
3238 /* No --root argument passed. Overwrite the current documents' root
3239 * element matching the root element of the imported data. */
3240 xml_free_request (req);
3241 req = NULL;
3242 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
3243 xmlFree (name);
3244 if (!rc)
3246 xmlNodePtr tmp;
3248 tmp = xml_find_elements (client, req,
3249 xmlDocGetRootElement (req->doc), &rc);
3250 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3251 goto fail;
3253 if (!rc)
3254 (void)xml_unlink_node (client, tmp);
3256 rc = 0;
3260 if (!rc)
3262 copy = xmlCopyNodeList (root);
3263 if (!copy)
3264 rc = GPG_ERR_ENOMEM;
3265 else
3267 n = xmlAddChildList (n, copy);
3268 if (!n)
3269 rc = GPG_ERR_ENOMEM;
3274 if (!rc && n && n->parent)
3275 rc = xml_update_element_mtime (client, n->parent);
3277 fail:
3278 xml_free_request (req);
3280 if (doc)
3281 xmlFreeDoc (doc);
3283 return rc;
3286 static gpg_error_t
3287 parse_import_opt_root (void *data, void *value)
3289 struct client_s *client = data;
3291 client->import_root = str_dup (value);
3292 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3295 static gpg_error_t
3296 import_command (assuan_context_t ctx, char *line)
3298 gpg_error_t rc;
3299 struct client_s *client = assuan_get_pointer (ctx);
3300 unsigned char *result;
3301 size_t len;
3302 struct argv_s *args[] = {
3303 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3304 NULL
3307 xfree (client->import_root);
3308 client->import_root = NULL;
3309 rc = parse_options (&line, args, client, client->bulk_p ? 1 : 0);
3310 if (rc)
3311 return send_error (ctx, rc);
3313 rc = copy_on_write (client);
3314 if (rc)
3315 return send_error (ctx, rc);
3317 if (!client->bulk_p)
3319 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3320 if (rc)
3322 xfree (client->import_root);
3323 client->import_root = NULL;
3324 return send_error (ctx, rc);
3326 rc = do_import (client, client->import_root, result);
3328 else
3330 char *p = str_dup (line);
3332 if (!p)
3333 rc = GPG_ERR_ENOMEM;
3334 else
3335 rc = do_import (client, client->import_root, (unsigned char *)p);
3338 xfree (client->import_root);
3339 client->import_root = NULL;
3340 return send_error (ctx, rc);
3343 static gpg_error_t
3344 do_lock (struct client_s *client, int add)
3346 gpg_error_t rc = lock_file_mutex (client, add);
3348 if (!rc)
3349 client->flags |= FLAG_LOCK_CMD;
3351 return rc;
3354 static gpg_error_t
3355 lock_command (assuan_context_t ctx, char *line)
3357 struct client_s *client = assuan_get_pointer (ctx);
3358 gpg_error_t rc;
3360 if (line && *line)
3361 return send_error (ctx, GPG_ERR_SYNTAX);
3363 rc = do_lock (client, 0);
3364 return send_error (ctx, rc);
3367 static gpg_error_t
3368 unlock_command (assuan_context_t ctx, char *line)
3370 struct client_s *client = assuan_get_pointer (ctx);
3371 gpg_error_t rc;
3373 if (line && *line)
3374 return send_error (ctx, GPG_ERR_SYNTAX);
3376 rc = unlock_file_mutex (client, 0);
3377 return send_error (ctx, rc);
3380 static void
3381 set_env (const char *name, char *buf, size_t size, const char *value)
3383 MUTEX_LOCK (&rcfile_mutex);
3384 if (!value || !*value)
3386 unsetenv (name);
3387 buf[0] = 0;
3389 else if (!buf[0] || strcmp (buf, value))
3391 snprintf (buf, size, "%s=%s", name, value);
3392 putenv (buf);
3395 MUTEX_UNLOCK (&rcfile_mutex);
3398 static gpg_error_t
3399 option_command (assuan_context_t ctx, char *line)
3401 struct client_s *client = assuan_get_pointer (ctx);
3402 gpg_error_t rc = 0;
3403 char namebuf[255] = { 0 };
3404 char *name = namebuf;
3405 char *value = NULL, *p, *tmp = NULL;
3407 p = strchr (line, '=');
3408 if (!p)
3410 strncpy (namebuf, line, sizeof(namebuf));
3411 namebuf[sizeof(namebuf)-1] = 0;
3413 else
3415 tmp = str_dup (line);
3416 if (!tmp)
3417 return send_error (ctx, GPG_ERR_ENOMEM);
3419 tmp[strlen (line) - strlen (p)] = 0;
3420 strncpy (namebuf, tmp, sizeof (namebuf));
3421 namebuf[sizeof(namebuf)-1] = 0;
3422 xfree (tmp);
3423 tmp = NULL;
3424 value = p+1;
3427 log_write2 ("OPTION name='%s' value='%s'", name, value);
3429 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3431 long n = 0;
3433 if (value)
3435 n = strtol (value, &tmp, 10);
3436 if (tmp && *tmp)
3437 return send_error (ctx, GPG_ERR_INV_VALUE);
3440 client->lock_timeout = n;
3442 else if (strcasecmp (name, (char *) "client-state") == 0)
3444 long n = 0;
3446 MUTEX_LOCK (&client->thd->status_mutex);
3447 if (value)
3449 n = strtol (value, &tmp, 10);
3450 if ((tmp && *tmp) || (n < 0 || n > 1))
3452 MUTEX_UNLOCK (&client->thd->status_mutex);
3453 return send_error (ctx, GPG_ERR_INV_VALUE);
3455 client->client_state = n;
3457 else
3458 client->client_state = 0;
3459 MUTEX_UNLOCK (&client->thd->status_mutex);
3461 else if (strcasecmp (name, (char *) "NAME") == 0)
3463 if (value && strchr (value, ' '))
3464 rc = GPG_ERR_INV_VALUE;
3465 else
3467 MUTEX_LOCK (&cn_mutex);
3468 tmp = pthread_getspecific (thread_name_key);
3469 pthread_setspecific (thread_name_key, NULL);
3470 xfree (tmp);
3471 xfree (client->thd->name);
3472 client->thd->name = NULL;
3473 if (value && *value)
3475 pthread_setspecific (thread_name_key, str_dup (value));
3476 client->thd->name = str_dup (value);
3478 MUTEX_UNLOCK (&cn_mutex);
3481 else if (strcasecmp (name, "disable-pinentry") == 0)
3483 int n = 1;
3485 if (value && *value)
3487 n = (int) strtol (value, &tmp, 10);
3488 if (*tmp || n < 0 || n > 1)
3489 return send_error (ctx, GPG_ERR_INV_VALUE);
3492 if (n)
3493 client->flags |= FLAG_NO_PINENTRY;
3494 else
3495 client->flags &= ~FLAG_NO_PINENTRY;
3497 else if (strcasecmp (name, "ttyname") == 0)
3498 set_env ("GPG_TTY", env_gpg_tty, sizeof (env_gpg_tty), value);
3499 else if (strcasecmp (name, "ttytype") == 0)
3500 set_env ("TERM", env_term, sizeof (env_term), value);
3501 else if (strcasecmp (name, "display") == 0)
3502 set_env ("DISPLAY", env_display, sizeof (env_display), value);
3503 else if (strcasecmp (name, "lc_messages") == 0)
3506 else if (strcasecmp (name, "lc_ctype") == 0)
3509 else if (strcasecmp (name, "desc") == 0)
3512 else if (strcasecmp (name, "pinentry-timeout") == 0)
3515 else
3516 rc = GPG_ERR_UNKNOWN_OPTION;
3518 return send_error (ctx, rc);
3521 static gpg_error_t
3522 do_rename (assuan_context_t ctx, char *line)
3524 struct client_s *client = assuan_get_pointer (ctx);
3525 char **args, *p;
3526 xmlNodePtr src, dst;
3527 struct string_s *str = NULL, *tstr;
3528 struct xml_request_s *req;
3529 gpg_error_t rc;
3531 if (!line || !*line)
3532 return GPG_ERR_SYNTAX;
3534 args = str_split (line, " ", 0);
3535 if (!args || strv_length (args) != 2)
3537 strv_free (args);
3538 return GPG_ERR_SYNTAX;
3541 if (!xml_valid_element ((xmlChar *) args[1]))
3543 strv_free (args);
3544 return GPG_ERR_INV_VALUE;
3547 rc = xml_new_request (client, args[0], XML_CMD_RENAME, &req);
3548 if (rc)
3550 strv_free (args);
3551 return rc;
3554 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3555 if (rc)
3556 goto fail;
3558 rc = xml_is_element_owner (client, src);
3559 if (rc)
3560 goto fail;
3562 xmlChar *a = xmlGetProp (src, (xmlChar *) "_name");
3563 if (!a)
3565 rc = GPG_ERR_ENOMEM;
3566 goto fail;
3569 /* To prevent unwanted effects:
3571 * <element _name="a"><element _name="b"/></element>
3573 * RENAME a<TAB>b b
3575 if (xmlStrEqual (a, (xmlChar *) args[1]))
3577 xmlFree (a);
3578 rc = GPG_ERR_EEXIST;
3579 goto fail;
3582 xmlFree (a);
3583 str = string_new (args[0]);
3584 if (!str)
3586 rc = GPG_ERR_ENOMEM;
3587 goto fail;
3590 p = strrchr (str->str, '\t');
3591 if (p)
3592 tstr = string_truncate (str, strlen (str->str)-strlen (p));
3593 else
3594 tstr = string_truncate (str, 0);
3596 if (!tstr)
3598 string_free (str, 1);
3599 rc = GPG_ERR_ENOMEM;
3600 goto fail;
3603 str = tstr;
3604 tstr = string_append_printf (str, "%s%s", str->len ? "\t" : "", args[1]);
3605 if (!tstr)
3607 string_free (str, 1);
3608 rc = GPG_ERR_ENOMEM;
3609 goto fail;
3612 str = tstr;
3613 xml_free_request (req);
3614 rc = xml_new_request (client, str->str, XML_CMD_RENAME, &req);
3615 string_free (str, 1);
3616 if (rc)
3618 req = NULL;
3619 goto fail;
3622 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3623 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3624 goto fail;
3626 rc = 0;
3628 /* Target may exist:
3630 * <element _name="a"/>
3631 * <element _name="b" target="a"/>
3633 * RENAME b a
3635 if (src == dst)
3637 rc = GPG_ERR_EEXIST;
3638 goto fail;
3641 if (dst)
3643 rc = xml_is_element_owner (client, dst);
3644 if (rc)
3645 goto fail;
3647 rc = xml_add_attribute (client, src, "_name", args[1]);
3648 if (!rc)
3649 xml_unlink_node (client, dst);
3651 else
3652 rc = xml_add_attribute (client, src, "_name", args[1]);
3654 fail:
3655 xml_free_request (req);
3656 strv_free (args);
3657 return rc;
3660 static gpg_error_t
3661 rename_command (assuan_context_t ctx, char *line)
3663 struct client_s *client = assuan_get_pointer (ctx);
3664 gpg_error_t rc;
3665 struct argv_s *args[] = {
3666 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3667 NULL
3670 rc = parse_options (&line, args, client, 1);
3671 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3672 rc = GPG_ERR_SYNTAX;
3673 if (rc)
3674 return send_error (ctx, rc);
3676 rc = copy_on_write (client);
3677 if (rc)
3678 return send_error (ctx, rc);
3680 if (client->opts & OPT_INQUIRE)
3682 unsigned char *result;
3683 size_t len;
3685 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3686 if (rc)
3687 return send_error (ctx, rc);
3689 pthread_cleanup_push ((void *)xfree, result);
3690 rc = do_rename (ctx, (char *)result);
3691 pthread_cleanup_pop (1);
3693 else
3694 rc = do_rename (ctx, line);
3696 return send_error (ctx, rc);
3699 static gpg_error_t
3700 do_copy (assuan_context_t ctx, char *line)
3702 struct client_s *client = assuan_get_pointer (ctx);
3703 char **args, **targs;
3704 xmlNodePtr src, dst, tree = NULL;
3705 struct xml_request_s *req;
3706 gpg_error_t rc;
3708 if (!line || !*line)
3709 return GPG_ERR_SYNTAX;
3711 args = str_split (line, " ", 0);
3712 if (!args || strv_length (args) != 2)
3714 strv_free (args);
3715 return GPG_ERR_SYNTAX;
3718 targs = str_split (args[1], "\t", 0);
3719 if (!targs)
3721 strv_free (args);
3722 return GPG_ERR_SYNTAX;
3725 if (!xml_valid_element_path (targs, 0))
3727 strv_free (args);
3728 strv_free (targs);
3729 return GPG_ERR_INV_VALUE;
3731 strv_free (targs);
3733 rc = xml_new_request (client, args[0], XML_CMD_NONE, &req);
3734 if (rc)
3736 strv_free (args);
3737 return rc;
3740 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3741 if (rc)
3742 goto fail;
3744 tree = xmlCopyNodeList (src);
3745 if (!tree)
3747 rc = GPG_ERR_ENOMEM;
3748 goto fail;
3751 xml_free_request (req);
3752 /* Create the destination element path if it does not exist. */
3753 rc = xml_new_request (client, args[1], XML_CMD_STORE, &req);
3754 if (rc)
3756 req = NULL;
3757 goto fail;
3760 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3761 if (rc)
3762 goto fail;
3764 rc = xml_is_element_owner (client, dst);
3765 if (rc)
3766 goto fail;
3768 rc = xml_validate_target (client, req->doc, args[1], src);
3769 if (rc || src == dst)
3771 rc = rc ? rc : GPG_ERR_EEXIST;
3772 goto fail;
3775 /* Merge any attributes from the src node to the initial dst node. */
3776 for (xmlAttrPtr attr = tree->properties; attr; attr = attr->next)
3778 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3779 continue;
3781 xmlAttrPtr a = xmlHasProp (dst, attr->name);
3782 if (a)
3783 xmlRemoveProp (a);
3785 xmlChar *tmp = xmlNodeGetContent (attr->children);
3786 xmlNewProp (dst, attr->name, tmp);
3787 xmlFree (tmp);
3788 /* Create the default attributes. */
3789 rc = xml_add_attribute (client, dst, NULL, NULL);
3792 xmlNodePtr n = dst->children;
3793 (void)xml_unlink_node (client, n);
3794 dst->children = NULL;
3796 if (tree->children)
3798 n = xmlCopyNodeList (tree->children);
3799 if (!n)
3801 rc = GPG_ERR_ENOMEM;
3802 goto fail;
3805 n = xmlAddChildList (dst, n);
3806 if (!n)
3808 rc = GPG_ERR_ENOMEM;
3809 goto fail;
3812 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc)
3813 == dst->parent ? dst : dst->parent);
3816 fail:
3817 if (tree)
3818 (void)xml_unlink_node (client, tree);
3820 xml_free_request (req);
3821 strv_free (args);
3822 return rc;
3825 static gpg_error_t
3826 copy_command (assuan_context_t ctx, char *line)
3828 struct client_s *client = assuan_get_pointer (ctx);
3829 gpg_error_t rc;
3830 struct argv_s *args[] = {
3831 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3832 NULL
3835 rc = parse_options (&line, args, client, 1);
3836 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3837 rc = GPG_ERR_SYNTAX;
3838 if (rc)
3839 return send_error (ctx, rc);
3841 rc = copy_on_write (client);
3842 if (rc)
3843 return send_error (ctx, rc);
3845 if (client->opts & OPT_INQUIRE)
3847 unsigned char *result;
3848 size_t len;
3850 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3851 if (rc)
3852 return send_error (ctx, rc);
3854 pthread_cleanup_push ((void *)xfree, result);
3855 rc = do_copy (ctx, (char *)result);
3856 pthread_cleanup_pop (1);
3858 else
3859 rc = do_copy (ctx, line);
3861 return send_error (ctx, rc);
3864 static gpg_error_t
3865 do_move (assuan_context_t ctx, char *line)
3867 struct client_s *client = assuan_get_pointer (ctx);
3868 char **args;
3869 xmlNodePtr src, dst;
3870 struct xml_request_s *req;
3871 gpg_error_t rc;
3873 if (!line || !*line)
3874 return GPG_ERR_SYNTAX;
3876 args = str_split (line, " ", 0);
3877 if (!args || strv_length (args) != 2)
3879 strv_free (args);
3880 return GPG_ERR_SYNTAX;
3883 if (*args[1])
3885 char **targs = str_split (args[1], "\t", 0);
3886 if (!targs)
3888 strv_free (args);
3889 return GPG_ERR_ENOMEM;
3892 if (!xml_valid_element_path (targs, 0))
3894 strv_free (targs);
3895 strv_free (args);
3896 return GPG_ERR_INV_VALUE;
3899 strv_free (targs);
3902 rc = xml_new_request (client, args[0], XML_CMD_MOVE, &req);
3903 if (rc)
3905 strv_free (args);
3906 return rc;
3909 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3910 if (rc)
3911 goto fail;
3913 rc = xml_is_element_owner (client, src);
3914 if (rc)
3915 goto fail;
3917 xml_free_request (req);
3918 req = NULL;
3919 if (*args[1])
3921 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
3922 if (rc)
3923 goto fail;
3925 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3926 &rc);
3928 else
3929 dst = xmlDocGetRootElement (client->doc);
3931 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3932 goto fail;
3934 rc = 0;
3936 for (xmlNodePtr n = dst; n; n = n->parent)
3938 if (n == src)
3940 rc = GPG_ERR_EEXIST;
3941 goto fail;
3945 if (dst)
3947 xmlChar *a = xml_attribute_value (src, (xmlChar *) "_name");
3948 xmlNodePtr dup = xml_find_element (client, dst->children, (char *) a, &rc);
3950 xmlFree (a);
3951 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3952 goto fail;
3954 rc = 0;
3956 if (dup)
3958 if (dup == src)
3960 rc = GPG_ERR_EEXIST;
3961 goto fail;
3964 if (dst == xmlDocGetRootElement (client->doc))
3966 xmlNodePtr n = src;
3967 int match = 0;
3969 while (n->parent && n->parent != dst)
3970 n = n->parent;
3972 a = xml_attribute_value (n, (xmlChar *) "_name");
3973 xmlChar *b = xml_attribute_value (src, (xmlChar *) "_name");
3975 if (xmlStrEqual (a, b))
3977 match = 1;
3978 xmlUnlinkNode (src);
3979 (void)xml_unlink_node (client, n);
3982 xmlFree (a);
3983 xmlFree (b);
3985 if (!match)
3986 (void)xml_unlink_node (client, dup);
3988 else
3989 xmlUnlinkNode (dup);
3993 if (!dst && req && req->args && *req->args)
3995 struct xml_request_s *nreq = NULL;
3996 xmlChar *name = xml_attribute_value (src, (xmlChar *) "_name");
3998 if (src->parent == xmlDocGetRootElement (client->doc)
3999 && !strcmp ((char *) name, *req->args))
4001 xmlFree (name);
4002 rc = GPG_ERR_EEXIST;
4003 goto fail;
4006 xmlFree (name);
4007 rc = xml_new_request (client, args[1], XML_CMD_STORE, &nreq);
4008 if (!rc)
4010 dst = xml_find_elements (client, nreq,
4011 xmlDocGetRootElement (nreq->doc), &rc);
4012 xml_free_request (nreq);
4015 if (rc)
4016 goto fail;
4019 xml_update_element_mtime (client, src->parent);
4020 xmlUnlinkNode (src);
4022 dst = xmlAddChildList (dst, src);
4023 if (!dst)
4024 rc = GPG_ERR_ENOMEM;
4025 else
4026 xml_update_element_mtime (client, dst->parent);
4028 fail:
4029 xml_free_request (req);
4030 strv_free (args);
4031 return rc;
4034 static gpg_error_t
4035 move_command (assuan_context_t ctx, char *line)
4037 struct client_s *client = assuan_get_pointer (ctx);
4038 gpg_error_t rc;
4039 struct argv_s *args[] = {
4040 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4041 NULL
4044 rc = parse_options (&line, args, client, 1);
4045 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
4046 rc = GPG_ERR_SYNTAX;
4047 if (rc)
4048 return send_error (ctx, rc);
4050 rc = copy_on_write (client);
4051 if (rc)
4052 return send_error (ctx, rc);
4054 if (client->opts & OPT_INQUIRE)
4056 unsigned char *result;
4057 size_t len;
4059 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4060 if (rc)
4061 return send_error (ctx, rc);
4063 pthread_cleanup_push ((void *)xfree, result);
4064 rc = do_move (ctx, (char *)result);
4065 pthread_cleanup_pop (1);
4067 else
4068 rc = do_move (ctx, line);
4070 return send_error (ctx, rc);
4073 static int
4074 sort_files (const void *arg1, const void *arg2)
4076 char *const *a = arg1;
4077 char *const *b = arg2;
4079 return strcmp (*a, *b);
4082 static gpg_error_t
4083 ls_command (assuan_context_t ctx, char *line)
4085 struct client_s *client = assuan_get_pointer (ctx);
4086 gpg_error_t rc;
4087 char *tmp;
4088 char *dir;
4089 DIR *d;
4090 char *list = NULL;
4091 char **v = NULL;
4092 #ifdef HAVE_READDIR_R
4093 size_t len;
4094 struct dirent *cur = NULL, *p;
4095 #else
4096 struct dirent *cur = NULL;
4097 #endif
4098 struct argv_s *args[] = {
4099 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4100 NULL
4103 rc = parse_options (&line, args, client, 0);
4104 if (rc)
4105 return send_error (ctx, rc);
4107 tmp = str_asprintf ("%s/data", homedir);
4108 dir = expand_homedir (tmp);
4109 xfree (tmp);
4110 if (!dir)
4111 return send_error (ctx, GPG_ERR_ENOMEM);
4113 d = opendir (dir);
4114 rc = gpg_error_from_errno (errno);
4116 if (!d)
4118 xfree (dir);
4119 return send_error (ctx, rc);
4122 #ifdef HAVE_READDIR_R
4123 len = offsetof (struct dirent, d_name) + pathconf (dir, _PC_NAME_MAX) + 1;
4124 p = xmalloc (len);
4125 if (!p)
4127 xfree (dir);
4128 closedir (d);
4129 return send_error (ctx, GPG_ERR_ENOMEM);
4131 pthread_cleanup_push (xfree, p);
4132 #endif
4134 pthread_cleanup_push ((void *)closedir, d);
4135 xfree (dir);
4136 rc = 0;
4138 #ifdef HAVE_READDIR_R
4139 while (!readdir_r (d, p, &cur) && cur)
4140 #else
4141 while ((cur = readdir (d)))
4142 #endif
4144 char **vtmp;
4145 struct stat st;
4147 rc = open_check_file (cur->d_name, NULL, &st, 1);
4148 if (rc)
4149 continue;
4151 if (client->opts & OPT_VERBOSE)
4152 tmp = str_asprintf ("%s %lu.%lu %lu.%lu %lu.%lu", cur->d_name,
4153 st.st_atim.tv_sec, st.st_atim.tv_nsec,
4154 st.st_mtim.tv_sec, st.st_mtim.tv_nsec,
4155 st.st_ctim.tv_sec, st.st_ctim.tv_nsec);
4156 else
4157 tmp = str_dup (cur->d_name);
4159 if (!tmp)
4161 rc = GPG_ERR_ENOMEM;
4162 break;
4165 vtmp = strv_cat (v, tmp);
4166 if (!vtmp)
4168 xfree (tmp);
4169 rc = GPG_ERR_ENOMEM;
4170 break;
4173 v = vtmp;
4176 pthread_cleanup_pop (1); // closedir (d)
4177 #ifdef HAVE_READDIR_R
4178 pthread_cleanup_pop (1); // xfree (p)
4179 #endif
4181 if (rc && rc != GPG_ERR_ENODEV)
4183 strv_free (v);
4184 return send_error (ctx, rc);
4187 rc = 0;
4188 if (v && *v)
4190 unsigned n, t = strv_length (v);
4192 qsort (v, t, sizeof (char **), sort_files);
4194 for (n = 0; n < t; n++)
4196 tmp = str_asprintf ("%s%s\n", list ? list : "", v[n]);
4197 if (!tmp)
4199 xfree (list);
4200 rc = GPG_ERR_ENOMEM;
4201 break;
4204 xfree (list);
4205 list = tmp;
4209 strv_free (v);
4210 if (!list)
4211 return send_error (ctx, GPG_ERR_NO_DATA);
4213 list[strlen (list) - 1] = 0;
4214 pthread_cleanup_push (xfree, list);
4215 rc = xfer_data (ctx, list, strlen (list));
4216 pthread_cleanup_pop (1);
4217 return send_error (ctx, rc);
4220 /* Run all commands in the command list 'head'. The return code isn't
4221 * considered at all for a command. It is stored in the list and later sent to
4222 * the client. */
4223 static gpg_error_t
4224 dispatch_bulk_commands (struct client_s *client, struct sexp_s **list)
4226 unsigned i;
4227 unsigned id = 0;
4228 gpg_error_t rc = 0;
4230 for (i = 0; list && list[i];)
4232 struct bulk_cmd_s *cur = list[i]->user;
4234 if (!strcmp (list[i]->tag, "command"))
4236 i++;
4237 continue;
4239 else if (!strcmp (list[i]->tag, "id"))
4241 id = i++;
4242 continue;
4245 if ((client->flags & FLAG_NO_PINENTRY) && cur->cmd->inquire)
4247 rc = send_status (client->ctx, STATUS_BULK, "BEGIN %s",
4248 list[id]->data);
4249 if (rc)
4250 break;
4253 client->bulk_p = cur;
4254 cur->ran = 1;
4256 cur->rc = command_startup (client->ctx, cur->cmd->name);
4257 if (!cur->rc)
4258 cur->rc = cur->cmd->handler (client->ctx, list[i]->data);
4260 if ((client->flags & FLAG_NO_PINENTRY) && cur->cmd->inquire)
4262 (void)send_status (client->ctx, STATUS_BULK, "END %s",
4263 list[id]->data);
4265 command_finalize (client->ctx, cur->rc);
4266 cur->rc = cur->rc ? cur->rc : client->last_rc;
4268 do {
4269 if (list[i+1] && !strcmp (list[i+1]->tag, "rc"))
4271 gpg_error_t erc = 0;
4272 int match = 0;
4274 if (list[i+1]->data)
4276 char **rcs = str_split (list[i+1]->data, "|", 0);
4277 char **p;
4279 for (p = rcs; p && *p; p++)
4281 erc = strtoul (*p, NULL, 10);
4282 if (erc == cur->rc)
4284 match = 1;
4285 break;
4289 strv_free (rcs);
4292 if (!match)
4294 i++;
4295 continue;
4298 rc = dispatch_bulk_commands (client, list[++i]->next);
4300 else
4302 i++;
4303 break;
4305 } while (1);
4308 return rc;
4311 static gpg_error_t
4312 bulk_command (assuan_context_t ctx, char *line)
4314 struct client_s *client = assuan_get_pointer (ctx);
4315 gpg_error_t rc = 0;
4316 unsigned char *result, *p;
4317 size_t len;
4318 struct sexp_s **sexp = NULL;
4319 struct argv_s *args[] = {
4320 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4321 NULL
4324 rc = parse_options (&line, args, client, 1);
4325 if (rc)
4326 return send_error (ctx, rc);
4328 if ((client->opts & OPT_INQUIRE) && line && *line)
4329 rc = GPG_ERR_SYNTAX;
4330 else if (!(client->opts & OPT_INQUIRE) && (!line || !*line))
4331 rc = GPG_ERR_SYNTAX;
4333 if (rc)
4334 return send_error (ctx, rc);
4336 if (client->opts & OPT_INQUIRE)
4338 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4339 if (rc)
4340 return send_error (ctx, rc);
4341 p = result;
4343 else
4344 p = (unsigned char *)line;
4346 if (!len)
4347 return send_error (ctx, GPG_ERR_SYNTAX);
4349 rc = bulk_parse_commands (&sexp, (const char *)p, command_table);
4350 if (client->opts & OPT_INQUIRE)
4351 xfree (result);
4353 if (rc)
4354 return send_error (ctx, rc);
4356 pthread_cleanup_push ((void *)bulk_free_list, sexp);
4357 rc = dispatch_bulk_commands (client, sexp);
4358 pthread_cleanup_pop (0);
4359 if (!rc)
4360 rc = bulk_build_result (sexp, (char **)&result);
4362 bulk_free_list (sexp);
4364 if (!rc)
4366 pthread_cleanup_push ((void *)xfree, result);
4367 rc = xfer_data (ctx, (char *)result, strlen ((char *)result));
4368 pthread_cleanup_pop (1);
4371 return send_error (ctx, rc);
4374 static gpg_error_t
4375 nop_command (assuan_context_t ctx, char *line)
4377 return send_error (ctx, 0);
4380 static gpg_error_t
4381 bye_notify (assuan_context_t ctx, char *line)
4383 struct client_s *cl = assuan_get_pointer (ctx);
4384 gpg_error_t ret = 0;
4386 (void)line;
4387 update_client_state (cl, CLIENT_STATE_DISCON);
4389 #ifdef WITH_GNUTLS
4390 cl->disco = 1;
4391 if (cl->thd->remote)
4393 int rc;
4397 struct timeval tv = { 0, 50000 };
4399 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4400 if (rc == GNUTLS_E_AGAIN)
4401 select (0, NULL, NULL, NULL, &tv);
4403 while (rc == GNUTLS_E_AGAIN);
4405 #endif
4407 /* This will let assuan_process_next() return. */
4408 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4410 cl->last_rc = gpg_error_from_errno (errno);
4411 ret = cl->last_rc;
4414 cl->last_rc = 0; // BYE command result
4415 return ret;
4418 static gpg_error_t
4419 reset_notify (assuan_context_t ctx, char *line)
4421 struct client_s *client = assuan_get_pointer (ctx);
4423 (void)line;
4424 if (client)
4425 reset_client (client);
4427 return 0;
4431 * This is called before every Assuan command.
4433 static gpg_error_t
4434 command_startup (assuan_context_t ctx, const char *name)
4436 struct client_s *client = assuan_get_pointer (ctx);
4437 gpg_error_t rc = 0;
4438 struct command_table_s *cmd = NULL;
4440 log_write2 ("command='%s'", name);
4441 client->last_rc = client->opts = 0;
4443 for (int i = 0; command_table[i]; i++)
4445 if (!strcasecmp (name, command_table[i]->name))
4447 if (command_table[i]->ignore_startup)
4448 goto send_state;
4450 cmd = command_table[i];
4451 break;
4455 if (!cmd)
4456 return GPG_ERR_UNKNOWN_COMMAND;
4458 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4460 send_state:
4461 if (!client->bulk_p && !rc)
4462 update_client_state (client, CLIENT_STATE_COMMAND);
4464 return rc;
4468 * This is called after every Assuan command.
4470 static void
4471 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4473 struct client_s *client = assuan_get_pointer (ctx);
4475 if (!(client->flags & FLAG_LOCK_CMD))
4476 unlock_file_mutex (client, 0);
4478 unlock_flock (&client->flock_fd);
4479 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4481 #ifdef WITH_GNUTLS
4482 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4483 #endif
4485 if (!client->bulk_p && client->thd->state != CLIENT_STATE_DISCON)
4486 update_client_state (client, CLIENT_STATE_IDLE);
4488 client->bulk_p = NULL;
4491 static gpg_error_t
4492 parse_help_opt_html (void *data, void *value)
4494 struct client_s *client = data;
4496 (void) value;
4497 client->opts |= OPT_HTML;
4498 return 0;
4501 static gpg_error_t
4502 help_command (assuan_context_t ctx, char *line)
4504 gpg_error_t rc;
4505 int i;
4506 struct client_s *client = assuan_get_pointer (ctx);
4507 struct argv_s *args[] = {
4508 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
4509 NULL
4512 rc = parse_options (&line, args, client, 1);
4513 if (rc)
4514 return send_error (ctx, rc);
4516 if (!line || !*line)
4518 char *tmp;
4519 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
4520 "For commands that take an element path as an argument, each element is "
4521 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4522 "@*@*COMMANDS:"));
4524 for (i = 0; command_table[i]; i++)
4526 if (!command_table[i]->help)
4527 continue;
4529 /* @npxref{} won't put a "See " or "see " in front of the command.
4530 * It's not a texinfo command but needed for --html. */
4531 tmp = str_asprintf ("%s %s%s%s", help,
4532 client->opts & OPT_HTML ? "@npxref{" : "",
4533 command_table[i]->name,
4534 client->opts & OPT_HTML ? "}" : "");
4535 xfree (help);
4536 help = tmp;
4539 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
4540 xfree (help);
4541 pthread_cleanup_push ((void *)xfree, tmp);
4542 rc = xfer_data (ctx, tmp, strlen (tmp));
4543 pthread_cleanup_pop (1);
4544 return send_error (ctx, rc);
4547 for (i = 0; command_table[i]; i++)
4549 if (!strcasecmp (line, command_table[i]->name))
4551 char *help, *tmp;
4553 if (!command_table[i]->help)
4554 break;
4556 help = strip_texi_and_wrap (command_table[i]->help,
4557 client->opts & OPT_HTML);
4558 tmp = str_asprintf ("%s%s",
4559 (client->opts & OPT_HTML) ? "" : _("Usage: "),
4560 help);
4561 xfree (help);
4562 pthread_cleanup_push ((void *)xfree, tmp);
4563 rc = xfer_data (ctx, tmp, strlen (tmp));
4564 pthread_cleanup_pop (1);
4565 return send_error (ctx, rc);
4569 return send_error (ctx, GPG_ERR_INV_NAME);
4572 static void
4573 new_command (const char *name, int inquire, int ignore, int unlock,
4574 int flock_type, gpg_error_t (*handler) (assuan_context_t, char *),
4575 const char *help)
4577 int i = 0;
4578 struct command_table_s **tmp;
4580 if (command_table)
4581 for (i = 0; command_table[i]; i++);
4583 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4584 assert (tmp);
4585 command_table = tmp;
4586 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4587 command_table[i]->name = name;
4588 command_table[i]->inquire = inquire;
4589 command_table[i]->handler = handler;
4590 command_table[i]->ignore_startup = ignore;
4591 command_table[i]->unlock = unlock;
4592 command_table[i]->flock_type = flock_type;
4593 command_table[i++]->help = help;
4594 command_table[i] = NULL;
4597 void
4598 deinit_commands ()
4600 int i;
4602 for (i = 0; command_table[i]; i++)
4603 xfree (command_table[i]);
4605 xfree (command_table);
4608 static int
4609 sort_commands (const void *arg1, const void *arg2)
4611 struct command_table_s *const *a = arg1;
4612 struct command_table_s *const *b = arg2;
4614 if (!*a || !*b)
4615 return 0;
4616 else if (*a && !*b)
4617 return 1;
4618 else if (!*a && *b)
4619 return -1;
4621 return strcmp ((*a)->name, (*b)->name);
4624 static gpg_error_t
4625 passwd_command (assuan_context_t ctx, char *line)
4627 struct client_s *client = assuan_get_pointer (ctx);
4628 gpg_error_t rc;
4630 (void)line;
4631 rc = peer_is_invoker (client);
4632 if (rc)
4633 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
4635 if (client->flags & FLAG_NEW)
4636 return send_error (ctx, GPG_ERR_INV_STATE);
4638 client->crypto->keyfile = config_get_string (client->filename,
4639 "passphrase_file");
4640 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY,
4641 client->crypto->keyfile);
4642 if (!rc)
4643 rc = crypto_passwd (client, client->crypto);
4645 crypto_free_non_keys (client->crypto);
4646 return send_error (ctx, rc);
4649 static gpg_error_t
4650 parse_opt_data (void *data, void *value)
4652 struct client_s *client = data;
4654 (void) value;
4655 client->opts |= OPT_DATA;
4656 return 0;
4659 static gpg_error_t
4660 send_client_list (assuan_context_t ctx)
4662 struct client_s *client = assuan_get_pointer (ctx);
4663 gpg_error_t rc = 0;
4665 if (client->opts & OPT_VERBOSE)
4667 unsigned i, t;
4668 char **list = NULL;
4669 char *line;
4671 MUTEX_LOCK (&cn_mutex);
4672 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4673 t = slist_length (cn_thread_list);
4675 for (i = 0; i < t; i++)
4677 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4678 char *tmp;
4680 if (thd->state == CLIENT_STATE_UNKNOWN)
4681 continue;
4683 tmp = build_client_info_line (thd, 0);
4684 if (tmp)
4686 char **l = strv_cat (list, tmp);
4687 if (!l)
4688 rc = GPG_ERR_ENOMEM;
4689 else
4690 list = l;
4692 else
4693 rc = GPG_ERR_ENOMEM;
4695 if (rc)
4697 strv_free (list);
4698 break;
4702 pthread_cleanup_pop (1);
4703 if (rc)
4704 return rc;
4706 line = strv_join ("\n", list);
4707 strv_free (list);
4708 pthread_cleanup_push ((void *)xfree, line);
4709 rc = xfer_data (ctx, line, strlen (line));
4710 pthread_cleanup_pop (1);
4711 return rc;
4714 if (client->opts & OPT_DATA)
4716 char buf[ASSUAN_LINELENGTH];
4718 MUTEX_LOCK (&cn_mutex);
4719 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4720 MUTEX_UNLOCK (&cn_mutex);
4721 rc = xfer_data (ctx, buf, strlen (buf));
4723 else
4724 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4726 return rc;
4729 static gpg_error_t
4730 getinfo_command (assuan_context_t ctx, char *line)
4732 struct client_s *client = assuan_get_pointer (ctx);
4733 gpg_error_t rc;
4734 char buf[ASSUAN_LINELENGTH];
4735 struct argv_s *args[] = {
4736 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4737 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4738 NULL
4741 rc = parse_options (&line, args, client, 1);
4742 if (rc)
4743 return send_error (ctx, rc);
4745 if (!line || !*line)
4746 return send_error (ctx, GPG_ERR_SYNTAX);
4748 if (!strcasecmp (line, "clients"))
4750 rc = send_client_list (ctx);
4752 else if (!strcasecmp (line, "cache"))
4754 if (client->opts & OPT_DATA)
4756 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4757 rc = xfer_data (ctx, buf, strlen (buf));
4759 else
4760 rc = send_status (ctx, STATUS_CACHE, NULL);
4762 else if (!strcasecmp (line, "pid"))
4764 pid_t pid = getpid ();
4766 snprintf (buf, sizeof (buf), "%u", pid);
4767 rc = xfer_data (ctx, buf, strlen (buf));
4769 else if (!strcasecmp (line, "version"))
4771 char *tmp = str_asprintf ("0x%06x %s", VERSION_HEX,
4772 #ifdef WITH_GNUTLS
4773 "GNUTLS "
4774 #endif
4775 #ifdef WITH_LIBACL
4776 "ACL "
4777 #endif
4778 "");
4779 pthread_cleanup_push (xfree, tmp);
4780 rc = xfer_data (ctx, tmp, strlen (tmp));
4781 pthread_cleanup_pop (1);
4783 else if (!strcasecmp (line, "last_error"))
4785 if (client->last_error)
4786 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4787 else
4788 rc = GPG_ERR_NO_DATA;
4790 else if (!strcasecmp (line, "user"))
4792 char *user = NULL;
4794 #ifdef WITH_GNUTLS
4795 if (client->thd->remote)
4796 user = str_asprintf ("#%s", client->thd->tls->fp);
4797 else
4798 user = get_username (client->thd->peer->uid);
4799 #else
4800 user = get_username (client->thd->peer->uid);
4801 #endif
4802 if (user)
4804 pthread_cleanup_push ((void *)xfree, user);
4805 rc = xfer_data (ctx, user, strlen (user));
4806 pthread_cleanup_pop (1);
4808 else
4809 rc = GPG_ERR_NO_DATA;
4811 else
4812 rc = gpg_error (GPG_ERR_SYNTAX);
4814 return send_error (ctx, rc);
4817 static gpg_error_t
4818 parse_opt_secret (void *data, void *value)
4820 struct client_s *client = data;
4822 (void) value;
4823 client->opts |= OPT_SECRET;
4824 return 0;
4827 static gpg_error_t
4828 parse_keyinfo_opt_learn (void *data, void *value)
4830 struct client_s *client = data;
4832 (void)value;
4833 client->opts |= OPT_KEYINFO_LEARN;
4834 return 0;
4837 static gpg_error_t
4838 keyinfo_command (assuan_context_t ctx, char *line)
4840 struct client_s *client = assuan_get_pointer (ctx);
4841 gpg_error_t rc = 0;
4842 char **keys = NULL, **p = NULL;
4843 int sym = 0;
4844 struct argv_s *args[] = {
4845 &(struct argv_s) {"learn", OPTION_TYPE_NOARG, parse_keyinfo_opt_learn},
4846 NULL
4849 rc = parse_options (&line, args, client, 0);
4850 if (rc)
4851 return send_error (ctx, rc);
4853 if (line && *line)
4854 return send_error (ctx, GPG_ERR_SYNTAX);
4856 if (!(client->flags & FLAG_OPEN))
4857 return send_error (ctx, GPG_ERR_INV_STATE);
4859 if (client->opts & OPT_KEYINFO_LEARN)
4861 rc = cache_agent_command ("LEARN");
4862 return send_error (ctx, rc);
4865 if (client->flags & FLAG_NEW)
4866 return send_error (ctx, GPG_ERR_NO_DATA);
4868 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
4869 if (rc)
4870 return send_error (ctx, rc);
4872 rc = crypto_is_symmetric (client->filename);
4873 unlock_flock (&client->flock_fd);
4874 if (!rc)
4875 sym = 1;
4876 else if (rc != GPG_ERR_BAD_DATA)
4877 return send_error (ctx, rc);
4879 rc = 0;
4880 if (!sym)
4882 p = strv_catv (keys, client->crypto->pubkey);
4883 if (!p)
4884 rc = GPG_ERR_ENOMEM;
4885 else
4886 keys = p;
4889 if (!rc && client->crypto->sigkey)
4891 if (!strv_printf (&keys, "S%s", client->crypto->sigkey))
4893 strv_free (keys);
4894 return send_error (ctx, GPG_ERR_ENOMEM);
4898 if (!rc)
4900 if (keys)
4902 line = strv_join ("\n", keys);
4903 strv_free (keys);
4904 pthread_cleanup_push ((void *)xfree, line);
4905 if (line)
4906 rc = xfer_data (ctx, line, strlen (line));
4907 else
4908 rc = GPG_ERR_ENOMEM;
4910 pthread_cleanup_pop (1);
4912 else
4913 rc = GPG_ERR_NO_DATA;
4915 else
4916 strv_free (keys);
4918 return send_error (ctx, rc);
4921 static gpg_error_t
4922 deletekey_command (assuan_context_t ctx, char *line)
4924 gpg_error_t rc;
4925 struct client_s *client = assuan_get_pointer (ctx);
4926 struct crypto_s *crypto = NULL;
4927 char *keys[] = { NULL, NULL };
4928 gpgme_key_t *result;
4929 char **p = NULL;
4931 if (!(client->flags & FLAG_OPEN))
4932 return send_error (ctx, GPG_ERR_INV_STATE);
4934 rc = peer_is_invoker (client);
4935 if (rc)
4936 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
4938 if (client->flags & FLAG_NO_PINENTRY)
4939 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4941 if (!*line)
4942 return send_error (ctx, GPG_ERR_SYNTAX);
4944 rc = crypto_keyid_to_16b_once (line);
4945 if (rc)
4946 return send_error (ctx, rc);
4948 for (p = client->crypto->pubkey; p && *p; p++)
4950 if (!strcmp (*p, line))
4951 break;
4954 if (!p)
4956 if (client->crypto->sigkey && strcmp (client->crypto->sigkey, line))
4957 return send_error (ctx, GPG_ERR_FORBIDDEN);
4958 else if (!client->crypto->sigkey)
4959 return send_error (ctx, GPG_ERR_NO_SECKEY);
4962 rc = crypto_init (&crypto, client->ctx, client->filename,
4963 client->flags & FLAG_NO_PINENTRY, NULL);
4964 if (rc)
4965 return send_error (ctx, rc);
4967 pthread_cleanup_push ((void *)crypto_free, crypto);
4968 keys[0] = line;
4969 rc = crypto_list_keys (crypto, keys, 1, &result);
4970 if (!rc)
4972 pthread_cleanup_push ((void *)crypto_free_key_list, result);
4973 rc = crypto_delete_key (client, crypto, *result, 1);
4974 pthread_cleanup_pop (1);
4977 pthread_cleanup_pop (1);
4978 return send_error (ctx, rc);
4981 static gpg_error_t
4982 kill_command (assuan_context_t ctx, char *line)
4984 struct client_s *client = assuan_get_pointer (ctx);
4985 gpg_error_t rc;
4986 unsigned i, t;
4988 if (!line || !*line)
4989 return send_error (ctx, GPG_ERR_SYNTAX);
4991 MUTEX_LOCK (&cn_mutex);
4992 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4993 t = slist_length (cn_thread_list);
4994 rc = GPG_ERR_ESRCH;
4996 for (i = 0; i < t; i++)
4998 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4999 char *tmp = str_asprintf ("%p", thd->tid);
5001 if (strcmp (line, tmp))
5003 xfree (tmp);
5004 continue;
5007 xfree (tmp);
5008 rc = peer_is_invoker (client);
5009 if (!rc)
5011 #ifdef HAVE_PTHREAD_CANCEL
5012 pthread_cancel (thd->tid);
5013 #else
5014 pthread_kill (thd->tid, SIGUSR2);
5015 #endif
5016 break;
5018 else if (rc == GPG_ERR_EACCES)
5019 rc = GPG_ERR_FORBIDDEN;
5020 else if (rc)
5021 break;
5023 if (config_get_boolean ("global", "strict_kill"))
5024 break;
5026 #ifdef WITH_GNUTLS
5027 if (client->thd->remote && thd->remote)
5029 if (!thd->tls || !thd->tls->fp)
5031 rc = GPG_ERR_INV_STATE;
5032 break;
5034 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
5036 #ifdef HAVE_PTHREAD_CANCEL
5037 pthread_cancel (thd->tid);
5038 #else
5039 pthread_kill (thd->tid, SIGUSR2);
5040 #endif
5041 rc = 0;
5042 break;
5045 else if (!client->thd->remote && !thd->remote)
5046 #endif
5048 if (client->thd->peer->uid == thd->peer->uid)
5050 #ifdef HAVE_PTHREAD_CANCEL
5051 pthread_cancel (thd->tid);
5052 #else
5053 pthread_kill (thd->tid, SIGUSR2);
5054 #endif
5055 rc = 0;
5058 break;
5061 pthread_cleanup_pop (1);
5062 return send_error (ctx, rc);
5065 static gpg_error_t
5066 listkeys_command (assuan_context_t ctx, char *line)
5068 struct client_s *client = assuan_get_pointer (ctx);
5069 struct crypto_s *crypto = NULL;
5070 char **pattern = NULL;
5071 gpgme_key_t *keys = NULL;
5072 char **result = NULL;
5073 gpg_error_t rc;
5074 struct argv_s *args[] = {
5075 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG, parse_opt_secret},
5076 NULL
5079 rc = parse_options (&line, args, client, 1);
5080 if (rc)
5081 return send_error (ctx, rc);
5083 rc = crypto_init (&crypto, client->ctx, client->filename,
5084 client->flags & FLAG_NO_PINENTRY, NULL);
5085 if (rc)
5086 return send_error (ctx, rc);
5088 pthread_cleanup_push ((void *)crypto_free, crypto);
5089 if (line)
5090 pattern = str_split (line, ",", 0);
5091 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
5092 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET,
5093 &keys);
5094 pthread_cleanup_pop (1);
5095 pthread_cleanup_pop (1);
5096 if (!rc)
5098 int i;
5100 for (i = 0; keys[i]; i++)
5102 char *p = crypto_key_info (keys[i]);
5103 char **r;
5105 if (!p)
5107 rc = GPG_ERR_ENOMEM;
5108 break;
5111 r = strv_cat (result, p);
5112 if (!r)
5114 rc = GPG_ERR_ENOMEM;
5115 break;
5118 result = r;
5121 if (!i)
5122 rc = GPG_ERR_NO_DATA;
5124 crypto_free_key_list (keys);
5127 if (!rc)
5129 line = strv_join ("\n", result);
5130 strv_free (result);
5131 pthread_cleanup_push ((void *)xfree, line);
5132 if (!line)
5133 rc = GPG_ERR_ENOMEM;
5134 else
5135 rc = xfer_data (ctx, line, strlen (line));
5137 pthread_cleanup_pop (1);
5139 else
5140 strv_free (result);
5142 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
5143 || gpg_err_code (rc) == GPG_ERR_NO_SECKEY)
5144 rc = GPG_ERR_NO_DATA;
5146 return send_error (ctx, rc);
5149 void
5150 init_commands ()
5152 /* !BEGIN-HELP-TEXT!
5154 * This comment is used as a marker to generate the offline documentation
5155 * found in doc/pwmd.info. The indentation needs to be kept for the awk
5156 * script to determine where commands begin and end.
5158 new_command("HELP", 0, 1, 1, 0, help_command, _(
5159 "HELP [--html] [<COMMAND>]\n" /* Showing available commands. */
5160 "Show available commands or command specific help text."
5161 "@*@*"
5162 "The @option{--html} option will output the help text in HTML format."
5165 new_command("DELETEKEY", 0, 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, deletekey_command, _(
5166 "DELETEKEY <keyid>\n" /* Deleting a key from the key ring. */
5167 "Deletes the public and secret key associated with key @var{keyid} from the "
5168 "keyring. The @var{keyid} must be one associated with the currently opened "
5169 "data file. "
5170 "Note that no confirmation occurs. Also note that when the key is deleted, "
5171 "the current or other data files using this key will no longer be able to be "
5172 "opened."
5175 new_command("KILL", 0, 1, 0, 0, kill_command, _(
5176 "KILL <thread_id>\n" /* Terminating another client. */
5177 "Terminates the client identified by @var{thread_id} and releases any file "
5178 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
5179 "for details about listing connected clients. An @code{invoking_user} "
5180 "(@pxref{Configuration}) may kill any client while others may only kill "
5181 "clients of the same @code{UID} or @abbr{TLS} fingerprint."
5184 new_command("LISTKEYS", 0, 1, 0, 0, listkeys_command, _(
5185 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n" /* Listing keys in the key ring. */
5186 "Returns a new line separated list of key information matching a comma "
5187 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
5188 "specified, only keys matching @var{pattern} that also have a secret key "
5189 "available will be returned."
5192 new_command("KEYINFO", 0, 1, 0, 0, keyinfo_command, _(
5193 "KEYINFO [--learn]\n" /* Showing keys used for the current data file. */
5194 "Returns a new line separated list of key ID's that the currently opened "
5195 "data file has recipients and signers for. If the key is a signing key it "
5196 "will be prefixed with an @code{S}. If the file is a new one, or has no "
5197 "signers in the case of being symmetrically encrypted, the error code "
5198 "@code{GPG_ERR_NO_DATA} is returned."
5199 "@*@*"
5200 "When the @option{--learn} option is passed, keys on a smartcard will be "
5201 "imported."
5204 new_command("GETINFO", 0, 1, 1, 0, getinfo_command, _(
5205 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n" /* Obtaining server and client information. */
5206 "Get server and other information. The information is returned via a status "
5207 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
5208 "is specified."
5209 "@*@*"
5210 "@var{CACHE} returns the number of cached documents."
5211 "@*@*"
5212 "@var{CLIENTS} returns the number of "
5213 "connected clients via a status message or a list of connected clients when "
5214 "the @option{--verbose} parameter is used (implies @option{--data}). A "
5215 "verbose line of a client list contains "
5216 "space delimited "
5217 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
5218 "IP address if remote, file lock status, whether the current client is self "
5219 "or not, client state (see below), "
5220 "user ID or TLS fingerprint of the connected client, username if the "
5221 "client is a local one else @code{-}, and finally the time stamp of when the "
5222 "client connected."
5223 "@*@*"
5224 "Client state @code{0} is an unknown client state, state @code{1} indicates "
5225 "the client has connected but hasn't completed initializing, state @code{2} "
5226 "indicates that the client is idle, state @code{3} means the "
5227 "client is in a command and state @code{4} means the client is disconnecting. "
5228 "@*@*"
5229 "@var{PID} returns the process ID number of the server via a data response."
5230 "@*@*"
5231 "@var{VERSION} returns the server version number and compile-time features "
5232 "via a data response with each being space delimited."
5233 "@*@*"
5234 "@var{LAST_ERROR} returns a detailed description of the last failed command "
5235 "via a data response, when available."
5236 "@*@*"
5237 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
5238 "via a data response."
5241 new_command("PASSWD", 1, 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
5242 "PASSWD\n" /* Changing the passphrase for a key. */
5243 "Changes the passphrase of the secret key required to open the current "
5244 "data file. If the data file is symmetrically encrypted, the error "
5245 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted, "
5246 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
5247 "this command saving any unwanted changes to the @abbr{XML} document."
5248 "@*@*"
5249 "Note that when the current data file has been either encrypted or signed "
5250 "with a key stored on a smartcard this command will return an error. In this "
5251 "case you should instead use @command{gpg --card-edit} to change the "
5252 "pin of the smartcard or @command{gpg --edit-key} to change the passphrase "
5253 "of the key used to sign or encrypt the data file."
5254 "@*@*"
5255 "This command is not available to non-invoking clients "
5256 "(@pxref{Access Control})."
5259 new_command("OPEN", 1, 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
5260 "OPEN [--lock] <filename>\n" /* Opening a data file. */
5261 "Opens @var{filename}. When the @var{filename} is not found on the "
5262 "file-system then a new in-memory document will be created. If the file is "
5263 "found, it is looked for in the file cache and when found no passphrase will "
5264 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
5265 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
5266 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
5267 "@emph{INQUIRE} the client for the passphrase. Note than when configuration "
5268 "option @option{strict_open} is enabled and the client is not an "
5269 "@option{invoking_user}, an error will be returned when the data file does "
5270 "not exist."
5271 "@*@*"
5272 "When the @option{--lock} option is passed then the file mutex will be "
5273 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
5274 "file had been opened."
5277 new_command("GENKEY", 1, 1, 1, 0, genkey_command, _(
5278 "GENKEY --subkey-of=fpr | --userid=\"str\" [--no-expire | --expire=N] [--algo=\"str\"] [--no-passphrase] [--usage=\"default|sign|encrypt\"]\n" /* Generating a new key. */
5279 "Generates a new key based on option arguments. One of "
5280 "@option{--subkey-of} or @option{--userid} is "
5281 "required. The @option{--subkey-of} option will generate a subkey for the key "
5282 "of the specified fingerprint."
5285 new_command("SAVE", 1, 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
5286 "SAVE [--sign-keyid=[<fpr>]] [--symmetric | --keyid=<fpr>[,..] | --inquire-keyid]\n" /* Saving document changes to disk. */
5287 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
5288 "file that was opened when using the @code{OPEN} command (@pxref{OPEN})."
5289 "@*@*"
5290 "If the file is a new one, one of @option{--symmetric}, @option{--keyid} or"
5291 "@option{--inquire-keyid} is required. When not @option{--symmetric}, option "
5292 "@option{--sign-keyid} is also required, but optional otherwise."
5293 "@*@*"
5294 "You can encrypt the data file to a recipient other than the one that it "
5295 "was originally encrypted with by passing the @option{--keyid} or "
5296 "@option{--inquire-keyid} option with a comma separated list of "
5297 "public encryption key fingerprints as its argument. Use the "
5298 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
5299 "pattern. The @option{--sign-keyid} option may also be used to sign the data "
5300 "file with an alternate key by specifying the fingerprint of a signing key. "
5301 "Only one signing key is supported unlike the @option{--keyid} option. "
5302 "A passphrase to decrypt the data file "
5303 "will be required when one or more of the original encryption keys or signing "
5304 "key are not found in either of these two options' arguments or when the data "
5305 "file is symmetrically encrypted reguardless of the @code{require_save_key} "
5306 "configuration parameter. The original encryption keys and signing key will be "
5307 "used when neither of these options are specified."
5308 "@*@*"
5309 "The @option{--keyid} and @option{--sign-keyid} options are not available "
5310 "to non-invoking clients "
5311 "(@pxref{Access Control}) when the recipients or signer do not match those "
5312 "that were used when the file was @code{OPEN}'ed."
5313 "@*@*"
5314 "The @option{--symmetric} option specifies that a new data file be "
5315 "conventionally encrypted. These types of data files do not use a recipient "
5316 "public key but may optionally be signed by using the @option{--sign-keyid} "
5317 "option. To remove the signing key from a symmtrically encrypted data file, "
5318 "leave the option value empty."
5319 "@*@*"
5320 "Note that you cannot change encryption schemes once a data file has been "
5321 "saved."
5324 new_command("ISCACHED", 0, 1, 0, 0, iscached_command, _(
5325 "ISCACHED [--lock] [--agent [--sign]] <filename>\n" /* Testing cache status. */
5326 "Determines the file cache status of the specified @var{filename}. "
5327 "The default is to test whether the filename is cached in memory. Passing "
5328 "option @option{--agent} will test the @command{gpg-agent} cache for at most "
5329 "one cached key used for opening the data file (@pxref{OPEN}). To test if "
5330 "a signing key is cached, pass @option{--sign} along with @option{--agent}. "
5331 "Both the @option{--agent} and @option{--sign} options require an opened data "
5332 "file."
5333 "@*@*"
5334 "An @emph{OK} response is returned if the specified @var{filename} is found "
5335 "in the cache. If not found in the cache but exists on the filesystem "
5336 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
5337 "returned."
5338 "@*@*"
5339 "The @option{--lock} option will lock the file mutex of @var{filename} when "
5340 "the file exists; it does not need to be opened nor cached. The lock will be "
5341 "released when the client exits or sends the @code{UNLOCK} command "
5342 "(@pxref{UNLOCK}). When this option is passed the current data file is closed."
5345 new_command("CLEARCACHE", 0, 1, 1, 0, clearcache_command, _(
5346 "CLEARCACHE [<filename>]\n" /* Removing a cache entry. */
5347 "Clears a file cache entry for all or the specified @var{filename}. Note that "
5348 "this will also clear any @command{gpg-agent} cached keys which may cause "
5349 "problems if another data file shares the same keys as @var{filename}."
5350 "@*@*"
5351 "When clearing all cache entries a permissions test is done against the "
5352 "current client based on the @var{allowed} configuration parameter in a "
5353 "@var{filename} section. Both a cache entry may be cleared and an error "
5354 "returned depending on cached data files and client permissions."
5357 new_command("CACHETIMEOUT", 0, 1, 1, 0, cachetimeout_command, _(
5358 "CACHETIMEOUT <seconds>\n" /* Setting the cache timeout. */
5359 "The time in @var{seconds} until the currently opened data file will be "
5360 "removed from the cache. @code{-1} will keep the cache entry forever, "
5361 "@code{0} will require the passphrase for each @code{OPEN} command "
5362 "(@pxref{OPEN}) or @code{SAVE} (@pxref{SAVE}) command. @xref{Configuration}, "
5363 "and the @code{cache_timeout} parameter."
5366 new_command("LIST", 0, 0, 1, 0, list_command, _(
5367 "LIST [--inquire] [--recurse] [element[<TAB>child[..]]]\n" /* Showing document elements. */
5368 "If no element path is given then a newline separated list of root elements "
5369 "is returned with a data response. If given, then children of the specified "
5370 "element path are returned."
5371 "@*@*"
5372 "Each element path "
5373 "returned will have zero or more flags appened to it. These flags are "
5374 "delimited from the element path by a single space character. A flag itself "
5375 "is a single character. Flag @code{P} indicates that access to the element "
5376 "is denied. Flag @code{+} indicates that there are child nodes of "
5377 "the current element path. Flag @code{E} indicates that an element of the "
5378 "element path contained in a @var{target} attribute could not be found. Flag "
5379 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
5380 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
5381 "then an element path, is the element path of the @var{target} attribute "
5382 "contained in the current element."
5383 "@*@*"
5384 "When a specified element path contains an error, beit from the final "
5385 "element in the path or any previous element, the path is still shown but "
5386 "will contain the error flag for the element with the error. Determining "
5387 "the actual element which contains the error is up to the client. This can be "
5388 "done by traversing the final element up to parent elements that contain the "
5389 "same error flag."
5390 "@*@*"
5391 "The option @option{--recurse} may be used to list the entire element tree "
5392 "for a specified element path or the entire tree for all root elements."
5393 "@*@*"
5394 "When the @option{--inquire} option is passed then all remaining non-option "
5395 "arguments are retrieved via a server @emph{INQUIRE}."
5398 new_command("REALPATH", 0, 0, 1, 0, realpath_command, _(
5399 "REALPATH [--inquire] element[<TAB>child[..]]\n" /* Resolving an element. */
5400 "Resolves all @code{target} attributes of the specified element path and "
5401 "returns the result with a data response. @xref{Target Attribute}, for details."
5402 "@*@*"
5403 "When the @option{--inquire} option is passed then all remaining non-option "
5404 "arguments are retrieved via a server @emph{INQUIRE}."
5407 new_command("STORE", 0, 0, 1, 0, store_command, _(
5408 "STORE element[<TAB>child[..]]<TAB>[content]\n" /* Modifying the content of an element. */
5409 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5410 "@*@*"
5411 "Creates a new element path or modifies the @var{content} of an existing "
5412 "element. If only a single element is specified then a new root element is "
5413 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
5414 "set to the final @key{TAB} delimited element. If no @var{content} is "
5415 "specified after the final @key{TAB}, then the content of the existing "
5416 "element will be removed; or will be empty if creating a new element."
5417 "@*@*"
5418 "The only restriction of an element name is that it not contain whitespace "
5419 "characters. There is no other whitespace between the @key{TAB} delimited "
5420 "elements. It is recommended that the content of an element be base64 encoded "
5421 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
5422 "parsing and @command{pwmd} syntax errors."
5425 new_command("RENAME", 0, 0, 1, 0, rename_command, _(
5426 "RENAME [--inquire] element[<TAB>child[..]] <value>\n" /* Renaming an element. */
5427 "Renames the specified @var{element} to the new @var{value}. If an element of "
5428 "the same name as the @var{value} already exists it will be overwritten."
5429 "@*@*"
5430 "When the @option{--inquire} option is passed then all remaining non-option "
5431 "arguments are retrieved via a server @emph{INQUIRE}."
5434 new_command("COPY", 0, 0, 1, 0, copy_command, _(
5435 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n" /* Copying an element. */
5436 "Copies the entire element tree starting from the child node of the source "
5437 "element, to the destination element path. If the destination element path "
5438 "does not exist then it will be created; otherwise it is overwritten."
5439 "@*@*"
5440 "Note that attributes from the source element are merged into the "
5441 "destination element when the destination element path exists. When an "
5442 "attribute of the same name exists in both the source and destination "
5443 "elements then the destination attribute will be updated to the source "
5444 "attribute value."
5445 "@*@*"
5446 "When the @option{--inquire} option is passed then all remaining non-option "
5447 "arguments are retrieved via a server @emph{INQUIRE}."
5450 new_command("MOVE", 0, 0, 1, 0, move_command, _(
5451 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n" /* Moving an element. */
5452 "Moves the source element path to the destination element path. If the "
5453 "destination is not specified then it will be moved to the root node of the "
5454 "document. If the destination is specified and exists then it will be "
5455 "overwritten; otherwise non-existing elements of the destination element "
5456 "path will be created."
5457 "@*@*"
5458 "When the @option{--inquire} option is passed then all remaining non-option "
5459 "arguments are retrieved via a server @emph{INQUIRE}."
5462 new_command("DELETE", 0, 0, 1, 0, delete_command, _(
5463 "DELETE [--inquire] element[<TAB>child[..]]\n" /* Deleting an element. */
5464 "Removes the specified element path and all of its children. This may break "
5465 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5466 "refers to this element or any of its children."
5467 "@*@*"
5468 "When the @option{--inquire} option is passed then all remaining non-option "
5469 "arguments are retrieved via a server @emph{INQUIRE}."
5472 new_command("GET", 0, 0, 1, 0, get_command, _(
5473 "GET [--inquire] element[<TAB>child[..]]\n" /* Getting the content of an element. */
5474 "Retrieves the content of the specified element. The content is returned "
5475 "with a data response."
5476 "@*@*"
5477 "When the @option{--inquire} option is passed then all remaining non-option "
5478 "arguments are retrieved via a server @emph{INQUIRE}."
5481 new_command("ATTR", 0, 0, 1, 0, attr_command, _(
5482 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n" /* Modifying element attributes. */
5483 "@table @asis\n"
5484 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
5485 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5486 "element. When no @var{value} is specified any existing value will be removed."
5487 "@*@*"
5488 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
5489 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
5490 "or @code{target} an error is returned. Use the @command{DELETE} command "
5491 "(@pxref{DELETE}) instead."
5492 "@*@*"
5493 "@item ATTR LIST element[<TAB>child[..]]\n"
5494 " Retrieves a newline separated list of attributes names and values "
5495 "from the specified element. Each attribute name and value is space delimited."
5496 "@*@*"
5497 "@item ATTR GET attribute element[<TAB>child[..]]\n"
5498 " Retrieves the value of an @var{attribute} from an element."
5499 "@end table\n"
5500 "@*@*"
5501 "When the @option{--inquire} option is passed then all remaining non-option "
5502 "arguments are retrieved via a server @emph{INQUIRE}."
5503 "@*@*"
5504 "@xref{Target Attribute}, for details about this special attribute and also "
5505 "@pxref{Other Attributes} for other attributes that are handled specially "
5506 "by @command{pwmd}."
5509 new_command("XPATH", 0, 0, 1, 0, xpath_command, _(
5510 "XPATH [--inquire] <expression>[<TAB>[value]]\n" /* Modifying more than one element. */
5511 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5512 "specified it is assumed the expression is a request to return a result. "
5513 "Otherwise, the result is set to the @var{value} argument and the document is "
5514 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5515 "is assumed to be empty and the document is updated. For example:"
5516 "@sp 1\n"
5517 "@example\n"
5518 "XPATH //element[@@_name='password']@key{TAB}\n"
5519 "@end example\n"
5520 "@sp 1\n"
5521 "would clear the content of all @var{password} elements in the data file "
5522 "while leaving off the trailing @key{TAB} would return all @var{password} "
5523 "elements in @abbr{XML} format."
5524 "@*@*"
5525 "When the @option{--inquire} option is passed then all remaining non-option "
5526 "arguments are retrieved via a server @emph{INQUIRE}."
5527 "@*@*"
5528 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5529 "expression syntax."
5532 new_command("XPATHATTR", 0, 0, 1, 0, xpathattr_command, _(
5533 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n" /* Modifying more than one element's attributes. */
5534 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5535 "attributes and does not return a result. For the @var{SET} operation the "
5536 "@var{value} is optional but the field is required. If not specified then "
5537 "the attribute value will be empty. For example:"
5538 "@sp 1\n"
5539 "@example\n"
5540 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5541 "@end example\n"
5542 "@sp 1\n"
5543 "would create a @var{password} attribute for each @var{password} element "
5544 "found in the document. The attribute value will be empty but still exist."
5545 "@*@*"
5546 "When the @option{--inquire} option is passed then all remaining non-option "
5547 "arguments are retrieved via a server @emph{INQUIRE}."
5548 "@*@*"
5549 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5550 "expression syntax."
5553 new_command("IMPORT", 0, 0, 1, 0, import_command, _(
5554 "IMPORT [--root=element[<TAB>child[..]]]\n" /* Creating elements from XML. */
5555 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5556 "@*@*"
5557 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5558 "argument is raw @abbr{XML} data. The content is created as a child of "
5559 "the element path specified with the @option{--root} option or at the "
5560 "document root when not specified. Existing elements of the same name will "
5561 "be overwritten."
5562 "@*@*"
5563 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5564 "for details."
5567 new_command("DUMP", 0, 1, 1, 0, dump_command, _(
5568 "DUMP\n" /* Showing the XML document. */
5569 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5570 "dumping a specific node."
5573 new_command("LOCK", 0, 0, 0, 0, lock_command, _(
5574 "LOCK\n" /* Locking the current data file. */
5575 "Locks the mutex associated with the opened file. This prevents other clients "
5576 "from sending commands to the same opened file until the client "
5577 "that sent this command either disconnects or sends the @code{UNLOCK} "
5578 "command. @xref{UNLOCK}."
5581 new_command("UNLOCK", 0, 1, 0, 0, unlock_command, _(
5582 "UNLOCK\n" /* Removing a data file lock. */
5583 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5584 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5585 "@pxref{ISCACHED})."
5588 new_command("GETCONFIG", 0, 1, 1, 0, getconfig_command, _(
5589 "GETCONFIG [filename] <parameter>\n" /* Obtaining a configuration value. */
5590 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5591 "data response. If no file has been opened then the value for @var{filename} "
5592 "or the default from the @var{global} section will be returned. If a file "
5593 "has been opened and no @var{filename} is specified, the value previously "
5594 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5597 new_command("OPTION", 0, 1, 1, 0, option_command, _(
5598 "OPTION <NAME>=[<VALUE>]\n" /* Setting various client parameters. */
5599 "Sets a client option @var{name} to @var{value}. The value for an option is "
5600 "kept for the duration of the connection with the exception of the "
5601 "@command{pinentry} options which are defaults for all future connections "
5602 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
5603 "@*@*"
5604 "@table @asis\n"
5605 "@item DISABLE-PINENTRY\n"
5606 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
5607 "server inquire is sent to the client to obtain the passphrase. This option "
5608 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5609 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
5610 "to use a @command{pinentry}."
5611 "@*@*"
5612 "@item DISPLAY\n"
5613 "Set or unset the X11 display to use when prompting for a passphrase."
5614 "@*@*"
5615 "@item TTYNAME\n"
5616 "Set the terminal device path to use when prompting for a passphrase."
5617 "@*@*"
5618 "@item TTYTYPE\n"
5619 "Set the terminal type for use with @option{TTYNAME}."
5620 "@*@*"
5621 "@item NAME\n"
5622 "Associates the thread ID of the connection with the specified textual "
5623 "representation. Useful for debugging log messages. May not contain whitespace."
5624 "@*@*"
5625 "@item LOCK-TIMEOUT\n"
5626 "When not @code{0}, the duration in tenths of a second to wait for the file "
5627 "mutex which has been locked by another thread to be released before returning "
5628 "an error. When @code{-1} the error will be returned immediately."
5629 "@*@*"
5630 "@item CLIENT-STATE\n"
5631 "When set to @code{1} then client state status messages for other clients are "
5632 "sent to the current client. The default is @code{0}."
5633 "@end table\n"
5636 new_command("LS", 0, 1, 1, 0, ls_command, _(
5637 "LS [--verbose]\n" /* Showing available data files. */
5638 "Returns a newline separated list of data files stored in the data directory "
5639 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response. When the "
5640 "@var{--verbose} option is passed, the space-separated filesystem inode "
5641 "access, modification and change times are appended to the line."
5644 new_command("BULK", 0, 1, 1, 0, bulk_command, _(
5645 "BULK [--inquire]\n" /* Run a series of commands in sequence. */
5646 "Parses a semi-canonical s-expression representing a series of protocol "
5647 "commands to be run in seqeunce (@pxref{Bulk Commands}). Returns a canonical "
5648 "s-expression containing each commands id, return value and result data "
5649 "(if any)."
5650 "@*@*"
5651 "When the @option{--inquire} option is passed then all remaining non-option "
5652 "arguments are retrieved via a server @emph{INQUIRE}."
5655 new_command("RESET", 0, 1, 1, 0, NULL, _(
5656 "RESET\n" /* Resetting the client state. */
5657 "Closes the currently opened file but keeps any previously set client options "
5658 "(@pxref{OPTION})."
5661 new_command("NOP", 0, 1, 1, 0, nop_command, _(
5662 "NOP\n" /* Testing the connection. */
5663 "This command does nothing. It is useful for testing the connection for a "
5664 "timeout condition."
5667 /* !END-HELP-TEXT! */
5668 new_command ("CANCEL", 0, 1, 1, 0, NULL, NULL);
5669 new_command ("END", 0, 1, 1, 0, NULL, NULL);
5670 new_command ("BYE", 0, 1, 1, 0, NULL, NULL);
5672 int i;
5673 for (i = 0; command_table[i]; i++);
5674 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5675 sort_commands);
5678 gpg_error_t
5679 register_commands (assuan_context_t ctx)
5681 int i = 0, rc;
5683 for (; command_table[i]; i++)
5685 if (!command_table[i]->handler)
5686 continue;
5688 rc = assuan_register_command (ctx, command_table[i]->name,
5689 command_table[i]->handler,
5690 command_table[i]->help);
5691 if (rc)
5692 return rc;
5695 rc = assuan_register_bye_notify (ctx, bye_notify);
5696 if (rc)
5697 return rc;
5699 rc = assuan_register_reset_notify (ctx, reset_notify);
5700 if (rc)
5701 return rc;
5703 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5704 if (rc)
5705 return rc;
5707 return assuan_register_post_cmd_notify (ctx, command_finalize);