Match internal assuan protocol commands in command_startup(). Fixes
[pwmd.git] / src / commands.c
blobc3bb2c6ab98d1e8ab313a8f54065715b2e355c11
1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
2 /*
3 Copyright (C) 2006-2009 Ben Kibbey <bjk@luxsci.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02110-1301 USA
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <err.h>
23 #include <errno.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <fcntl.h>
27 #include <ctype.h>
28 #include <glib.h>
29 #include <gcrypt.h>
30 #include <zlib.h>
32 #ifdef HAVE_CONFIG_H
33 #include <config.h>
34 #endif
36 #ifdef WITH_LIBACL
37 #include <sys/acl.h>
38 #endif
40 #include "mem.h"
41 #include "xml.h"
42 #include "common.h"
44 #ifdef WITH_PINENTRY
45 #include "pinentry.h"
46 #endif
48 #include "pwmd_error.h"
49 #include "cache.h"
50 #include "misc.h"
51 #include "commands.h"
52 #include "lock.h"
54 struct gz_s {
55 z_stream z;
56 gpointer out;
57 gboolean done;
58 status_msg_t which;
61 static void *z_alloc(void *data, unsigned items, unsigned size)
63 return gcry_calloc(items, size);
66 static void z_free(void *data, void *p)
68 gcry_free(p);
71 static gpg_error_t file_modified(struct client_s *client)
73 struct stat st;
74 gpg_error_t rc;
76 if (client->state != STATE_OPEN)
77 return EPWMD_NO_FILE;
79 rc = lock_file_mutex(client);
81 if (rc)
82 return rc;
84 if (lstat(client->filename, &st) == 0 && client->mtime) {
85 if (client->mtime != st.st_mtime)
86 return EPWMD_FILE_MODIFIED;
89 pth_cancel_point();
90 return 0;
93 static gpg_error_t parse_xml(assuan_context_t ctx)
95 struct client_s *client = assuan_get_pointer(ctx);
97 client->doc = xmlReadMemory(client->xml, client->len, NULL, "UTF-8", XML_PARSE_NOBLANKS);
99 if (!client->doc)
100 return EPWMD_LIBXML_ERROR;
102 return 0;
105 void unlock_file_mutex(struct client_s *client)
107 pth_mutex_t *m;
109 #ifdef WITH_PINENTRY
110 if (client->has_lock == FALSE || client->pinentry->status != PINENTRY_NONE)
111 #else
112 if (client->has_lock == FALSE)
113 #endif
114 return;
116 CACHE_LOCK(client->ctx);
118 if (cache_get_mutex(client->md5file, &m) == FALSE) {
119 CACHE_UNLOCK;
120 return;
123 CACHE_UNLOCK;
124 MUTEX_UNLOCK(m);
125 client->has_lock = client->is_lock_cmd = FALSE;
128 gpg_error_t lock_file_mutex(struct client_s *client)
130 pth_mutex_t *m;
131 gpg_error_t rc = 0;
133 if (client->has_lock == TRUE)
134 return 0;
136 CACHE_LOCK(client->ctx);
138 if (cache_get_mutex(client->md5file, &m) == FALSE) {
139 CACHE_UNLOCK;
140 return 0;
143 CACHE_UNLOCK;
144 MUTEX_TRYLOCK(client->ctx, m, rc);
146 if (!rc)
147 client->has_lock = TRUE;
149 return rc;
152 void free_client(struct client_s *client)
154 if (client->doc)
155 xmlFreeDoc(client->doc);
157 if (client->xml)
158 gcry_free(client->xml);
160 if (client->filename)
161 g_free(client->filename);
163 if (client->crypto)
164 cleanup_crypto(&client->crypto);
166 if (client->xml_error)
167 xmlResetError(client->xml_error);
170 void cleanup_client(struct client_s *client)
172 assuan_context_t ctx = client->ctx;
173 struct client_thread_s *thd = client->thd;
174 gboolean has_lock = client->has_lock;
175 #ifdef WITH_PINENTRY
176 struct pinentry_s *pin = client->pinentry;
177 #endif
179 unlock_file_mutex(client);
180 CACHE_LOCK(client->ctx);
181 cache_decr_refcount(client->md5file);
184 * This may be a new file so don't use a cache slot. save_command() will
185 * set this to FALSE on success.
187 if (client->new == TRUE)
188 cache_clear(client->md5file, 1);
190 CACHE_UNLOCK;
191 free_client(client);
192 memset(client, 0, sizeof(struct client_s));
193 client->state = STATE_CONNECTED;
194 client->ctx = ctx;
195 client->thd = thd;
196 client->freed = TRUE;
197 #ifdef WITH_PINENTRY
198 client->pinentry = pin;
199 #endif
200 client->has_lock = has_lock;
203 static void gz_cleanup(void *arg)
205 struct gz_s **gz = (struct gz_s **)arg;
207 if (!gz)
208 return;
210 if (!(*gz)->done && (*gz)->out)
211 gcry_free((*gz)->out);
213 if ((*gz)->which == STATUS_COMPRESS) {
214 if ((*gz)->z.zalloc)
215 deflateEnd(&(*gz)->z);
217 else {
218 if ((*gz)->z.zalloc)
219 inflateEnd(&(*gz)->z);
222 g_free(*gz);
223 *gz = NULL;
226 gboolean do_decompress(assuan_context_t ctx, gpointer in, gulong insize,
227 gpointer *out, gulong *outsize, gint *rc)
229 struct gz_s *gz;
230 gz_header h;
231 gchar buf[17];
233 gz = g_malloc0(sizeof(struct gz_s));
235 if (!gz) {
236 *rc = gpg_error_from_errno(ENOMEM);
237 return FALSE;
240 pth_cleanup_push(gz_cleanup, &gz);
241 gz->which = STATUS_DECOMPRESS;
242 gz->z.zalloc = z_alloc;
243 gz->z.zfree = z_free;
244 gz->z.next_in = in;
245 gz->z.avail_in = (uInt)insize;
246 gz->z.avail_out = zlib_bufsize;
247 gz->z.next_out = gz->out = gcry_malloc(zlib_bufsize);
249 if (!gz->out) {
250 log_write("%s(%i): %s", __FUNCTION__, __LINE__, strerror(ENOMEM));
251 *rc = Z_MEM_ERROR;
252 pth_cleanup_pop(1);
253 return FALSE;
256 *rc = inflateInit2(&gz->z, 47);
258 if (*rc != Z_OK) {
259 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
260 pth_cleanup_pop(1);
261 return FALSE;
264 memset(&h, 0, sizeof(gz_header));
265 h.comment = (guchar *)buf;
266 h.comm_max = sizeof(buf);
267 *rc = inflateGetHeader(&gz->z, &h);
269 if (*rc != Z_OK) {
270 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
271 pth_cleanup_pop(1);
272 return FALSE;
275 *rc = inflate(&gz->z, Z_BLOCK);
277 if (*rc != Z_OK) {
278 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
279 pth_cleanup_pop(1);
280 return FALSE;
283 if (h.comment)
284 insize = (gulong)strtol((gchar *)h.comment, NULL, 10);
286 do {
287 gpointer p;
289 *rc = inflate(&gz->z, Z_FINISH);
291 switch (*rc) {
292 case Z_OK:
293 break;
294 case Z_BUF_ERROR:
295 if (!gz->z.avail_out) {
296 p = gcry_realloc(gz->out, gz->z.total_out + zlib_bufsize);
298 if (!p) {
299 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
300 *rc = Z_MEM_ERROR;
301 goto fail;
304 gz->out = p;
305 gz->z.next_out = gz->out + gz->z.total_out;
306 gz->z.avail_out = zlib_bufsize;
307 *rc = send_status(ctx, STATUS_DECOMPRESS, "%li %li",
308 gz->z.total_out, insize);
310 if (*rc)
311 goto fail;
313 break;
314 case Z_STREAM_END:
315 break;
316 default:
317 goto fail;
318 break;
320 } while (*rc != Z_STREAM_END);
322 *rc = send_status(ctx, STATUS_DECOMPRESS, "%li %li", gz->z.total_out,
323 insize);
325 if (*rc)
326 goto fail;
328 *out = gz->out;
329 *outsize = gz->z.total_out;
330 gz->done = TRUE;
331 pth_cleanup_pop(1);
332 *rc = 0;
333 return TRUE;
335 fail:
336 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
337 pth_cleanup_pop(1);
338 return FALSE;
341 file_header_internal_t *read_file_header(const gchar *filename, gboolean v1,
342 gpg_error_t *rc)
344 gint fd;
345 gsize len;
346 file_header_internal_t *fh = g_malloc0(sizeof(file_header_internal_t));
347 gsize fh_size;
348 gpointer p;
350 *rc = 0;
352 if (!fh) {
353 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
354 *rc = gpg_error_from_errno(ENOMEM);
355 return NULL;
358 pth_cleanup_push(g_free, fh);
359 fh_size = v1 ? sizeof(fh->fh1) : sizeof(fh->fh2);
361 if (lstat(filename, &fh->st) == -1) {
362 *rc = gpg_error_from_syserror();
363 pth_cleanup_pop(1);
364 return NULL;
367 if (!S_ISREG(fh->st.st_mode)) {
368 *rc = GPG_ERR_ENOANO;
369 pth_cleanup_pop(1);
370 return NULL;
373 fd = open(filename, O_RDONLY);
375 if (fd == -1) {
376 *rc = gpg_error_from_errno(errno);
377 pth_cleanup_pop(1);
378 return NULL;
381 pth_cleanup_push(close, (void *)fd);
382 p = v1 ? (void *)&fh->fh1 : (void *)&fh->fh2;
383 len = pth_read(fd, p, fh_size);
385 if (len != fh_size) {
386 gint n = errno;
387 pth_cleanup_pop(1);
388 pth_cleanup_pop(1);
389 *rc = gpg_error_from_errno(n);
390 return NULL;
393 fh->v1 = v1;
394 fh->fd = fd;
395 pth_cleanup_pop(0);
396 pth_cleanup_pop(0);
397 return fh;
400 static gpg_error_t open_command_finalize(assuan_context_t ctx, guchar *key,
401 gboolean cached)
403 struct client_s *client = assuan_get_pointer(ctx);
404 gpg_error_t rc;
405 gint timeout;
407 /* New file. */
408 if (!client->crypto->fh) {
409 if (key[0])
410 goto update_cache;
412 goto done;
415 rc = try_xml_decrypt(ctx, key, client->crypto, NULL, NULL);
417 if (rc) {
418 cleanup_client(client);
419 return send_error(ctx, rc);
422 update_cache:
423 CACHE_LOCK(client->ctx);
425 if (cached == FALSE) {
426 if (cache_update_key(client->md5file, key) == FALSE) {
427 cleanup_client(client);
428 CACHE_UNLOCK;
429 return send_syserror(ctx, ENOMEM);
432 timeout = get_key_file_integer(client->filename, "cache_timeout");
433 cache_reset_timeout(client->md5file, timeout);
435 else
436 cache_set_timeout(client->md5file, -2);
438 CACHE_UNLOCK;
440 done:
441 rc = parse_xml(ctx);
443 if (client->xml) {
444 gcry_free(client->xml);
445 client->xml = NULL;
448 if (!rc) {
449 if (client->new == FALSE)
450 send_status_all(STATUS_CACHE);
452 client->state = STATE_OPEN;
455 if (!rc && client->new == FALSE &&
456 client->crypto->fh->fh2.iter != (guint64)get_key_file_integer(client->filename, "iterations")) {
457 MUTEX_LOCK(&rcfile_mutex);
458 g_key_file_set_integer(keyfileh, client->filename, "iterations",
459 client->crypto->fh->fh2.iter);
460 MUTEX_UNLOCK(&rcfile_mutex);
461 send_status_all(STATUS_CONFIG);
464 if (!rc)
465 log_write("OPEN '%s'", client->filename);
467 cleanup_crypto(&client->crypto);
468 return send_error(ctx, rc);
471 static void req_cleanup(void *arg)
473 if (!arg)
474 return;
476 g_strfreev((gchar **)arg);
479 static int open_command(assuan_context_t ctx, char *line)
481 gboolean cached = FALSE;
482 gpg_error_t rc;
483 struct client_s *client = assuan_get_pointer(ctx);
484 gchar **req;
485 gchar *filename = NULL;
487 if ((req = split_input_line(line, " ", 2)) != NULL)
488 filename = req[0];
490 pth_cleanup_push(req_cleanup, req);
492 if (!filename || !*filename) {
493 pth_cleanup_pop(1);
494 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
497 if (valid_filename(filename) == FALSE) {
498 pth_cleanup_pop(1);
499 return send_error(ctx, EPWMD_INVALID_FILENAME);
502 if (client->state == STATE_OPEN)
503 cleanup_client(client);
505 gcry_md_hash_buffer(GCRY_MD_MD5, client->md5file, filename, strlen(filename));
506 CACHE_LOCK(client->ctx);
508 if (cache_has_file(client->md5file) == FALSE) {
509 if (cache_add_file(client->md5file, NULL) == FALSE) {
510 pth_cleanup_pop(1);
511 CACHE_UNLOCK;
512 return send_syserror(ctx, ENOMEM);
516 cache_incr_refcount(client->md5file);
517 CACHE_UNLOCK;
518 rc = lock_file_mutex(client);
520 if (rc) {
521 pth_cleanup_pop(1);
522 return send_error(ctx, rc);
525 client->freed = FALSE;
526 client->crypto = init_client_crypto();
528 if (!client->crypto) {
529 pth_cleanup_pop(1);
530 cleanup_client(client);
531 return send_syserror(ctx, ENOMEM);
534 client->crypto->key = gcry_malloc(gcrykeysize);
536 if (!client->crypto->key) {
537 pth_cleanup_pop(1);
538 log_write("%s(%i): %s", __FUNCTION__, __LINE__,
539 gpg_error_from_errno(ENOMEM));
540 cleanup_client(client);
541 return send_syserror(ctx, ENOMEM);
544 memset(client->crypto->key, 0, gcrykeysize);
545 client->crypto->fh = read_file_header(filename, FALSE, &rc);
547 if (!client->crypto->fh) {
548 if (gpg_err_code_to_errno(rc) != ENOENT) {
549 log_write("%s: %s", filename, pwmd_strerror(rc));
550 pth_cleanup_pop(1);
551 cleanup_client(client);
552 return send_error(ctx, rc);
556 * New files don't need a key.
558 if ((client->xml = new_document()) == NULL) {
559 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
560 pth_cleanup_pop(1);
561 cleanup_client(client);
562 return send_syserror(ctx, ENOMEM);
565 client->len = xmlStrlen(client->xml);
566 client->new = TRUE;
567 client->filename = g_strdup(filename);
569 if (!client->filename) {
570 pth_cleanup_pop(1);
571 cleanup_client(client);
572 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
573 return send_syserror(ctx, ENOMEM);
576 if (req[1] && *req[1])
577 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, req[1],
578 strlen(req[1]));
580 pth_cleanup_pop(1);
581 #ifdef WITH_PINENTRY
582 client->pinentry->filename = g_strdup(client->filename);
584 if (!client->pinentry->filename) {
585 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
586 cleanup_client(client);
587 return send_syserror(ctx, ENOMEM);
589 #endif
590 return open_command_finalize(ctx, client->crypto->key, cached);
592 else
593 client->mtime = client->crypto->fh->st.st_mtime;
595 client->filename = g_strdup(filename);
597 if (!client->filename) {
598 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
599 pth_cleanup_pop(1);
600 cleanup_client(client);
601 return send_syserror(ctx, ENOMEM);
604 #ifdef WITH_PINENTRY
605 client->pinentry->filename = g_strdup(client->filename);
607 if (!client->pinentry->filename) {
608 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
609 pth_cleanup_pop(1);
610 cleanup_client(client);
611 return send_syserror(ctx, ENOMEM);
613 #endif
615 if (client->crypto->fh->fh2.iter <= 0)
616 goto done;
618 CACHE_LOCK(client->ctx);
619 cached = cache_get_key(client->md5file, client->crypto->key);
620 CACHE_UNLOCK;
622 if (cached == FALSE) {
623 gchar *tmp = get_key_file_string(filename, "key_file");
625 if (tmp) {
626 g_free(tmp);
627 pth_cleanup_pop(1);
628 cleanup_client(client);
629 return send_error(ctx, GPG_ERR_WRONG_KEY_USAGE);
633 * No key specified and no matching filename found in the cache. Use
634 * pinentry to retrieve the key. Cannot return assuan_process_done()
635 * here otherwise the command will be interrupted. The event loop in
636 * client_thread() will poll the file descriptor waiting for it to
637 * become ready to read a pinentry_key_s which will contain the
638 * entered key or an error code. It will then call
639 * open_command_finalize() to to finish the command.
641 if (!req[1] || !*req[1]) {
642 #ifdef WITH_PINENTRY
643 gboolean b = get_key_file_boolean(filename, "enable_pinentry");
645 /* From set_pinentry_defaults(). */
646 if (client->pinentry->enable == FALSE ||
647 (client->pinentry->enable == -1 && b == FALSE)) {
648 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, "", 1);
649 goto done;
652 pth_cleanup_pop(1);
653 rc = lock_pin_mutex(client);
655 if (rc) {
656 unlock_pin_mutex(client->pinentry);
657 cleanup_client(client);
658 return send_error(ctx, rc);
661 client->pinentry->which = PINENTRY_OPEN;
662 rc = pinentry_fork(ctx);
664 if (rc) {
665 unlock_pin_mutex(client->pinentry);
666 cleanup_client(client);
667 return send_error(ctx, rc);
670 // Called from pinentry iterate.
671 client->pinentry->cb = open_command_finalize;
672 client->pinentry->status = PINENTRY_INIT;
673 return 0;
674 #else
675 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, "", 1);
676 goto done;
677 #endif
680 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, req[1],
681 strlen(req[1]));
684 done:
685 pth_cleanup_pop(1);
686 return open_command_finalize(ctx, client->crypto->key, cached);
689 gboolean do_compress(assuan_context_t ctx, gint level, gpointer data,
690 gulong size, gpointer *out, gulong *outsize, gint *rc)
692 struct gz_s *gz;
693 gz_header h;
694 gchar buf[17];
695 gint cmd = Z_NO_FLUSH;
697 gz = g_malloc0(sizeof(struct gz_s));
699 if (!gz) {
700 *rc = gpg_error_from_errno(ENOMEM);
701 return FALSE;
704 pth_cleanup_push(gz_cleanup, &gz);
705 gz->which = STATUS_COMPRESS;
706 gz->z.zalloc = z_alloc;
707 gz->z.zfree = z_free;
708 gz->z.next_in = data;
709 gz->z.avail_in = size < zlib_bufsize ? (uInt)size : (uInt)zlib_bufsize;
710 gz->z.avail_out = (uInt)zlib_bufsize;
711 gz->z.next_out = gz->out = gcry_malloc(zlib_bufsize);
713 if (!gz->out) {
714 log_write("%s(%i): %s", __FUNCTION__, __LINE__, strerror(ENOMEM));
715 *rc = Z_MEM_ERROR;
716 pth_cleanup_pop(1);
717 return FALSE;
720 *rc = deflateInit2(&gz->z, level, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY);
722 if (*rc != Z_OK) {
723 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
724 pth_cleanup_pop(1);
725 return FALSE;
728 /* Rather than store the size of the uncompressed data in the file header,
729 * store it in the comment field of the gzip header. Don't give anyone too
730 * much information. Not sure why really, but it seems the right way. :)
732 memset(&h, 0, sizeof(gz_header));
733 g_snprintf(buf, sizeof(buf), "%li", size);
734 h.comment = (guchar *)buf;
735 *rc = deflateSetHeader(&gz->z, &h);
737 if (*rc != Z_OK) {
738 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
739 pth_cleanup_pop(1);
740 return FALSE;
743 do {
744 gpointer p;
746 *rc = deflate(&gz->z, cmd);
748 switch (*rc) {
749 case Z_OK:
750 break;
751 case Z_BUF_ERROR:
752 if (!gz->z.avail_out) {
753 p = gcry_realloc(gz->out, gz->z.total_out + zlib_bufsize);
755 if (!p) {
756 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
757 *rc = Z_MEM_ERROR;
758 goto fail;
761 gz->out = p;
762 gz->z.next_out = gz->out + gz->z.total_out;
763 gz->z.avail_out = zlib_bufsize;
766 if (!gz->z.avail_in && gz->z.total_in < size) {
767 if (gz->z.total_in + zlib_bufsize > size)
768 gz->z.avail_in = size - gz->z.total_in;
769 else
770 gz->z.avail_in = zlib_bufsize;
772 *rc = send_status(ctx, STATUS_COMPRESS, "%li %li",
773 gz->z.total_in, size);
775 if (*rc)
776 goto fail;
779 if (gz->z.total_in >= size)
780 cmd = Z_FINISH;
782 break;
783 case Z_STREAM_END:
784 break;
785 default:
786 goto fail;
788 } while (*rc != Z_STREAM_END);
790 *rc = send_status(ctx, STATUS_COMPRESS, "%li %li", gz->z.total_in, size);
792 if (*rc)
793 goto fail;
795 *out = gz->out;
796 *outsize = gz->z.total_out;
797 *rc = 0;
798 gz->done = TRUE;
799 pth_cleanup_pop(1);
800 return TRUE;
802 fail:
803 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
804 pth_cleanup_pop(1);
805 return FALSE;
808 #define CRYPTO_BLOCKSIZE (gcryblocksize * 1024)
810 static gpg_error_t iterate_crypto_once(struct client_s *client,
811 struct client_crypto_s *crypto, status_msg_t which)
813 gpg_error_t rc = 0;
814 goffset len = CRYPTO_BLOCKSIZE;
815 gpointer p = gcry_malloc(len);
816 goffset total = 0;
817 gpointer inbuf;
819 if (!p)
820 return gpg_err_code_from_errno(ENOMEM);
822 if (crypto->insize < CRYPTO_BLOCKSIZE)
823 len = crypto->insize;
825 pth_cleanup_push(gcry_free, p);
827 for (;;) {
828 inbuf = crypto->inbuf + total;
829 guchar *tmp;
831 if (len + total > crypto->insize)
832 len = gcryblocksize;
834 if (which == STATUS_ENCRYPT)
835 rc = gcry_cipher_encrypt(crypto->gh, p, len, inbuf, len);
836 else
837 rc = gcry_cipher_decrypt(crypto->gh, p, len, inbuf, len);
839 if (rc)
840 goto done;
842 tmp = crypto->inbuf+total;
843 memmove(tmp, p, len);
844 total += len;
846 if (total >= crypto->insize)
847 break;
849 pth_cancel_point();
852 done:
853 pth_cleanup_pop(1);
854 return rc;
857 /* The crypto struct must be setup for iterations and .key. */
858 gpg_error_t do_xml_encrypt(struct client_s *client,
859 struct client_crypto_s *crypto, const gchar *filename)
861 goffset len = crypto->insize;
862 gpointer inbuf;
863 gchar *p;
864 gpg_error_t rc;
865 guint64 iter_progress = 0, n_iter = 0, xiter = 0;
866 gchar tmp[FILENAME_MAX];
867 struct stat st;
868 mode_t mode = 0;
870 if (!crypto->fh->fh2.iter) {
872 * cache_file_count() needs both .used == TRUE and a valid key in
873 * order for it to count as a used cache entry. Fixes CACHE status
874 * messages.
876 memset(crypto->key, '!', gcrykeysize);
877 goto write_file;
881 * Resize the existing xml buffer to the block size required by gcrypt
882 * rather than duplicating it and wasting memory.
884 if (crypto->insize / gcryblocksize) {
885 len = (crypto->insize / gcryblocksize) * gcryblocksize;
887 if (crypto->insize % gcryblocksize)
888 len += gcryblocksize;
891 inbuf = gcry_realloc(crypto->inbuf, len);
893 if (!inbuf) {
894 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
895 return gpg_error_from_errno(ENOMEM);
898 crypto->inbuf = inbuf;
899 crypto->insize = len;
900 gcry_create_nonce(crypto->fh->fh2.iv, sizeof(crypto->fh->fh2.iv));
901 crypto->tkey = gcry_malloc(gcrykeysize);
903 if (!crypto->tkey) {
904 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
905 return gpg_error_from_errno(ENOMEM);
908 memcpy(crypto->tkey, crypto->key, gcrykeysize);
909 guchar *tkey = crypto->tkey;
910 tkey[0] ^= 1;
912 if ((rc = gcry_cipher_setkey(crypto->gh, crypto->tkey, gcrykeysize))) {
913 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
914 return rc;
917 iter_progress = (guint64)get_key_file_integer(
918 client ? client->filename : "global", "iteration_progress");
920 if (iter_progress && crypto->fh->fh2.iter >= iter_progress) {
921 rc = send_status(client ? client->ctx : NULL, STATUS_ENCRYPT,
922 "0 %llu", crypto->fh->fh2.iter);
924 if (rc)
925 return rc;
928 while (xiter < crypto->fh->fh2.iter-1) {
929 if (iter_progress > 0 && xiter >= iter_progress) {
930 if (!(xiter % iter_progress)) {
931 rc = send_status(client ? client->ctx : NULL, STATUS_ENCRYPT,
932 "%llu %llu", ++n_iter * iter_progress,
933 crypto->fh->fh2.iter);
935 if (rc)
936 return rc;
940 if ((rc = gcry_cipher_setiv(crypto->gh, crypto->fh->fh2.iv,
941 sizeof(crypto->fh->fh2.iv)))) {
942 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
943 return rc;
946 rc = iterate_crypto_once(client, crypto, STATUS_ENCRYPT);
948 if (rc) {
949 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
950 return rc;
953 xiter++;
956 if ((rc = gcry_cipher_setiv(crypto->gh, crypto->fh->fh2.iv,
957 sizeof(crypto->fh->fh2.iv)))) {
958 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
959 return rc;
962 if ((rc = gcry_cipher_setkey(crypto->gh, crypto->key, gcrykeysize))) {
963 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
964 return rc;
967 rc = iterate_crypto_once(client, crypto, STATUS_ENCRYPT);
969 if (rc)
970 return rc;
972 if (iter_progress && crypto->fh->fh2.iter >= iter_progress) {
973 rc = send_status(client ? client->ctx : NULL, STATUS_ENCRYPT,
974 "%llu %llu", crypto->fh->fh2.iter, crypto->fh->fh2.iter);
976 if (rc)
977 return rc;
980 write_file:
981 tmp[0] = 0;
983 if (filename) {
984 if (!client && !g_strcmp0(filename, "-")) {
985 crypto->fh->fd = STDOUT_FILENO;
986 goto do_write_file;
989 if (lstat(filename, &st) == 0) {
990 mode = st.st_mode & (S_IRWXU|S_IRWXG|S_IRWXO);
992 if (!(mode & S_IWUSR))
993 return gpg_error_from_errno(EACCES);
995 else if (errno != ENOENT)
996 return gpg_error_from_errno(errno);
998 g_snprintf(tmp, sizeof(tmp), "%s.XXXXXX", filename);
999 crypto->fh->fd = mkstemp(tmp);
1001 if (crypto->fh->fd == -1) {
1002 rc = errno;
1003 p = strrchr(tmp, '/');
1004 p++;
1005 log_write("%s: %s", p, strerror(rc));
1006 return gpg_error_from_errno(rc);
1009 pth_cleanup_push(unlink, tmp);
1011 else
1013 * xml_import() or convert_file() from command line.
1015 crypto->fh->fd = STDOUT_FILENO;
1017 do_write_file:
1018 crypto->fh->fh2.magic[0] = '\177';
1019 crypto->fh->fh2.magic[1] = 'P';
1020 crypto->fh->fh2.magic[2] = 'W';
1021 crypto->fh->fh2.magic[3] = 'M';
1022 crypto->fh->fh2.magic[4] = 'D';
1023 crypto->fh->fh2.version = VERSION_HEX;
1024 len = pth_write(crypto->fh->fd, &crypto->fh->fh2, sizeof(crypto->fh->fh2));
1026 if (len != sizeof(crypto->fh->fh2)) {
1027 len = errno;
1029 if (tmp[0])
1030 pth_cleanup_pop(1);
1032 return gpg_error_from_errno(len);
1035 len = pth_write(crypto->fh->fd, crypto->inbuf, crypto->insize);
1037 if (len != crypto->insize) {
1038 len = errno;
1040 if (tmp[0])
1041 pth_cleanup_pop(1);
1043 return gpg_error_from_errno(len);
1046 if (fsync(crypto->fh->fd) == -1) {
1047 len = errno;
1049 if (tmp[0])
1050 pth_cleanup_pop(1);
1052 return gpg_error_from_errno(len);
1055 if (tmp[0]) {
1056 #ifdef WITH_LIBACL
1057 acl_t acl;
1058 #endif
1059 if (mode && get_key_file_boolean(filename, "backup") == TRUE) {
1060 gchar tmp2[FILENAME_MAX];
1062 g_snprintf(tmp2, sizeof(tmp2), "%s.backup", filename);
1063 #ifdef WITH_LIBACL
1064 acl = acl_get_file(filename, ACL_TYPE_ACCESS);
1066 if (!acl)
1067 log_write("ACL: %s: %s", filename, strerror(errno));
1068 #endif
1070 if (rename(filename, tmp2) == -1) {
1071 len = errno;
1072 pth_cleanup_pop(1);
1073 #ifdef WITH_LIBACL
1074 if (acl)
1075 acl_free(acl);
1076 #endif
1077 return gpg_error_from_errno(len);
1080 #ifdef WITH_LIBACL
1081 else {
1082 acl = acl_get_file(".", ACL_TYPE_DEFAULT);
1084 if (!acl)
1085 log_write("ACL: %s: %s", filename, strerror(errno));
1087 #endif
1089 if (rename(tmp, filename) == -1) {
1090 len = errno;
1091 pth_cleanup_pop(1);
1092 #ifdef WITH_LIBACL
1093 if (acl)
1094 acl_free(acl);
1095 #endif
1096 return gpg_error_from_errno(len);
1099 pth_cleanup_pop(0);
1101 if (mode)
1102 chmod(filename, mode);
1104 #ifdef WITH_LIBACL
1105 if (acl && acl_set_file(filename, ACL_TYPE_ACCESS, acl))
1106 log_write("ACL: %s: %s", filename, strerror(errno));
1108 if (acl)
1109 acl_free(acl);
1110 #endif
1113 if (client && lstat(filename, &st) == 0)
1114 client->mtime = st.st_mtime;
1116 return 0;
1119 static gpg_error_t save_command_finalize(assuan_context_t ctx, guchar *key,
1120 gboolean cached)
1122 struct client_s *client = assuan_get_pointer(ctx);
1123 gpointer xmlbuf;
1124 gulong len, outsize = 0;
1125 guint iter;
1126 gint timeout;
1127 gpointer outbuf;
1128 gint zrc;
1129 gpg_error_t rc;
1131 if (client->crypto->key && client->crypto->key != key)
1132 gcry_free(client->crypto->key);
1134 client->crypto->key = key;
1135 xmlDocDumpFormatMemory(client->doc, (xmlChar **)&xmlbuf, (gint *)&len, 0);
1136 pth_cleanup_push(xmlFree, xmlbuf);
1137 iter = (guint)get_key_file_integer(client->filename, "compression_level");
1139 if (iter < 0)
1140 iter = 0;
1142 if (do_compress(ctx, (gint)iter, xmlbuf, len, &outbuf, &outsize, &zrc)
1143 == FALSE) {
1144 pth_cleanup_pop(1);
1145 cleanup_crypto(&client->crypto);
1147 if (zrc == Z_MEM_ERROR)
1148 return send_syserror(ctx, ENOMEM);
1149 else
1150 return send_error(ctx, GPG_ERR_COMPR_ALGO);
1152 else {
1153 pth_cleanup_pop(1);
1154 xmlbuf = outbuf;
1155 len = outsize;
1158 client->crypto->fh = g_malloc0(sizeof(file_header_internal_t));
1160 if (!client->crypto->fh) {
1161 cleanup_crypto(&client->crypto);
1162 gcry_free(outbuf);
1163 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1164 return send_syserror(ctx, ENOMEM);
1167 iter = get_key_file_integer(client->filename, "iterations");
1168 client->crypto->fh->fh2.iter = iter < 0 ? 0 : iter;
1169 client->crypto->inbuf = xmlbuf;
1170 client->crypto->insize = len;
1171 rc = do_xml_encrypt(client, client->crypto, client->filename);
1173 if (rc) {
1174 cleanup_crypto(&client->crypto);
1175 return send_error(ctx, rc);
1178 timeout = get_key_file_integer(client->filename, "cache_timeout");
1179 CACHE_LOCK(client->ctx);
1181 if (cached) {
1182 cache_reset_timeout(client->md5file, timeout);
1183 CACHE_UNLOCK;
1185 if (client->new == TRUE)
1186 send_status_all(STATUS_CACHE);
1188 client->new = FALSE;
1189 cleanup_crypto(&client->crypto);
1190 return send_error(ctx, 0);
1193 if (cache_update_key(client->md5file, client->crypto->key) == FALSE) {
1194 CACHE_UNLOCK;
1195 cleanup_crypto(&client->crypto);
1196 return send_syserror(ctx, ENOMEM);
1199 client->new = FALSE;
1200 cache_reset_timeout(client->md5file, timeout);
1201 CACHE_UNLOCK;
1202 send_status_all(STATUS_CACHE);
1203 cleanup_crypto(&client->crypto);
1204 return send_error(ctx, 0);
1207 static int save_command(assuan_context_t ctx, char *line)
1209 gboolean cached = FALSE;
1210 struct stat st;
1211 struct client_s *client = assuan_get_pointer(ctx);
1212 gpg_error_t rc;
1214 if (lstat(client->filename, &st) == -1 && errno != ENOENT)
1215 return send_syserror(ctx, errno);
1217 if (errno != ENOENT && !S_ISREG(st.st_mode)) {
1218 log_write("%s: %s", client->filename, pwmd_strerror(GPG_ERR_ENOANO));
1219 return send_error(ctx, GPG_ERR_ENOANO);
1222 CACHE_LOCK(ctx);
1223 cached = cache_iscached(client->md5file);
1224 CACHE_UNLOCK;
1227 * If a cache entry doesn't exist for this file and the file has a
1228 * "key_file" or "key" parameter, then it's an error. The reason is that
1229 * cache expiration would be useless.
1231 if (cached == FALSE) {
1232 gchar *tmp = get_key_file_string(client->filename, "key_file");
1234 if (tmp) {
1235 g_free(tmp);
1236 return send_error(ctx, GPG_ERR_WRONG_KEY_USAGE);
1240 cached = FALSE;
1241 client->crypto = init_client_crypto();
1243 if (!client->crypto) {
1244 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1245 return send_syserror(ctx, ENOMEM);
1248 client->crypto->key = gcry_malloc(gcrykeysize);
1250 if (!client->crypto->key) {
1251 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1252 cleanup_crypto(&client->crypto);
1253 return send_syserror(ctx, ENOMEM);
1256 memset(client->crypto->key, '!', gcrykeysize);
1258 if (get_key_file_integer(client->filename, "iterations") <= 0)
1259 goto done;
1261 if (!line || !*line) {
1262 client->crypto->tkey = gcry_malloc(gcrykeysize);
1264 if (!client->crypto->tkey) {
1265 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1266 cleanup_crypto(&client->crypto);
1267 return send_syserror(ctx, ENOMEM);
1270 memset(client->crypto->tkey, '!', gcrykeysize);
1271 CACHE_LOCK(ctx);
1273 if (cache_get_key(client->md5file, client->crypto->key) == FALSE ||
1274 memcmp(client->crypto->key, client->crypto->tkey,
1275 gcrykeysize) == 0) {
1276 CACHE_UNLOCK;
1278 #ifdef WITH_PINENTRY
1279 if (client->pinentry->enable == FALSE ||
1280 get_key_file_boolean(client->filename, "enable_pinentry") == FALSE) {
1281 /* Empty keys are allowed. */
1282 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, "", 1);
1283 goto done;
1286 lock_pin_mutex(client);
1287 client->pinentry->which = PINENTRY_SAVE;
1288 rc = pinentry_fork(ctx);
1290 if (rc) {
1291 unlock_pin_mutex(client->pinentry);
1292 return send_error(ctx, rc);
1295 client->pinentry->cb = save_command_finalize;
1296 client->pinentry->status = PINENTRY_INIT;
1297 return 0;
1298 #else
1299 /* Empty keys are allowed. */
1300 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, "", 1);
1301 goto done;
1302 #endif
1304 else {
1305 CACHE_UNLOCK;
1306 cached = TRUE;
1309 else
1310 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, line,
1311 strlen(line));
1313 done:
1314 return save_command_finalize(ctx, client->crypto->key, cached);
1317 static int delete_command(assuan_context_t ctx, char *line)
1319 struct client_s *client = assuan_get_pointer(ctx);
1320 gchar **req;
1321 gpg_error_t rc;
1322 xmlNodePtr n;
1324 if (strchr(line, '\t'))
1325 req = split_input_line(line, "\t", -1);
1326 else
1327 req = split_input_line(line, " ", -1);
1329 if (!req || !*req)
1330 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
1332 n = find_account(client->doc, &req, &rc, NULL, 0);
1334 if (!n) {
1335 g_strfreev(req);
1336 return send_error(ctx, rc);
1340 * No sub-node defined. Remove the entire node (account).
1342 if (!req[1]) {
1343 if (n) {
1344 xmlUnlinkNode(n);
1345 xmlFreeNode(n);
1348 g_strfreev(req);
1349 return send_error(ctx, 0);
1352 n = find_elements(client->doc, n->children, req+1, &rc, NULL, NULL, NULL, FALSE, 0, NULL);
1353 g_strfreev(req);
1355 if (!n)
1356 return send_error(ctx, rc);
1358 if (n) {
1359 xmlUnlinkNode(n);
1360 xmlFreeNode(n);
1363 return send_error(ctx, 0);
1367 * Don't return with assuan_process_done() here. This has been called from
1368 * assuan_process_next() and the command should be finished in
1369 * client_thread().
1371 static int store_command_finalize(gpointer data, gint assuan_rc, guchar *line,
1372 gsize len)
1374 assuan_context_t ctx = data;
1375 struct client_s *client = assuan_get_pointer(ctx);
1376 gchar **req;
1377 xmlNodePtr n;
1378 gpg_error_t rc = file_modified(client);
1380 if (assuan_rc || rc) {
1381 if (line)
1382 xfree(line);
1383 return assuan_rc ? assuan_rc : rc;
1386 req = split_input_line((gchar *)line, "\t", 0);
1387 xfree(line);
1389 if (!req || !*req)
1390 return EPWMD_COMMAND_SYNTAX;
1392 if (valid_xml_element((xmlChar *)*req) == FALSE) {
1393 g_strfreev(req);
1394 return EPWMD_INVALID_ELEMENT;
1397 if (valid_element_path(req+1, TRUE) == FALSE) {
1398 g_strfreev(req);
1399 return EPWMD_INVALID_ELEMENT;
1402 again:
1403 n = find_account(client->doc, &req, &rc, NULL, 0);
1405 if (rc && rc == EPWMD_ELEMENT_NOT_FOUND) {
1406 rc = new_account(client->doc, *req);
1408 if (rc) {
1409 g_strfreev(req);
1410 return rc;
1413 goto again;
1416 if (!n) {
1417 g_strfreev(req);
1418 return rc;
1421 if (req[1]) {
1422 if (!n->children)
1423 create_elements_cb(n, req+1, &rc, NULL);
1424 else
1425 find_elements(client->doc, n->children, req+1, &rc,
1426 NULL, NULL, create_elements_cb, FALSE, 0, NULL);
1429 g_strfreev(req);
1430 client->inquire_status = INQUIRE_DONE;
1431 return rc;
1434 static int store_command(assuan_context_t ctx, char *line)
1436 struct client_s *client = assuan_get_pointer(ctx);
1437 gpg_error_t rc;
1439 rc = assuan_inquire_ext(ctx, "STORE", 0, store_command_finalize, ctx);
1441 if (rc)
1442 return send_error(ctx, rc);
1444 /* Don't return with assuan_process_done() here. This is an INQUIRE. */
1445 client->inquire_status = INQUIRE_BUSY;
1446 return 0;
1449 static void *send_data_cb(void *arg)
1451 struct assuan_cmd_s *data = arg;
1452 gint old;
1453 gpg_error_t rc;
1455 pth_cancel_state(PTH_CANCEL_ENABLE|PTH_CANCEL_ASYNCHRONOUS, &old);
1456 rc = assuan_send_data(data->ctx, data->line, data->line_len);
1457 pth_cancel_state(old, NULL);
1458 pth_exit((void *)rc);
1459 return NULL;
1462 /* For every assuan command that needs to be sent to the client, a timeout is
1463 * needed to determine if the client lost the connection. The timeout is the
1464 * same as the "keepalive" configuration parameter or a default if unset.
1466 gpg_error_t do_assuan_command(assuan_context_t ctx,
1467 void *(*cb)(void *data), void *data)
1469 pth_attr_t attr = pth_attr_new();
1470 pth_t tid;
1471 gint n;
1472 gint to = get_key_file_integer("global", "keepalive");
1473 pth_event_t ev, tev;
1474 pth_status_t st;
1475 gpg_error_t rc;
1477 pth_attr_init(attr);
1478 pth_attr_set(attr, PTH_ATTR_JOINABLE, TRUE);
1479 pth_cleanup_push(pth_attr_destroy, attr);
1480 tid = pth_spawn(attr, cb, data);
1481 n = errno;
1482 pth_cleanup_pop(1);
1484 if (!tid) {
1485 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
1486 _gpg_strerror(gpg_error_from_errno(n)));
1487 return gpg_error_from_errno(n);
1490 pth_cleanup_push(pth_cancel, tid);
1491 to = to <= 0 ? DEFAULT_KEEPALIVE_TO : to;
1492 ev = pth_event(PTH_EVENT_TID|PTH_UNTIL_TID_DEAD, tid);
1493 tev = pth_event(PTH_EVENT_TIME, pth_timeout(to, 0));
1494 ev = pth_event_concat(ev, tev, NULL);
1495 pth_cleanup_push(cleanup_ev_cb, ev);
1496 pth_yield(tid);
1497 pth_wait(ev);
1498 st = pth_event_status(ev);
1500 if (st == PTH_STATUS_FAILED) {
1501 pth_cancel(tid);
1502 rc = GPG_ERR_ASS_WRITE_ERROR;
1504 else if (st == PTH_STATUS_OCCURRED)
1505 pth_join(tid, (void **)&rc);
1506 else {
1507 st = pth_event_status(tev);
1509 if (st == PTH_STATUS_OCCURRED) {
1510 pth_cancel(tid);
1511 rc = GPG_ERR_ASS_WRITE_ERROR;
1515 pth_cleanup_pop(1);
1516 pth_cleanup_pop(0);
1517 return rc;
1520 static gpg_error_t xfer_data(assuan_context_t ctx, const gchar *line,
1521 gint total)
1523 int to_send;
1524 int sent = 0;
1525 gpg_error_t rc;
1526 struct assuan_cmd_s data;
1527 int progress = get_key_file_integer("global", "xfer_progress");
1528 int flush = 0;
1530 progress = progress>0 ? (progress/ASSUAN_LINELENGTH)*ASSUAN_LINELENGTH : 0;
1531 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1532 data.ctx = ctx;
1533 rc = send_status(ctx, STATUS_XFER, "%li %li", sent, total);
1535 if (rc)
1536 return rc;
1538 again:
1539 do {
1540 if (sent + to_send > total)
1541 to_send = total - sent;
1543 data.line = flush ? NULL : (gchar *)line+sent;
1544 data.line_len = flush ? 0 : to_send;
1545 rc = do_assuan_command(ctx, send_data_cb, &data);
1547 if (!rc) {
1548 sent += flush ? 0 : to_send;
1550 if ((progress && !(sent % progress) && sent != total) ||
1551 (sent == total && flush))
1552 rc = send_status(ctx, STATUS_XFER, "%li %li", sent, total);
1554 if (!flush && !rc && sent == total) {
1555 flush = 1;
1556 goto again;
1559 } while (!rc && sent < total);
1561 return rc;
1564 static int get_command(assuan_context_t ctx, char *line)
1566 struct client_s *client = assuan_get_pointer(ctx);
1567 gchar **req;
1568 gpg_error_t rc;
1569 xmlNodePtr n;
1571 req = split_input_line(line, "\t", -1);
1573 if (!req || !*req) {
1574 g_strfreev(req);
1575 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
1578 n = find_account(client->doc, &req, &rc, NULL, 0);
1580 if (!n) {
1581 g_strfreev(req);
1582 return send_error(ctx, rc);
1585 if (req[1])
1586 n = find_elements(client->doc, n->children, req+1, &rc, NULL, NULL, NULL, FALSE, 0, NULL);
1588 g_strfreev(req);
1590 if (rc)
1591 return send_error(ctx, rc);
1593 if (!n || !n->children)
1594 return send_error(ctx, EPWMD_EMPTY_ELEMENT);
1596 n = find_text_node(n->children);
1598 if (!n || !n->content || !*n->content)
1599 return send_error(ctx, EPWMD_EMPTY_ELEMENT);
1601 rc = xfer_data(ctx, (gchar *)n->content, xmlStrlen(n->content));
1602 return send_error(ctx, rc);
1605 static xmlNodePtr realpath_elements_cb(xmlNodePtr node, gchar **target,
1606 gpg_error_t *rc, gchar **req_orig, void *data)
1608 gchar *path = *(gchar **)data;
1609 gchar *tmp = NULL, *result;
1611 if (path) {
1612 g_free(path);
1613 *(gchar **)data = NULL;
1616 path = g_strjoinv("\t", target);
1618 if (!path) {
1619 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1620 *rc = gpg_error_from_errno(ENOMEM);
1621 return NULL;
1624 if (req_orig) {
1625 tmp = g_strjoinv("\t", req_orig);
1627 if (!tmp) {
1628 g_free(path);
1629 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1630 *rc = gpg_error_from_errno(ENOMEM);
1631 return NULL;
1635 if (tmp && *tmp)
1636 result = g_strdup_printf("%s\t%s", path, tmp);
1637 else
1638 result = g_strdup(path);
1640 if (!result) {
1641 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1642 *rc = gpg_error_from_errno(ENOMEM);
1643 g_free(path);
1644 g_free(tmp);
1645 return NULL;
1648 g_free(path);
1649 g_free(tmp);
1650 *(gchar **)data = result;
1651 return node;
1654 static void list_command_cleanup1(void *arg);
1655 static int realpath_command(assuan_context_t ctx, char *line)
1657 gpg_error_t rc;
1658 struct client_s *client = assuan_get_pointer(ctx);
1659 gchar **req;
1660 gchar *t;
1661 gint i;
1662 xmlNodePtr n;
1663 GString *string;
1664 gchar *rp = NULL;
1666 if (strchr(line, '\t') != NULL) {
1667 if ((req = split_input_line(line, "\t", 0)) == NULL)
1668 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
1670 else {
1671 if ((req = split_input_line(line, " ", 0)) == NULL)
1672 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
1675 n = find_account(client->doc, &req, &rc, NULL, 0);
1677 if (!n) {
1678 g_strfreev(req);
1679 return send_error(ctx, rc);
1682 rp = g_strjoinv("\t", req);
1684 if (!rp) {
1685 g_strfreev(req);
1686 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1687 return send_syserror(ctx, ENOMEM);
1690 if (req[1]) {
1691 n = find_elements(client->doc, n->children, req+1, &rc,
1692 NULL, realpath_elements_cb, NULL, FALSE, 0, &rp);
1694 if (!n) {
1695 g_free(rp);
1696 g_strfreev(req);
1697 return send_error(ctx, rc);
1701 string = g_string_new(rp);
1702 g_free(rp);
1703 g_strfreev(req);
1705 if (!string) {
1706 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1707 return send_syserror(ctx, ENOMEM);
1710 again:
1711 for (i = 0, t = string->str + i; *t; t++, i++) {
1712 if ((!i && *t != '!') || (*t == '\t' && *(t+1) && *(t+1) != '!')) {
1713 string = g_string_insert_c(string, !i ? i++ : ++i, '!');
1714 goto again;
1718 pth_cleanup_push(list_command_cleanup1, string);
1719 rc = xfer_data(ctx, string->str, string->len);
1720 pth_cleanup_pop(1);
1721 return send_error(ctx, rc);
1724 static void list_command_cleanup1(void *arg)
1726 g_string_free((GString *)arg, TRUE);
1729 static void list_command_cleanup2(void *arg)
1731 struct element_list_s *elements = arg;
1733 if (elements) {
1734 gint total = g_slist_length(elements->list);
1735 gint i;
1737 for (i = 0; i < total; i++) {
1738 gchar *tmp = g_slist_nth_data(elements->list, i);
1739 g_free(tmp);
1742 g_slist_free(elements->list);
1744 if (elements->prefix)
1745 g_free(elements->prefix);
1747 g_free(elements);
1751 static int list_command(assuan_context_t ctx, char *line)
1753 struct client_s *client = assuan_get_pointer(ctx);
1754 gpg_error_t rc;
1755 struct element_list_s *elements = NULL;
1756 gchar *tmp;
1758 if (disable_list_and_dump == TRUE)
1759 return send_error(ctx, GPG_ERR_NOT_IMPLEMENTED);
1761 if (!*line) {
1762 GString *str;
1764 rc = list_accounts(client->doc, &str);
1766 if (rc)
1767 return send_error(ctx, rc);
1769 pth_cleanup_push(list_command_cleanup1, str);
1770 rc = xfer_data(ctx, str->str, str->len);
1771 pth_cleanup_pop(1);
1772 return send_error(ctx, rc);
1775 elements = g_malloc0(sizeof(struct element_list_s));
1777 if (!elements) {
1778 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1779 rc = gpg_err_code_from_errno(ENOMEM);
1780 goto fail;
1783 pth_cleanup_push(list_command_cleanup2, elements);
1784 rc = create_path_list(client->doc, elements, line);
1786 if (rc)
1787 goto fail;
1789 if (elements) {
1790 gint total = g_slist_length(elements->list);
1791 gint i;
1792 GString *str;
1794 if (!total) {
1795 rc = EPWMD_EMPTY_ELEMENT;
1796 goto fail;
1799 str = g_string_new(NULL);
1801 if (!str) {
1802 rc = gpg_err_code_from_errno(ENOMEM);
1803 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1804 goto fail;
1807 for (i = 0; i < total; i++) {
1808 tmp = g_slist_nth_data(elements->list, i);
1809 g_string_append_printf(str, "%s%s", tmp, i+1 == total ? "" : "\n");
1812 pth_cleanup_push(list_command_cleanup1, str);
1813 rc = xfer_data(ctx, str->str, str->len);
1814 pth_cleanup_pop(1);
1816 else
1817 rc = EPWMD_EMPTY_ELEMENT;
1819 fail:
1820 pth_cleanup_pop(1);
1821 return send_error(ctx, rc);
1824 static gpg_error_t add_attribute(xmlNodePtr node, const gchar *name,
1825 const gchar *value)
1827 xmlAttrPtr a;
1829 if ((a = xmlHasProp(node, (xmlChar *)name)) == NULL) {
1830 a = xmlNewProp(node, (xmlChar *)name, (xmlChar *)value);
1832 if (!a)
1833 return EPWMD_LIBXML_ERROR;
1835 else
1836 xmlNodeSetContent(a->children, (xmlChar *)value);
1838 return 0;
1842 * req[0] - element path
1844 static int attribute_list(assuan_context_t ctx, gchar **req)
1846 struct client_s *client = assuan_get_pointer(ctx);
1847 gchar **attrlist = NULL;
1848 gint i = 0;
1849 gchar **path = NULL;
1850 xmlAttrPtr a;
1851 xmlNodePtr n, an;
1852 gchar *line;
1853 gpg_error_t rc;
1855 if (!req || !req[0])
1856 return EPWMD_COMMAND_SYNTAX;
1858 if ((path = split_input_line(req[0], "\t", 0)) == NULL) {
1860 * The first argument may be only an account.
1862 if ((path = split_input_line(req[0], " ", 0)) == NULL)
1863 return EPWMD_COMMAND_SYNTAX;
1866 n = find_account(client->doc, &path, &rc, NULL, 0);
1868 if (!n) {
1869 g_strfreev(path);
1870 return rc;
1873 if (path[1]) {
1874 n = find_elements(client->doc, n->children, path+1, &rc,
1875 NULL, NULL, NULL, FALSE, 0, NULL);
1877 if (!n) {
1878 g_strfreev(path);
1879 return rc;
1883 g_strfreev(path);
1885 for (a = n->properties; a; a = a->next) {
1886 gchar **pa;
1888 if ((pa = g_realloc(attrlist, (i + 2) * sizeof(gchar *))) == NULL) {
1889 if (attrlist)
1890 g_strfreev(attrlist);
1892 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1893 return gpg_error_from_errno(ENOMEM);
1896 attrlist = pa;
1897 an = a->children;
1898 attrlist[i] = g_strdup_printf("%s %s", (gchar *)a->name, (gchar *)an->content);
1900 if (!attrlist[i]) {
1901 g_strfreev(attrlist);
1902 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1903 return gpg_error_from_errno(ENOMEM);
1906 attrlist[++i] = NULL;
1909 if (!attrlist)
1910 return EPWMD_EMPTY_ELEMENT;
1912 line = g_strjoinv("\n", attrlist);
1914 if (!line) {
1915 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1916 g_strfreev(attrlist);
1917 return gpg_error_from_errno(ENOMEM);
1920 pth_cleanup_push(g_free, line);
1921 pth_cleanup_push(req_cleanup, attrlist);
1922 rc = xfer_data(ctx, line, strlen(line));
1923 pth_cleanup_pop(1);
1924 pth_cleanup_pop(1);
1925 return rc;
1929 * req[0] - attribute
1930 * req[1] - element path
1932 static int attribute_delete(struct client_s *client, gchar **req)
1934 xmlAttrPtr a;
1935 xmlNodePtr n;
1936 gchar **path = NULL;
1937 gpg_error_t rc;
1939 if (!req || !req[0] || !req[1])
1940 return EPWMD_COMMAND_SYNTAX;
1942 if ((path = split_input_line(req[1], "\t", 0)) == NULL) {
1944 * The first argument may be only an account.
1946 if ((path = split_input_line(req[1], " ", 0)) == NULL)
1947 return EPWMD_COMMAND_SYNTAX;
1951 * Don't remove the "name" attribute for the account element. To remove an
1952 * account use DELETE <account>.
1954 if (!path[1] && xmlStrEqual((xmlChar *)req[0], (xmlChar *)"name")) {
1955 rc = EPWMD_ATTR_SYNTAX;
1956 goto fail;
1959 n = find_account(client->doc, &path, &rc, NULL, 0);
1961 if (!n)
1962 goto fail;
1964 if (path[1]) {
1965 n = find_elements(client->doc, n->children, path+1, &rc,
1966 NULL, NULL, NULL, FALSE, 0, NULL);
1968 if (!n)
1969 goto fail;
1972 g_strfreev(path);
1974 if ((a = xmlHasProp(n, (xmlChar *)req[0])) == NULL)
1975 return EPWMD_ATTR_NOT_FOUND;
1977 if (xmlRemoveProp(a) == -1)
1978 return EPWMD_LIBXML_ERROR;
1980 return 0;
1982 fail:
1983 g_strfreev(path);
1984 return rc;
1987 static xmlNodePtr create_element_path(struct client_s *client, gchar ***path,
1988 gpg_error_t *rc)
1990 gchar **src = *path;
1991 gchar **src_orig = g_strdupv(src);
1992 xmlNodePtr n = NULL;
1994 *rc = 0;
1996 if (!src_orig) {
1997 *rc = gpg_error_from_errno(ENOMEM);
1998 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1999 goto fail;
2002 again:
2003 n = find_account(client->doc, &src, rc, NULL, 0);
2005 if (!n) {
2006 if (*rc == EPWMD_ELEMENT_NOT_FOUND) {
2007 *rc = new_account(client->doc, src[0]);
2009 if (*rc)
2010 goto fail;
2012 goto again;
2014 else
2015 goto fail;
2018 if (src[1]) {
2019 if (!n->children)
2020 n = create_target_elements_cb(n, src+1, rc, NULL);
2021 else
2022 n = find_elements(client->doc, n->children, src+1, rc,
2023 NULL, NULL, create_target_elements_cb, FALSE, 0, NULL);
2025 if (!n)
2026 goto fail;
2029 * Reset the position of the element tree now that the elements
2030 * have been created.
2032 g_strfreev(src);
2033 src = src_orig;
2034 src_orig = NULL;
2035 n = find_account(client->doc, &src, rc, NULL, 0);
2037 if (!n)
2038 goto fail;
2040 n = find_elements(client->doc, n->children, src+1, rc,
2041 NULL, NULL, NULL, FALSE, 0, NULL);
2043 if (!n)
2044 goto fail;
2047 fail:
2048 if (src_orig)
2049 g_strfreev(src_orig);
2051 *path = src;
2052 return n;
2056 * Creates a "target" attribute. When other commands encounter an element with
2057 * this attribute, the element path is modified to the target value. If the
2058 * source element path doesn't exist when using 'ATTR SET target', it is
2059 * created, but the destination element path must exist.
2061 * req[0] - source element path
2062 * req[1] - destination element path
2064 static gpg_error_t target_attribute(struct client_s *client, gchar **req)
2066 gchar **src, **dst, *line = NULL;
2067 gpg_error_t rc;
2068 xmlNodePtr n;
2070 if (!req || !req[0] || !req[1])
2071 return EPWMD_COMMAND_SYNTAX;
2073 if ((src = split_input_line(req[0], "\t", 0)) == NULL) {
2075 * The first argument may be only an account.
2077 if ((src = split_input_line(req[0], " ", 0)) == NULL)
2078 return EPWMD_COMMAND_SYNTAX;
2081 if (valid_element_path(src, FALSE) == FALSE) {
2082 g_strfreev(src);
2083 return EPWMD_INVALID_ELEMENT;
2086 if ((dst = split_input_line(req[1], "\t", 0)) == NULL) {
2088 * The first argument may be only an account.
2090 if ((dst = split_input_line(req[1], " ", 0)) == NULL) {
2091 rc = EPWMD_COMMAND_SYNTAX;
2092 goto fail;
2096 n = find_account(client->doc, &dst, &rc, NULL, 0);
2099 * Make sure the destination element path exists.
2101 if (!n)
2102 goto fail;
2104 if (dst[1]) {
2105 n = find_elements(client->doc, n->children, dst+1, &rc,
2106 NULL, NULL, NULL, FALSE, 0, NULL);
2108 if (!n)
2109 goto fail;
2112 n = create_element_path(client, &src, &rc);
2114 if (rc)
2115 goto fail;
2117 line = g_strjoinv("\t", dst);
2119 if (!line) {
2120 rc = gpg_error_from_errno(ENOMEM);
2121 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2122 goto fail;
2125 rc = add_attribute(n, "target", line);
2127 fail:
2128 g_free(line);
2129 g_strfreev(src);
2130 g_strfreev(dst);
2131 return rc;
2135 * req[0] - account name
2136 * req[1] - new name
2138 static gpg_error_t name_attribute(struct client_s *client, gchar **req)
2140 gpg_error_t rc;
2141 gchar **tmp;
2142 xmlNodePtr n;
2144 tmp = g_strdupv(req);
2146 if (!tmp) {
2147 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2148 return gpg_error_from_errno(ENOMEM);
2151 n = find_account(client->doc, &tmp, &rc, NULL, 0);
2152 g_strfreev(tmp);
2154 if (!n)
2155 return rc;
2157 if (g_utf8_collate(req[0], req[1]) == 0)
2158 return 0;
2161 * Will not overwrite an existing account.
2163 tmp = g_strdupv(req+1);
2165 if (!tmp) {
2166 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2167 return gpg_error_from_errno(ENOMEM);
2170 n = find_account(client->doc, &tmp, &rc, NULL, 0);
2171 g_strfreev(tmp);
2173 if (rc && rc != EPWMD_ELEMENT_NOT_FOUND)
2174 return rc;
2176 if (n)
2177 return EPWMD_ACCOUNT_EXISTS;
2180 * Whitespace not allowed in account names.
2182 if (contains_whitespace(req[1]) == TRUE)
2183 return EPWMD_ATTR_SYNTAX;
2185 tmp = g_strdupv(req);
2187 if (!tmp) {
2188 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2189 return gpg_error_from_errno(ENOMEM);
2192 n = find_account(client->doc, &tmp, &rc, NULL, 0);
2193 g_strfreev(tmp);
2195 if (!n)
2196 return EPWMD_ELEMENT_NOT_FOUND;
2198 return add_attribute(n, "name", req[1]);
2202 * req[0] - attribute
2203 * req[1] - element path
2205 static int attribute_get(assuan_context_t ctx, gchar **req)
2207 struct client_s *client = assuan_get_pointer(ctx);
2208 xmlNodePtr n;
2209 xmlChar *a;
2210 gchar **path= NULL;
2211 gpg_error_t rc;
2213 if (!req || !req[0] || !req[1])
2214 return EPWMD_COMMAND_SYNTAX;
2216 if (strchr(req[1], '\t')) {
2217 if ((path = split_input_line(req[1], "\t", 0)) == NULL)
2218 return EPWMD_COMMAND_SYNTAX;
2220 else {
2221 if ((path = split_input_line(req[1], " ", 0)) == NULL)
2222 return EPWMD_COMMAND_SYNTAX;
2225 n = find_account(client->doc, &path, &rc, NULL, 0);
2227 if (!n)
2228 goto fail;
2230 if (path[1]) {
2231 n = find_elements(client->doc, n->children, path+1, &rc,
2232 NULL, NULL, NULL, FALSE, 0, NULL);
2234 if (!n)
2235 goto fail;
2238 g_strfreev(path);
2240 if ((a = xmlGetProp(n, (xmlChar *)req[0])) == NULL)
2241 return EPWMD_ATTR_NOT_FOUND;
2243 pth_cleanup_push(xmlFree, a);
2244 rc = xfer_data(ctx, (gchar *)a, xmlStrlen(a));
2245 pth_cleanup_pop(1);
2246 return rc;
2248 fail:
2249 g_strfreev(path);
2250 return rc;
2254 * req[0] - attribute
2255 * req[1] - element path
2256 * req[2] - value
2258 static int attribute_set(struct client_s *client, gchar **req)
2260 gchar **path = NULL;
2261 gpg_error_t rc;
2262 xmlNodePtr n;
2264 if (!req || !req[0] || !req[1] || !req[2])
2265 return EPWMD_COMMAND_SYNTAX;
2268 * Reserved attribute names.
2270 if (g_utf8_collate(req[0], "name") == 0) {
2272 * Only reserved for the account element. Not the rest of the
2273 * document.
2275 if (strchr(req[1], '\t') == NULL)
2276 return name_attribute(client, req + 1);
2278 else if (g_utf8_collate(req[0], "target") == 0)
2279 return target_attribute(client, req + 1);
2281 if ((path = split_input_line(req[1], "\t", 0)) == NULL) {
2283 * The first argument may be only an account.
2285 if ((path = split_input_line(req[1], " ", 0)) == NULL)
2286 return EPWMD_COMMAND_SYNTAX;
2289 n = find_account(client->doc, &path, &rc, NULL, 0);
2291 if (!n)
2292 goto fail;
2294 if (path[1]) {
2295 n = find_elements(client->doc, n->children, path+1, &rc,
2296 NULL, NULL, NULL, FALSE, 0, NULL);
2298 if (!n)
2299 goto fail;
2302 g_strfreev(path);
2303 return add_attribute(n, req[0], req[2]);
2305 fail:
2306 g_strfreev(path);
2307 return rc;
2311 * req[0] - command
2312 * req[1] - attribute name or element path if command is LIST
2313 * req[2] - element path
2314 * req[2] - element path or value
2316 static int attr_command(assuan_context_t ctx, char *line)
2318 struct client_s *client = assuan_get_pointer(ctx);
2319 gchar **req;
2320 gpg_error_t rc = 0;
2322 req = split_input_line(line, " ", 4);
2324 if (!req || !req[0] || !req[1]) {
2325 g_strfreev(req);
2326 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2329 pth_cleanup_push(req_cleanup, req);
2331 if (g_ascii_strcasecmp(req[0], "SET") == 0)
2332 rc = attribute_set(client, req+1);
2333 else if (g_ascii_strcasecmp(req[0], "GET") == 0)
2334 rc = attribute_get(ctx, req+1);
2335 else if (g_ascii_strcasecmp(req[0], "DELETE") == 0)
2336 rc = attribute_delete(client, req+1);
2337 else if (g_ascii_strcasecmp(req[0], "LIST") == 0)
2338 rc = attribute_list(ctx, req+1);
2339 else
2340 rc = EPWMD_COMMAND_SYNTAX;
2342 pth_cleanup_pop(1);
2343 return send_error(ctx, rc);
2346 static int iscached_command(assuan_context_t ctx, char *line)
2348 gchar **req = split_input_line(line, " ", 0);
2349 guchar md5file[16];
2350 gchar *path, *tmp;
2352 if (!req || !*req) {
2353 g_strfreev(req);
2354 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2357 if (!valid_filename(req[0])) {
2358 g_strfreev(req);
2359 return EPWMD_INVALID_FILENAME;
2362 tmp = get_key_file_string("global", "data_directory");
2364 if (!tmp) {
2365 g_strfreev(req);
2366 return gpg_error_from_errno(ENOMEM);
2369 path = expand_homedir(tmp);
2371 if (!path) {
2372 g_strfreev(req);
2373 g_free(tmp);
2374 return gpg_error_from_errno(ENOMEM);
2377 g_free(tmp);
2378 tmp = path;
2379 path = g_strdup_printf("%s/%s", tmp, req[0]);
2380 g_free(tmp);
2382 if (!path) {
2383 g_strfreev(req);
2384 return gpg_error_from_errno(ENOMEM);
2387 if (access(path, R_OK) == -1) {
2388 gpg_error_t rc = gpg_error_from_syserror();
2390 g_free(path);
2391 g_strfreev(req);
2392 return send_error(ctx, rc);
2395 g_free(path);
2396 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, req[0], strlen(req[0]));
2397 g_strfreev(req);
2398 CACHE_LOCK(ctx);
2400 if (cache_iscached(md5file) == FALSE) {
2401 CACHE_UNLOCK;
2402 return send_error(ctx, EPWMD_CACHE_NOT_FOUND);
2405 CACHE_UNLOCK;
2406 return send_error(ctx, 0);
2409 static int clearcache_command(assuan_context_t ctx, char *line)
2411 struct client_s *client = assuan_get_pointer(ctx);
2412 gchar **req = split_input_line(line, " ", 0);
2413 guchar md5file[16];
2415 CACHE_LOCK(ctx);
2417 if (!req || !*req) {
2418 g_strfreev(req);
2419 cache_clear(client->md5file, 2);
2420 CACHE_UNLOCK;
2421 return send_error(ctx, 0);
2424 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, req[0], strlen(req[0]));
2425 g_strfreev(req);
2427 if (cache_clear(md5file, 1) == FALSE) {
2428 CACHE_UNLOCK;
2429 return send_error(ctx, EPWMD_CACHE_NOT_FOUND);
2432 CACHE_UNLOCK;
2433 return send_error(ctx, 0);
2436 static int cachetimeout_command(assuan_context_t ctx, char *line)
2438 guchar md5file[16];
2439 glong timeout;
2440 gchar **req = split_input_line(line, " ", 0);
2441 gchar *p;
2443 if (!req || !*req || !req[1]) {
2444 g_strfreev(req);
2445 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2448 errno = 0;
2449 timeout = strtol(req[0], &p, 10);
2451 if (errno != 0 || *p != 0) {
2452 g_strfreev(req);
2453 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2456 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, req[1], strlen(req[1]));
2457 CACHE_LOCK(client->ctx);
2459 if (cache_set_timeout(md5file, timeout) == FALSE) {
2460 CACHE_UNLOCK;
2461 return send_error(ctx, EPWMD_CACHE_NOT_FOUND);
2464 CACHE_UNLOCK;
2465 return send_error(ctx, 0);
2468 static int dump_command(assuan_context_t ctx, char *line)
2470 xmlChar *xml;
2471 gssize len;
2472 struct client_s *client = assuan_get_pointer(ctx);
2473 gpg_error_t rc;
2475 if (disable_list_and_dump == TRUE)
2476 return send_error(ctx, GPG_ERR_NOT_IMPLEMENTED);
2478 xmlDocDumpFormatMemory(client->doc, &xml, &len, 1);
2480 if (!xml) {
2481 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2482 return send_syserror(ctx, ENOMEM);
2485 pth_cleanup_push(xmlFree, xml);
2486 rc = xfer_data(ctx, (gchar *)xml, len);
2487 pth_cleanup_pop(1);
2488 return send_error(ctx, rc);
2491 static int getconfig_command(assuan_context_t ctx, gchar *line)
2493 struct client_s *client = assuan_get_pointer(ctx);
2494 gpg_error_t rc = 0;
2495 gchar filename[255]={0}, param[747]={0};
2496 gchar *p, *tmp, *fp = client->filename, *paramp = line;
2498 if (strchr(line, ' ')) {
2499 sscanf(line, " %254[^ ] %746c", filename, param);
2500 paramp = param;
2501 fp = filename;
2504 if (fp && !valid_filename(fp))
2505 return send_error(ctx, EPWMD_INVALID_FILENAME);
2507 paramp = g_ascii_strdown(paramp, -1);
2509 if (!paramp) {
2510 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2511 return send_syserror(ctx, ENOMEM);
2514 if (fp && !g_ascii_strcasecmp(paramp, "iterations")) {
2515 if (!(client->opts & OPT_ITERATIONS) || fp != client->filename) {
2516 file_header_internal_t *fh = read_file_header(fp, FALSE, &rc);
2518 if (!fh && rc != GPG_ERR_ENOENT)
2519 return send_error(ctx, rc);
2521 if (!rc) {
2522 g_free(paramp);
2523 p = g_strdup_printf("%llu", fh->fh2.iter);
2524 close_file_header(fh);
2526 if (!p) {
2527 log_write("%s(%i): %s", __FILE__, __LINE__,
2528 strerror(ENOMEM));
2529 return send_syserror(ctx, ENOMEM);
2532 goto done;
2536 else if (!g_ascii_strcasecmp(paramp, "enable_pinentry")) {
2537 gboolean n;
2539 if (fp == client->filename && (client->opts & OPT_PINENTRY))
2540 n = client->pinentry->enable;
2541 else
2542 n = get_key_file_boolean(fp, "enable_pinentry");
2544 p = g_strdup_printf("%s", n ? "true" : "false");
2546 if (!p) {
2547 log_write("%s(%i): %s", __FILE__, __LINE__,
2548 strerror(ENOMEM));
2549 return send_syserror(ctx, ENOMEM);
2552 goto done;
2554 else if (!g_ascii_strcasecmp(paramp, "pinentry_timeout")) {
2555 if (fp == client->filename && (client->opts & OPT_PINENTRY_TO))
2556 p = g_strdup_printf("%i", client->pinentry->timeout);
2557 else
2558 p = g_strdup_printf("%i",
2559 get_key_file_integer(fp, "pinentry_timeout"));
2561 if (!p) {
2562 log_write("%s(%i): %s", __FILE__, __LINE__,
2563 strerror(ENOMEM));
2564 return send_syserror(ctx, ENOMEM);
2567 goto done;
2570 p = get_key_file_string(fp ? fp : "global", paramp);
2571 g_free(paramp);
2573 if (!p)
2574 return send_error(ctx, GPG_ERR_NO_VALUE);
2576 tmp = expand_homedir(p);
2577 g_free(p);
2579 if (!tmp) {
2580 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2581 return send_syserror(ctx, ENOMEM);
2584 p = tmp;
2585 done:
2586 pth_cleanup_push(g_free, p);
2587 rc = xfer_data(ctx, p, strlen(p));
2588 pth_cleanup_pop(1);
2589 return send_error(ctx, rc);
2592 struct xpath_s {
2593 xmlXPathContextPtr xp;
2594 xmlXPathObjectPtr result;
2595 xmlBufferPtr buf;
2596 gchar **req;
2599 static void xpath_command_cleanup(void *arg)
2601 struct xpath_s *xpath = arg;
2603 req_cleanup(xpath->req);
2605 if (xpath->buf)
2606 xmlBufferFree(xpath->buf);
2608 if (xpath->result)
2609 xmlXPathFreeObject(xpath->result);
2611 if (xpath->xp)
2612 xmlXPathFreeContext(xpath->xp);
2615 static int xpath_command(assuan_context_t ctx, gchar *line)
2617 struct client_s *client = assuan_get_pointer(ctx);
2618 gpg_error_t rc;
2619 struct xpath_s xpath;
2621 if (disable_list_and_dump == TRUE)
2622 return send_error(ctx, GPG_ERR_NOT_IMPLEMENTED);
2624 if (!line || !*line)
2625 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2627 memset(&xpath, 0, sizeof(struct xpath_s));
2629 if ((xpath.req = split_input_line(line, "\t", 2)) == NULL) {
2630 if (strv_printf(&xpath.req, "%s", line) == FALSE)
2631 return send_syserror(ctx, ENOMEM);
2634 xpath.xp = xmlXPathNewContext(client->doc);
2636 if (!xpath.xp) {
2637 xpath_command_cleanup(&xpath);
2638 return send_error(ctx, EPWMD_LIBXML_ERROR);
2641 xpath.result = xmlXPathEvalExpression((xmlChar *)xpath.req[0], xpath.xp);
2643 if (!xpath.result) {
2644 xpath_command_cleanup(&xpath);
2645 return send_error(ctx, EPWMD_LIBXML_ERROR);
2648 if (xmlXPathNodeSetIsEmpty(xpath.result->nodesetval)) {
2649 rc = EPWMD_EMPTY_ELEMENT;
2650 goto fail;
2653 rc = recurse_xpath_nodeset(client->doc, xpath.result->nodesetval,
2654 (xmlChar *)xpath.req[1], &xpath.buf);
2656 if (rc)
2657 goto fail;
2658 else if (!xpath.req[1] && !xmlBufferLength(xpath.buf)) {
2659 rc = EPWMD_EMPTY_ELEMENT;
2660 goto fail;
2662 else if (xpath.req[1])
2663 goto fail;
2665 pth_cleanup_push(xpath_command_cleanup, &xpath);
2666 rc = xfer_data(ctx, (gchar *)xmlBufferContent(xpath.buf),
2667 xmlBufferLength(xpath.buf));
2668 pth_cleanup_pop(0);
2670 fail:
2671 xpath_command_cleanup(&xpath);
2672 return send_error(ctx, rc);
2675 static int import_command_finalize(gpointer data, gint assuan_rc, guchar *line,
2676 gsize len)
2678 struct client_s *client = assuan_get_pointer((assuan_context_t)data);
2679 gpg_error_t rc = file_modified(client);
2680 gchar **req, **path = NULL, **path_orig = NULL, *content;
2681 xmlDocPtr doc;
2682 xmlNodePtr n, root, copy;
2684 if (assuan_rc || rc) {
2685 if (line)
2686 xfree(line);
2687 return assuan_rc ? assuan_rc : rc;
2690 req = split_input_line((gchar *)line, " ", 2);
2691 xfree(line);
2693 if (!req || !*req)
2694 return EPWMD_COMMAND_SYNTAX;
2696 if ((path = split_input_line(req[0], "\t", 0)) == NULL) {
2697 if ((path = split_input_line(req[0], " ", 0)) == NULL)
2698 return EPWMD_COMMAND_SYNTAX;
2701 content = req[1];
2703 if (!content || !*content) {
2704 rc = EPWMD_COMMAND_SYNTAX;
2705 goto fail;
2708 if (valid_xml_element((xmlChar *)*path) == FALSE) {
2709 rc = EPWMD_INVALID_ELEMENT;
2710 goto fail;
2713 if (valid_element_path(path+1, FALSE) == FALSE) {
2714 rc = EPWMD_INVALID_ELEMENT;
2715 goto fail;
2718 doc = xmlReadDoc((xmlChar *)content, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2720 if (!doc) {
2721 rc = EPWMD_LIBXML_ERROR;
2722 goto fail;
2725 root = xmlDocGetRootElement(doc);
2726 path_orig = g_strdupv(path);
2728 if (!path_orig) {
2729 xmlFreeDoc(doc);
2730 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2731 rc = gpg_error_from_errno(ENOMEM);
2732 goto fail;
2735 if (strv_printf(&path, "%s", (gchar *)root->name) == FALSE) {
2736 g_strfreev(path_orig);
2737 xmlFreeDoc(doc);
2738 rc = gpg_error_from_errno(ENOMEM);
2739 goto fail;
2742 n = find_account(client->doc, &path, &rc, NULL, 0);
2744 if (rc && rc != EPWMD_ELEMENT_NOT_FOUND) {
2745 g_strfreev(path_orig);
2746 xmlFreeDoc(doc);
2747 goto fail;
2749 else if (!rc) {
2750 n = find_elements(client->doc, n->children, path+1, &rc, NULL, NULL, NULL, FALSE, 0, NULL);
2752 if (rc && rc != EPWMD_ELEMENT_NOT_FOUND) {
2753 g_strfreev(path_orig);
2754 xmlFreeDoc(doc);
2755 goto fail;
2757 else if (!rc) {
2758 xmlNodePtr parent = n->parent;
2760 xmlUnlinkNode(n);
2761 xmlFreeNode(n);
2762 n = parent;
2766 g_strfreev(path);
2767 path = path_orig;
2769 if (rc == EPWMD_ELEMENT_NOT_FOUND) {
2770 n = create_element_path(client, &path, &rc);
2772 if (rc) {
2773 xmlFreeDoc(doc);
2774 goto fail;
2778 copy = xmlCopyNode(root, 1);
2779 n = xmlAddChild(n, copy);
2780 xmlFreeDoc(doc);
2782 if (!n)
2783 rc = EPWMD_LIBXML_ERROR;
2785 fail:
2786 g_strfreev(path);
2787 g_strfreev(req);
2788 client->inquire_status = INQUIRE_DONE;
2789 return rc;
2792 static int import_command(assuan_context_t ctx, gchar *line)
2794 gpg_error_t rc;
2795 struct client_s *client = assuan_get_pointer(ctx);
2797 rc = assuan_inquire_ext(ctx, "IMPORT", 0, import_command_finalize, ctx);
2799 if (rc)
2800 return send_error(ctx, rc);
2802 /* Don't return with assuan_process_done() here. This is an INQUIRE. */
2803 client->inquire_status = INQUIRE_BUSY;
2804 return 0;
2807 static int lock_command(assuan_context_t ctx, gchar *line)
2809 gpg_error_t rc;
2810 struct client_s *client = assuan_get_pointer(ctx);
2812 rc = lock_file_mutex(client);
2814 if (!rc)
2815 client->is_lock_cmd = TRUE;
2817 return send_error(ctx, rc);
2820 static int unlock_command(assuan_context_t ctx, gchar *line)
2822 struct client_s *client = assuan_get_pointer(ctx);
2824 unlock_file_mutex(client);
2825 return send_error(ctx, 0);
2828 static int getpid_command(assuan_context_t ctx, gchar *line)
2830 gpg_error_t rc;
2831 gchar buf[32];
2832 pid_t pid = getpid();
2834 print_fmt(buf, sizeof(buf), "%i", pid);
2835 rc = xfer_data(ctx, buf, strlen(buf));
2836 return send_error(ctx, rc);
2839 static int version_command(assuan_context_t ctx, gchar *line)
2841 gpg_error_t rc;
2842 gchar buf[32];
2844 print_fmt(buf, sizeof(buf), "0x%X", VERSION_HEX);
2845 rc = xfer_data(ctx, buf, strlen(buf));
2846 return send_error(ctx, rc);
2849 static void set_option_value(gchar **opt, const gchar *value)
2851 if (opt)
2852 g_free(*opt);
2854 *opt = NULL;
2856 if (value)
2857 *opt = g_strdup(value);
2860 static int set_unset_common(assuan_context_t ctx, const gchar *name,
2861 const gchar *value)
2863 struct client_s *client = assuan_get_pointer(ctx);
2865 if (g_ascii_strcasecmp(name, (gchar *)"iterations") == 0) {
2866 long n;
2867 gchar *p = NULL;
2869 if (!client->filename)
2870 return EPWMD_NO_FILE;
2872 if (!value) {
2873 MUTEX_LOCK(&rcfile_mutex);
2874 g_key_file_set_integer(keyfileh, client->filename, "iterations",
2875 get_key_file_integer("global", "iterations"));
2876 MUTEX_UNLOCK(&rcfile_mutex);
2877 goto done;
2880 errno = 0;
2881 n = strtol(value, &p, 10);
2883 if (errno || (p && *p) || n < 0)
2884 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_INV_VALUE);
2886 MUTEX_LOCK(&rcfile_mutex);
2887 g_key_file_set_integer(keyfileh,
2888 client->filename ? client->filename : "global", "iterations",
2889 (guint)n);
2890 MUTEX_UNLOCK(&rcfile_mutex);
2892 if (client->filename)
2893 client->opts |= OPT_ITERATIONS;
2895 else if (g_ascii_strcasecmp(name, (gchar *)"NAME") == 0) {
2896 pth_attr_t attr = pth_attr_of(pth_self());
2897 gchar buf[41];
2899 if (!value) {
2900 pth_attr_destroy(attr);
2901 goto done;
2904 print_fmt(buf, sizeof(buf), "%s", value);
2905 pth_attr_set(attr, PTH_ATTR_NAME, buf);
2906 pth_attr_destroy(attr);
2907 #ifdef WITH_PINENTRY
2908 if (client->pinentry->name)
2909 g_free(client->pinentry->name);
2911 client->pinentry->name = g_strdup(buf);
2913 if (!client->pinentry->name)
2914 return gpg_error_from_errno(ENOMEM);
2915 #endif
2917 #ifdef WITH_PINENTRY
2918 else if (g_ascii_strcasecmp(name, (gchar *)"lc_messages") == 0)
2919 set_option_value(&client->pinentry->lcmessages, value);
2920 else if (g_ascii_strcasecmp(name, (gchar *)"lc_ctype") == 0)
2921 set_option_value(&client->pinentry->lcctype, value);
2922 else if (g_ascii_strcasecmp(name, (gchar *)"ttyname") == 0)
2923 set_option_value(&client->pinentry->ttyname, value);
2924 else if (g_ascii_strcasecmp(name, (gchar *)"ttytype") == 0)
2925 set_option_value(&client->pinentry->ttytype, value);
2926 else if (g_ascii_strcasecmp(name, (gchar *)"display") == 0)
2927 set_option_value(&client->pinentry->display, value);
2928 else if (g_ascii_strcasecmp(name, (gchar *)"pinentry_path") == 0)
2929 set_option_value(&client->pinentry->path, value);
2930 else if (g_ascii_strcasecmp(name, (gchar *)"title") == 0)
2931 set_option_value(&client->pinentry->title, value);
2932 else if (g_ascii_strcasecmp(name, (gchar *)"prompt") == 0)
2933 set_option_value(&client->pinentry->prompt, value);
2934 else if (g_ascii_strcasecmp(name, (gchar *)"desc") == 0)
2935 set_option_value(&client->pinentry->desc, value);
2936 else if (g_ascii_strcasecmp(name, "pinentry_timeout") == 0) {
2937 gchar *p = NULL;
2938 gint n;
2940 if (!value) {
2941 client->pinentry->timeout =
2942 get_key_file_integer(client->filename, "pinentry_timeout");
2943 client->opts &= ~(OPT_PINENTRY_TO);
2944 goto done;
2947 n = strtol(value, &p, 10);
2949 if (*p || n < 0)
2950 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_INV_VALUE);
2952 client->pinentry->timeout = n;
2953 client->opts |= OPT_PINENTRY_TO;
2955 else if (g_ascii_strcasecmp(name, "enable_pinentry") == 0) {
2956 gchar *p = NULL;
2957 gint n;
2959 if (!value) {
2960 client->pinentry->enable = -1;
2961 client->opts &= ~(OPT_PINENTRY);
2962 goto done;
2965 n = strtol(value, &p, 10);
2967 if (*p || n < 0 || n > 1)
2968 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_INV_VALUE);
2970 client->pinentry->enable = n == 0 ? FALSE : TRUE;
2971 client->opts |= OPT_PINENTRY;
2973 #endif
2974 else
2975 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_UNKNOWN_OPTION);
2977 done:
2978 log_write("%s %s%s%s", value ? "SET" : "UNSET", name,
2979 value ? "=" : "", value ? value : "");
2980 return 0;
2983 static int unset_command(assuan_context_t ctx, gchar *line)
2985 return send_error(ctx, set_unset_common(ctx, line, NULL));
2988 static int set_command(assuan_context_t ctx, gchar *line)
2990 gchar name[64] = {0}, value[256] = {0};
2992 if (sscanf(line, " %63[_a-zA-Z] = %255c", name, value) != 2)
2993 return send_error(ctx, gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_SYNTAX));
2995 return send_error(ctx, set_unset_common(ctx, name, value));
2998 static void bye_notify(assuan_context_t ctx)
3000 struct client_s *cl = assuan_get_pointer(ctx);
3002 /* This will let assuan_process_next() return. */
3003 fcntl(cl->thd->fd, F_SETFL, O_NONBLOCK);
3006 static void reset_notify(assuan_context_t ctx)
3008 struct client_s *cl = assuan_get_pointer(ctx);
3010 if (cl)
3011 cleanup_client(cl);
3015 * This is called before every Assuan command.
3017 int command_startup(assuan_context_t ctx, const char *name)
3019 struct client_s *cl = assuan_get_pointer(ctx);
3020 gpg_error_t rc;
3022 if (!g_strcmp0(name, "ISCACHED") ||
3023 !g_strcmp0(name, "CLEARCACHE") ||
3024 !g_strcmp0(name, "CACHETIMEOUT") ||
3025 !g_strcmp0(name, "GETCONFIG") ||
3026 !g_strcmp0(name, "GETPID") ||
3027 !g_strcmp0(name, "VERSION") ||
3028 !g_strcmp0(name, "SET") ||
3029 !g_strcmp0(name, "BYE") ||
3030 !g_strcmp0(name, "NOP") ||
3031 !g_strcmp0(name, "CANCEL") ||
3032 !g_strcmp0(name, "RESET") ||
3033 !g_strcmp0(name, "END") ||
3034 !g_strcmp0(name, "HELP") ||
3035 !g_strcmp0(name, "OPTION") ||
3036 !g_strcmp0(name, "INPUT") ||
3037 !g_strcmp0(name, "OUTPUT") ||
3038 !g_strcmp0(name, "UNSET"))
3039 return 0;
3041 rc = file_modified(cl);
3043 if (rc) {
3044 if ((rc == EPWMD_NO_FILE || rc == EPWMD_FILE_MODIFIED) &&
3045 !g_strcmp0(name, "OPEN"))
3046 rc = 0;
3049 return rc;
3053 * This is called after every Assuan command.
3055 void command_finalize(assuan_context_t ctx, gint rc)
3057 struct client_s *client = assuan_get_pointer(ctx);
3059 if (!client->is_lock_cmd)
3060 unlock_file_mutex(client);
3063 gpg_error_t register_commands(assuan_context_t ctx)
3065 static struct {
3066 const gchar *name;
3067 gint (*handler)(assuan_context_t, gchar *line);
3068 } table[] = {
3069 { "OPEN", open_command },
3070 { "SAVE", save_command },
3071 { "LIST", list_command },
3072 { "REALPATH", realpath_command },
3073 { "STORE", store_command },
3074 { "DELETE", delete_command },
3075 { "GET", get_command },
3076 { "ATTR", attr_command },
3077 { "ISCACHED", iscached_command },
3078 { "CLEARCACHE", clearcache_command },
3079 { "CACHETIMEOUT", cachetimeout_command },
3080 { "GETCONFIG", getconfig_command },
3081 { "DUMP", dump_command },
3082 { "XPATH", xpath_command },
3083 { "IMPORT", import_command },
3084 { "LOCK", lock_command },
3085 { "UNLOCK", unlock_command },
3086 { "GETPID", getpid_command },
3087 { "VERSION", version_command },
3088 { "SET", set_command },
3089 { "UNSET", unset_command },
3090 { "INPUT", NULL },
3091 { "OUTPUT", NULL },
3092 { NULL, NULL }
3094 gint i, rc;
3096 for (i=0; table[i].name; i++) {
3097 rc = assuan_register_command (ctx, table[i].name, table[i].handler);
3099 if (rc)
3100 return rc;
3103 rc = assuan_register_bye_notify(ctx, bye_notify);
3105 if (rc)
3106 return rc;
3108 rc = assuan_register_reset_notify(ctx, reset_notify);
3110 if (rc)
3111 return rc;
3113 rc = assuan_register_pre_cmd_notify(ctx, command_startup);
3115 if (rc)
3116 return rc;
3118 return assuan_register_post_cmd_notify(ctx, command_finalize);
3121 gpg_error_t try_xml_decrypt(assuan_context_t ctx, guchar *key,
3122 struct client_crypto_s *crypto, gpointer *dst, goffset *dst_len)
3124 goffset insize, len;
3125 struct client_s *client = ctx ? assuan_get_pointer(ctx) : NULL;
3126 guint64 iter = 0, n_iter = 0, iter_progress = 0;
3127 gint zrc = 0;
3128 gulong outsize = 0;
3129 gpg_error_t rc;
3130 gsize fh_size = crypto->fh->v1 ? sizeof(crypto->fh->fh1) : sizeof(crypto->fh->fh2);
3131 guint64 fh_iter = crypto->fh->v1 ? crypto->fh->fh1.iter : crypto->fh->fh2.iter;
3133 lseek(crypto->fh->fd, fh_size, SEEK_SET);
3134 insize = crypto->fh->st.st_size - fh_size;
3135 crypto->iv = gcry_malloc(gcryblocksize);
3137 if (!crypto->iv) {
3138 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
3139 return gpg_error_from_errno(ENOMEM);
3142 /* No encryption iterations. This is a plain (gzipped) file. */
3143 if ((crypto->fh->v1 && fh_iter < 0) || (!crypto->fh->v1 && fh_iter <= 0)) {
3145 * cache_file_count() needs both .used == TRUE and a valid key in
3146 * order for it to count as a used cache entry. Fixes CACHE status
3147 * messages.
3149 memset(key, '!', gcrykeysize);
3152 if (crypto->fh->v1)
3153 memcpy(crypto->iv, crypto->fh->fh1.iv, gcryblocksize);
3154 else
3155 memcpy(crypto->iv, crypto->fh->fh2.iv, gcryblocksize);
3157 crypto->inbuf = gcry_malloc(insize);
3159 if (!crypto->inbuf) {
3160 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
3161 return gpg_error_from_errno(ENOMEM);
3164 crypto->insize = insize;
3165 len = pth_read(crypto->fh->fd, crypto->inbuf, crypto->insize);
3167 if (len != crypto->insize)
3168 return GPG_ERR_INV_LENGTH;
3170 if ((crypto->fh->v1 && fh_iter < 0) || (!crypto->fh->v1 && fh_iter <= 0))
3171 goto decompress;
3173 if ((rc = gcry_cipher_setiv(crypto->gh, crypto->iv, gcryblocksize))) {
3174 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3175 return rc;
3178 if ((rc = gcry_cipher_setkey(crypto->gh, key, gcrykeysize))) {
3179 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3180 return rc;
3183 iter_progress = (guint64)get_key_file_integer(client && client->filename ?
3184 client->filename : "global", "iteration_progress");
3186 if (iter_progress > 0 && fh_iter >= iter_progress) {
3187 rc = send_status(ctx, STATUS_DECRYPT, "0 %llu", fh_iter);
3189 if (rc)
3190 return rc;
3193 rc = iterate_crypto_once(client, crypto, STATUS_DECRYPT);
3195 if (rc)
3196 return rc;
3198 crypto->tkey = gcry_malloc(gcrykeysize);
3200 if (!crypto->tkey) {
3201 log_write("%s(%i): %s", __FUNCTION__, __LINE__, strerror(ENOMEM));
3202 return gpg_error_from_errno(ENOMEM);
3205 memcpy(crypto->tkey, key, gcrykeysize);
3206 guchar *tkey = crypto->tkey;
3207 tkey[0] ^= 1;
3209 if ((rc = gcry_cipher_setkey(crypto->gh, crypto->tkey, gcrykeysize))) {
3210 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3211 return rc;
3214 while (iter < (crypto->fh->v1 ? fh_iter : fh_iter-1)) {
3215 if (iter_progress > 0 && iter >= iter_progress) {
3216 if (!(iter % iter_progress)) {
3217 rc = send_status(ctx, STATUS_DECRYPT, "%llu %llu",
3218 ++n_iter * iter_progress, fh_iter);
3220 if (rc)
3221 return rc;
3225 if ((rc = gcry_cipher_setiv(crypto->gh, crypto->iv, gcryblocksize))) {
3226 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3227 return rc;
3230 rc = iterate_crypto_once(client, crypto, STATUS_DECRYPT);
3232 if (rc) {
3233 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3234 return rc;
3237 iter++;
3240 if (iter_progress && fh_iter >= iter_progress) {
3241 rc = send_status(ctx, STATUS_DECRYPT, "%llu %llu", fh_iter, fh_iter);
3243 if (rc)
3244 return rc;
3247 decompress:
3248 if (do_decompress(ctx, crypto->inbuf, crypto->insize,
3249 (gpointer *)&crypto->outbuf, &outsize, &zrc) == FALSE) {
3250 if (zrc == Z_MEM_ERROR)
3251 return gpg_error_from_errno(ENOMEM);
3252 else
3253 return EPWMD_BADKEY; // Not a valid gzip header. Must be a bad key.
3256 if (g_strncasecmp(crypto->outbuf, "<?xml version=", 14) != 0) {
3257 gcry_free(crypto->outbuf);
3258 crypto->outbuf = NULL;
3259 return EPWMD_BADKEY;
3262 if (ctx) {
3263 client->xml = crypto->outbuf;
3264 client->len = outsize;
3265 crypto->outbuf = NULL;
3267 else if (dst) {
3268 *dst = crypto->outbuf;
3269 *dst_len = outsize;
3270 crypto->outbuf = NULL;
3273 /* The calling function should free the crypto struct. */
3274 return 0;