All commands that send data use do_assuan_command() or xfer_data(). This
[pwmd.git] / src / commands.c
blob428de24f783869504b6b8ca445aae5970d84e2d9
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 #include "mem.h"
37 #include "xml.h"
38 #include "common.h"
40 #ifdef WITH_PINENTRY
41 #include "pinentry.h"
42 #endif
44 #include "pwmd_error.h"
45 #include "cache.h"
46 #include "misc.h"
47 #include "commands.h"
48 #include "lock.h"
50 struct gz_s {
51 z_stream z;
52 gpointer out;
53 gboolean done;
54 status_msg_t which;
57 static void *z_alloc(void *data, unsigned items, unsigned size)
59 return gcry_calloc(items, size);
62 static void z_free(void *data, void *p)
64 gcry_free(p);
67 static gpg_error_t file_modified(struct client_s *client)
69 struct stat st;
70 gpg_error_t rc;
72 if (client->state != STATE_OPEN)
73 return EPWMD_NO_FILE;
75 rc = lock_file_mutex(client);
77 if (rc)
78 return rc;
80 if (lstat(client->filename, &st) == 0 && client->mtime) {
81 if (client->mtime != st.st_mtime)
82 return EPWMD_FILE_MODIFIED;
85 pth_cancel_point();
86 return 0;
89 static gpg_error_t parse_xml(assuan_context_t ctx)
91 struct client_s *client = assuan_get_pointer(ctx);
93 client->doc = xmlReadMemory(client->xml, client->len, NULL, "UTF-8", XML_PARSE_NOBLANKS);
95 if (!client->doc)
96 return EPWMD_LIBXML_ERROR;
98 return 0;
101 void unlock_file_mutex(struct client_s *client)
103 pth_mutex_t *m;
105 #ifdef WITH_PINENTRY
106 if (client->has_lock == FALSE || client->pinentry->status != PINENTRY_NONE)
107 #else
108 if (client->has_lock == FALSE)
109 #endif
110 return;
112 CACHE_LOCK(client->ctx);
114 if (cache_get_mutex(client->md5file, &m) == FALSE) {
115 CACHE_UNLOCK;
116 return;
119 CACHE_UNLOCK;
120 MUTEX_UNLOCK(m);
121 client->has_lock = client->is_lock_cmd = FALSE;
124 gpg_error_t lock_file_mutex(struct client_s *client)
126 pth_mutex_t *m;
127 gpg_error_t rc = 0;
129 if (client->has_lock == TRUE)
130 return 0;
132 CACHE_LOCK(client->ctx);
134 if (cache_get_mutex(client->md5file, &m) == FALSE) {
135 CACHE_UNLOCK;
136 return 0;
139 CACHE_UNLOCK;
140 MUTEX_TRYLOCK(client->ctx, m, rc);
142 if (!rc)
143 client->has_lock = TRUE;
145 return rc;
148 void free_client(struct client_s *client)
150 if (client->doc)
151 xmlFreeDoc(client->doc);
153 if (client->xml)
154 gcry_free(client->xml);
156 if (client->filename)
157 g_free(client->filename);
159 if (client->crypto)
160 cleanup_crypto(&client->crypto);
162 if (client->xml_error)
163 xmlResetError(client->xml_error);
166 void cleanup_client(struct client_s *client)
168 assuan_context_t ctx = client->ctx;
169 struct client_thread_s *thd = client->thd;
170 gboolean has_lock = client->has_lock;
171 #ifdef WITH_PINENTRY
172 struct pinentry_s *pin = client->pinentry;
173 #endif
175 unlock_file_mutex(client);
176 CACHE_LOCK(client->ctx);
177 cache_decr_refcount(client->md5file);
180 * This may be a new file so don't use a cache slot. save_command() will
181 * set this to FALSE on success.
183 if (client->new == TRUE)
184 cache_clear(client->md5file, 1);
186 CACHE_UNLOCK;
187 free_client(client);
188 memset(client, 0, sizeof(struct client_s));
189 client->state = STATE_CONNECTED;
190 client->ctx = ctx;
191 client->thd = thd;
192 client->freed = TRUE;
193 #ifdef WITH_PINENTRY
194 client->pinentry = pin;
195 #endif
196 client->has_lock = has_lock;
199 static void gz_cleanup(void *arg)
201 struct gz_s **gz = (struct gz_s **)arg;
203 if (!gz)
204 return;
206 if (!(*gz)->done && (*gz)->out)
207 gcry_free((*gz)->out);
210 if ((*gz)->which == STATUS_COMPRESS) {
211 if ((*gz)->z.zalloc)
212 deflateEnd(&(*gz)->z);
214 else {
215 if ((*gz)->z.zalloc)
216 inflateEnd(&(*gz)->z);
219 g_free(*gz);
220 *gz = NULL;
223 gboolean do_decompress(assuan_context_t ctx, gpointer in, gulong insize,
224 gpointer *out, gulong *outsize, gint *rc)
226 struct gz_s *gz;
227 gz_header h;
228 gchar buf[17];
230 gz = g_malloc0(sizeof(struct gz_s));
232 if (!gz) {
233 *rc = gpg_error_from_errno(ENOMEM);
234 return FALSE;
237 gz->which = STATUS_DECOMPRESS;
238 gz->z.zalloc = z_alloc;
239 gz->z.zfree = z_free;
240 gz->z.next_in = in;
241 gz->z.avail_in = (uInt)insize;
242 gz->z.avail_out = zlib_bufsize;
243 gz->z.next_out = gz->out = gcry_malloc(zlib_bufsize);
245 if (!gz->out) {
246 log_write("%s(%i): %s", __FUNCTION__, __LINE__, strerror(ENOMEM));
247 *rc = Z_MEM_ERROR;
248 gz_cleanup(&gz);
249 return FALSE;
252 *rc = inflateInit2(&gz->z, 47);
254 if (*rc != Z_OK) {
255 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
256 gz_cleanup(&gz);
257 return FALSE;
260 memset(&h, 0, sizeof(gz_header));
261 h.comment = (guchar *)buf;
262 h.comm_max = sizeof(buf);
263 *rc = inflateGetHeader(&gz->z, &h);
265 if (*rc != Z_OK) {
266 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
267 gz_cleanup(&gz);
268 return FALSE;
271 *rc = inflate(&gz->z, Z_BLOCK);
273 if (*rc != Z_OK) {
274 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
275 gz_cleanup(&gz);
276 return FALSE;
279 if (h.comment)
280 insize = (gulong)strtol((gchar *)h.comment, NULL, 10);
282 do {
283 gpointer p;
285 *rc = inflate(&gz->z, Z_FINISH);
287 switch (*rc) {
288 case Z_OK:
289 break;
290 case Z_BUF_ERROR:
291 if (!gz->z.avail_out) {
292 p = gcry_realloc(gz->out, gz->z.total_out + zlib_bufsize);
294 if (!p) {
295 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
296 *rc = Z_MEM_ERROR;
297 goto fail;
300 gz->out = p;
301 gz->z.next_out = gz->out + gz->z.total_out;
302 gz->z.avail_out = zlib_bufsize;
303 *rc = send_status(ctx, STATUS_DECOMPRESS, "%li %li",
304 gz->z.total_out, insize);
306 if (*rc)
307 goto fail;
309 break;
310 case Z_STREAM_END:
311 break;
312 default:
313 goto fail;
314 break;
316 } while (*rc != Z_STREAM_END);
318 pth_cancel_point();
319 *rc = send_status(ctx, STATUS_DECOMPRESS, "%li %li", gz->z.total_out,
320 insize);
321 pth_cancel_point();
323 if (*rc)
324 goto fail;
326 *out = gz->out;
327 *outsize = gz->z.total_out;
328 gz->done = TRUE;
329 gz_cleanup(&gz);
330 *rc = 0;
331 return TRUE;
333 fail:
334 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
335 gz_cleanup(&gz);
336 return FALSE;
339 file_header_internal_t *read_file_header(const gchar *filename, gboolean v1,
340 gpg_error_t *rc)
342 gint fd;
343 gsize len;
344 file_header_internal_t *fh = g_malloc0(sizeof(file_header_internal_t));
345 gsize fh_size;
347 *rc = 0;
349 if (!fh) {
350 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
351 *rc = gpg_error_from_errno(ENOMEM);
352 return NULL;
355 fh_size = v1 ? sizeof(fh->fh1) : sizeof(fh->fh2);
357 if (lstat(filename, &fh->st) == -1) {
358 *rc = gpg_error_from_syserror();
359 g_free(fh);
360 return NULL;
363 if (!S_ISREG(fh->st.st_mode)) {
364 *rc = GPG_ERR_ENOANO;
365 g_free(fh);
366 return NULL;
369 fd = open(filename, O_RDONLY);
371 if (fd == -1) {
372 *rc = gpg_error_from_errno(errno);
373 g_free(fh);
374 return NULL;
377 if (v1)
378 len = pth_read(fd, &fh->fh1, fh_size);
379 else
380 len = pth_read(fd, &fh->fh2, fh_size);
382 if (len != fh_size) {
383 gint n = errno;
384 close(fd);
385 g_free(fh);
386 *rc = gpg_error_from_errno(n);
387 return NULL;
390 fh->v1 = v1;
391 fh->fd = fd;
392 return fh;
395 static gpg_error_t open_command_finalize(assuan_context_t ctx, guchar *key,
396 gboolean cached)
398 struct client_s *client = assuan_get_pointer(ctx);
399 gpg_error_t rc;
400 gint timeout;
402 /* New file. */
403 if (!client->crypto->fh) {
404 if (key[0])
405 goto update_cache;
407 goto done;
410 rc = try_xml_decrypt(ctx, key, client->crypto, NULL, NULL);
412 if (rc) {
413 cleanup_client(client);
414 return send_error(ctx, rc);
417 update_cache:
418 CACHE_LOCK(client->ctx);
420 if (cached == FALSE) {
421 if (cache_update_key(client->md5file, key) == FALSE) {
422 cleanup_client(client);
423 CACHE_UNLOCK;
424 return send_syserror(ctx, ENOMEM);
427 timeout = get_key_file_integer(client->filename, "cache_timeout");
428 cache_reset_timeout(client->md5file, timeout);
430 else
431 cache_set_timeout(client->md5file, -2);
433 CACHE_UNLOCK;
435 done:
436 rc = parse_xml(ctx);
438 if (client->xml) {
439 gcry_free(client->xml);
440 client->xml = NULL;
443 if (!rc) {
444 if (client->new == FALSE)
445 send_status_all(STATUS_CACHE);
447 client->state = STATE_OPEN;
450 if (!rc && client->new == FALSE &&
451 client->crypto->fh->fh2.iter != (guint64)get_key_file_integer(client->filename, "iterations")) {
452 MUTEX_LOCK(&rcfile_mutex);
453 g_key_file_set_integer(keyfileh, client->filename, "iterations",
454 client->crypto->fh->fh2.iter);
455 MUTEX_UNLOCK(&rcfile_mutex);
456 send_status_all(STATUS_CONFIG);
459 if (!rc)
460 log_write("OPEN '%s'", client->filename);
462 cleanup_crypto(&client->crypto);
463 return send_error(ctx, rc);
466 static void req_cleanup(void *arg)
468 if (!arg)
469 return;
471 g_strfreev((gchar **)arg);
474 static int open_command(assuan_context_t ctx, char *line)
476 gboolean cached = FALSE;
477 gpg_error_t rc;
478 struct client_s *client = assuan_get_pointer(ctx);
479 gchar **req;
480 gchar *filename = NULL;
482 if ((req = split_input_line(line, " ", 2)) != NULL)
483 filename = req[0];
485 if (!filename || !*filename) {
486 g_strfreev(req);
487 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
490 if (valid_filename(filename) == FALSE) {
491 g_strfreev(req);
492 return send_error(ctx, EPWMD_INVALID_FILENAME);
495 if (client->state == STATE_OPEN)
496 cleanup_client(client);
498 gcry_md_hash_buffer(GCRY_MD_MD5, client->md5file, filename, strlen(filename));
499 CACHE_LOCK(client->ctx);
501 if (cache_has_file(client->md5file) == FALSE) {
502 if (cache_add_file(client->md5file, NULL) == FALSE) {
503 g_strfreev(req);
504 CACHE_UNLOCK;
505 return send_syserror(ctx, ENOMEM);
509 cache_incr_refcount(client->md5file);
510 CACHE_UNLOCK;
511 rc = lock_file_mutex(client);
513 if (rc) {
514 g_strfreev(req);
515 return send_error(ctx, rc);
518 client->freed = FALSE;
519 client->crypto = init_client_crypto();
521 if (!client->crypto) {
522 g_strfreev(req);
523 cleanup_client(client);
524 return send_syserror(ctx, ENOMEM);
527 client->crypto->key = gcry_malloc(gcrykeysize);
529 if (!client->crypto->key) {
530 g_strfreev(req);
531 log_write("%s(%i): %s", __FUNCTION__, __LINE__,
532 gpg_error_from_errno(ENOMEM));
533 cleanup_client(client);
534 return send_syserror(ctx, ENOMEM);
537 memset(client->crypto->key, 0, gcrykeysize);
538 client->crypto->fh = read_file_header(filename, FALSE, &rc);
539 pth_cancel_point();
541 if (!client->crypto->fh) {
542 if (gpg_err_code_to_errno(rc) != ENOENT) {
543 log_write("%s: %s", filename, pwmd_strerror(rc));
544 g_strfreev(req);
545 cleanup_client(client);
546 return send_error(ctx, rc);
550 * New files don't need a key.
552 if ((client->xml = new_document()) == NULL) {
553 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
554 g_strfreev(req);
555 cleanup_client(client);
556 return send_syserror(ctx, ENOMEM);
559 client->len = xmlStrlen(client->xml);
560 client->new = TRUE;
561 client->filename = g_strdup(filename);
563 if (!client->filename) {
564 g_strfreev(req);
565 cleanup_client(client);
566 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
567 return send_syserror(ctx, ENOMEM);
570 if (req[1] && *req[1])
571 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, req[1],
572 strlen(req[1]));
574 g_strfreev(req);
575 #ifdef WITH_PINENTRY
576 client->pinentry->filename = g_strdup(client->filename);
578 if (!client->pinentry->filename) {
579 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
580 cleanup_client(client);
581 return send_syserror(ctx, ENOMEM);
583 #endif
584 return open_command_finalize(ctx, client->crypto->key, cached);
586 else
587 client->mtime = client->crypto->fh->st.st_mtime;
589 client->filename = g_strdup(filename);
591 if (!client->filename) {
592 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
593 g_strfreev(req);
594 cleanup_client(client);
595 return send_syserror(ctx, ENOMEM);
598 #ifdef WITH_PINENTRY
599 client->pinentry->filename = g_strdup(client->filename);
601 if (!client->pinentry->filename) {
602 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
603 g_strfreev(req);
604 cleanup_client(client);
605 return send_syserror(ctx, ENOMEM);
607 #endif
609 if (client->crypto->fh->fh2.iter <= 0)
610 goto done;
612 CACHE_LOCK(client->ctx);
613 cached = cache_get_key(client->md5file, client->crypto->key);
614 CACHE_UNLOCK;
616 if (cached == FALSE) {
617 gchar *tmp = get_key_file_string(filename, "key_file");
619 if (tmp) {
620 g_free(tmp);
621 cleanup_client(client);
622 return send_error(ctx, GPG_ERR_WRONG_KEY_USAGE);
626 * No key specified and no matching filename found in the cache. Use
627 * pinentry to retrieve the key. Cannot return assuan_process_done()
628 * here otherwise the command will be interrupted. The event loop in
629 * client_thread() will poll the file descriptor waiting for it to
630 * become ready to read a pinentry_key_s which will contain the
631 * entered key or an error code. It will then call
632 * open_command_finalize() to to finish the command.
634 if (!req[1] || !*req[1]) {
635 #ifdef WITH_PINENTRY
636 gboolean b = get_key_file_boolean(filename, "enable_pinentry");
638 /* From set_pinentry_defaults(). */
639 if (client->pinentry->enable == FALSE ||
640 (client->pinentry->enable == -1 && b == FALSE)) {
641 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, "", 1);
642 goto done;
645 g_strfreev(req);
646 rc = lock_pin_mutex(client);
648 if (rc) {
649 unlock_pin_mutex(client->pinentry);
650 cleanup_client(client);
651 return send_error(ctx, rc);
654 client->pinentry->which = PINENTRY_OPEN;
655 rc = pinentry_fork(ctx);
657 if (rc) {
658 unlock_pin_mutex(client->pinentry);
659 cleanup_client(client);
660 return send_error(ctx, rc);
663 // Called from pinentry iterate.
664 client->pinentry->cb = open_command_finalize;
665 client->pinentry->status = PINENTRY_INIT;
666 return 0;
667 #else
668 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, "", 1);
669 goto done;
670 #endif
673 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, req[1],
674 strlen(req[1]));
677 done:
678 req_cleanup(req);
679 return open_command_finalize(ctx, client->crypto->key, cached);
682 gboolean do_compress(assuan_context_t ctx, gint level, gpointer data,
683 gulong size, gpointer *out, gulong *outsize, gint *rc)
685 struct gz_s *gz;
686 gz_header h;
687 gchar buf[17];
688 gint cmd = Z_NO_FLUSH;
690 gz = g_malloc0(sizeof(struct gz_s));
692 if (!gz) {
693 *rc = gpg_error_from_errno(ENOMEM);
694 return FALSE;
697 gz->which = STATUS_COMPRESS;
698 gz->z.zalloc = z_alloc;
699 gz->z.zfree = z_free;
700 gz->z.next_in = data;
701 gz->z.avail_in = size < zlib_bufsize ? (uInt)size : (uInt)zlib_bufsize;
702 gz->z.avail_out = (uInt)zlib_bufsize;
703 gz->z.next_out = gz->out = gcry_malloc(zlib_bufsize);
705 if (!gz->out) {
706 log_write("%s(%i): %s", __FUNCTION__, __LINE__, strerror(ENOMEM));
707 *rc = Z_MEM_ERROR;
708 gz_cleanup(&gz);
709 return FALSE;
712 *rc = deflateInit2(&gz->z, level, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY);
714 if (*rc != Z_OK) {
715 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
716 gz_cleanup(&gz);
717 return FALSE;
720 /* Rather than store the size of the uncompressed data in the file header,
721 * store it in the comment field of the gzip header. Don't give anyone too
722 * much information. Not sure why really, but it seems the right way. :)
724 memset(&h, 0, sizeof(gz_header));
725 g_snprintf(buf, sizeof(buf), "%li", size);
726 h.comment = (guchar *)buf;
727 *rc = deflateSetHeader(&gz->z, &h);
729 if (*rc != Z_OK) {
730 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
731 gz_cleanup(&gz);
732 return FALSE;
735 do {
736 gpointer p;
738 *rc = deflate(&gz->z, cmd);
740 switch (*rc) {
741 case Z_OK:
742 break;
743 case Z_BUF_ERROR:
744 if (!gz->z.avail_out) {
745 p = gcry_realloc(gz->out, gz->z.total_out + zlib_bufsize);
747 if (!p) {
748 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
749 *rc = Z_MEM_ERROR;
750 goto fail;
753 gz->out = p;
754 gz->z.next_out = gz->out + gz->z.total_out;
755 gz->z.avail_out = zlib_bufsize;
758 if (!gz->z.avail_in && gz->z.total_in < size) {
759 if (gz->z.total_in + zlib_bufsize > size)
760 gz->z.avail_in = size - gz->z.total_in;
761 else
762 gz->z.avail_in = zlib_bufsize;
764 *rc = send_status(ctx, STATUS_COMPRESS, "%li %li",
765 gz->z.total_in, size);
767 if (*rc)
768 goto fail;
771 if (gz->z.total_in >= size)
772 cmd = Z_FINISH;
774 break;
775 case Z_STREAM_END:
776 break;
777 default:
778 goto fail;
780 } while (*rc != Z_STREAM_END);
782 pth_cancel_point();
783 *rc = send_status(ctx, STATUS_COMPRESS, "%li %li", gz->z.total_in, size);
784 pth_cancel_point();
786 if (*rc)
787 goto fail;
789 *out = gz->out;
790 *outsize = gz->z.total_out;
791 *rc = 0;
792 gz->done = TRUE;
793 gz_cleanup(&gz);
794 return TRUE;
796 fail:
797 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
798 gz_cleanup(&gz);
799 return FALSE;
802 #define CRYPTO_BLOCKSIZE (gcryblocksize * 1024)
804 static gpg_error_t iterate_crypto_once(struct client_s *client,
805 struct client_crypto_s *crypto, status_msg_t which)
807 gpg_error_t rc = 0;
808 goffset len = CRYPTO_BLOCKSIZE;
809 gpointer p = gcry_malloc(len);
810 goffset total = 0;
811 gpointer inbuf;
813 if (!p)
814 return gpg_err_code_from_errno(ENOMEM);
816 if (crypto->insize < CRYPTO_BLOCKSIZE)
817 len = crypto->insize;
819 for (;;) {
820 inbuf = crypto->inbuf + total;
821 guchar *tmp;
823 if (len + total > crypto->insize)
824 len = gcryblocksize;
826 if (which == STATUS_ENCRYPT)
827 rc = gcry_cipher_encrypt(crypto->gh, p, len, inbuf, len);
828 else
829 rc = gcry_cipher_decrypt(crypto->gh, p, len, inbuf, len);
831 if (rc)
832 goto done;
834 tmp = crypto->inbuf+total;
835 memmove(tmp, p, len);
836 total += len;
838 if (total >= crypto->insize)
839 break;
841 pth_cancel_point();
844 done:
845 gcry_free(p);
846 return rc;
849 /* The crypto struct must be setup for iterations and .key. */
850 gpg_error_t do_xml_encrypt(struct client_s *client,
851 struct client_crypto_s *crypto, const gchar *filename)
853 goffset len = crypto->insize;
854 gpointer inbuf;
855 gchar *p;
856 gpg_error_t rc;
857 guint64 iter_progress = 0, n_iter = 0, xiter = 0;
858 gchar tmp[FILENAME_MAX];
859 struct stat st;
860 mode_t mode = 0;
862 if (!crypto->fh->fh2.iter) {
864 * cache_file_count() needs both .used == TRUE and a valid key in
865 * order for it to count as a used cache entry. Fixes CACHE status
866 * messages.
868 memset(crypto->key, '!', gcrykeysize);
869 goto write_file;
873 * Resize the existing xml buffer to the block size required by gcrypt
874 * rather than duplicating it and wasting memory.
876 if (crypto->insize / gcryblocksize) {
877 len = (crypto->insize / gcryblocksize) * gcryblocksize;
879 if (crypto->insize % gcryblocksize)
880 len += gcryblocksize;
883 inbuf = gcry_realloc(crypto->inbuf, len);
885 if (!inbuf) {
886 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
887 return gpg_error_from_errno(ENOMEM);
890 crypto->inbuf = inbuf;
891 crypto->insize = len;
892 gcry_create_nonce(crypto->fh->fh2.iv, sizeof(crypto->fh->fh2.iv));
893 crypto->tkey = gcry_malloc(gcrykeysize);
895 if (!crypto->tkey) {
896 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
897 return gpg_error_from_errno(ENOMEM);
900 memcpy(crypto->tkey, crypto->key, gcrykeysize);
901 guchar *tkey = crypto->tkey;
902 tkey[0] ^= 1;
904 if ((rc = gcry_cipher_setkey(crypto->gh, crypto->tkey, gcrykeysize))) {
905 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
906 return rc;
909 iter_progress = (guint64)get_key_file_integer(
910 client ? client->filename : "global", "iteration_progress");
912 if (iter_progress && crypto->fh->fh2.iter >= iter_progress) {
913 rc = send_status(client ? client->ctx : NULL, STATUS_ENCRYPT,
914 "0 %llu", crypto->fh->fh2.iter);
915 pth_cancel_point();
917 if (rc)
918 return rc;
921 while (xiter < crypto->fh->fh2.iter-1) {
922 if (iter_progress > 0 && xiter >= iter_progress) {
923 if (!(xiter % iter_progress)) {
924 rc = send_status(client ? client->ctx : NULL, STATUS_ENCRYPT,
925 "%llu %llu", ++n_iter * iter_progress,
926 crypto->fh->fh2.iter);
927 pth_cancel_point();
929 if (rc)
930 return rc;
934 if ((rc = gcry_cipher_setiv(crypto->gh, crypto->fh->fh2.iv,
935 sizeof(crypto->fh->fh2.iv)))) {
936 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
937 return rc;
940 rc = iterate_crypto_once(client, crypto, STATUS_ENCRYPT);
942 if (rc) {
943 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
944 return rc;
947 xiter++;
950 if ((rc = gcry_cipher_setiv(crypto->gh, crypto->fh->fh2.iv,
951 sizeof(crypto->fh->fh2.iv)))) {
952 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
953 return rc;
956 if ((rc = gcry_cipher_setkey(crypto->gh, crypto->key, gcrykeysize))) {
957 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
958 return rc;
961 rc = iterate_crypto_once(client, crypto, STATUS_ENCRYPT);
963 if (rc)
964 return rc;
966 if (iter_progress && crypto->fh->fh2.iter >= iter_progress) {
967 rc = send_status(client ? client->ctx : NULL, STATUS_ENCRYPT,
968 "%llu %llu", crypto->fh->fh2.iter, crypto->fh->fh2.iter);
969 pth_cancel_point();
971 if (rc)
972 return rc;
975 write_file:
976 if (filename) {
977 if (!client && !strcmp(filename, "-")) {
978 crypto->fh->fd = STDOUT_FILENO;
979 goto do_write_file;
982 if (lstat(filename, &st) == 0) {
983 pth_cancel_point();
984 mode = st.st_mode & (S_IRWXU|S_IRWXG|S_IRWXO);
987 * FIXME What if the file has an ACL?
989 if (!(mode & S_IWUSR))
990 return gpg_error_from_errno(EACCES);
992 else {
993 pth_cancel_point();
994 if (errno != ENOENT)
995 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 else
1011 * xml_import() or convert_file() from command line.
1013 crypto->fh->fd = STDOUT_FILENO;
1015 do_write_file:
1016 crypto->fh->fh2.version = VERSION_HEX;
1017 len = pth_write(crypto->fh->fd, &crypto->fh->fh2, sizeof(crypto->fh->fh2));
1018 pth_cancel_point();
1020 if (len != sizeof(crypto->fh->fh2)) {
1021 len = errno;
1023 if (filename && strcmp(filename, "-"))
1024 unlink(tmp);
1026 return gpg_error_from_errno(len);
1029 len = pth_write(crypto->fh->fd, crypto->inbuf, crypto->insize);
1030 pth_cancel_point();
1032 if (len != crypto->insize) {
1033 pth_cancel_point();
1034 len = errno;
1036 if (filename && strcmp(filename, "-")) {
1037 unlink(tmp);
1038 pth_cancel_point();
1041 return gpg_error_from_errno(len);
1044 if (fsync(crypto->fh->fd) == -1) {
1045 pth_cancel_point();
1046 len = errno;
1048 if (filename && strcmp(filename, "-"))
1049 unlink(tmp);
1051 return gpg_error_from_errno(len);
1054 if (filename && strcmp(filename, "-")) {
1055 if (mode && get_key_file_boolean(filename, "backup") == TRUE) {
1056 gchar tmp2[FILENAME_MAX];
1058 g_snprintf(tmp2, sizeof(tmp2), "%s.backup", filename);
1060 if (rename(filename, tmp2) == -1) {
1061 pth_cancel_point();
1062 unlink(tmp);
1063 len = errno;
1064 return gpg_error_from_errno(len);
1068 if (rename(tmp, filename) == -1) {
1069 pth_cancel_point();
1070 len = errno;
1071 unlink(tmp);
1072 return gpg_error_from_errno(len);
1075 if (mode) {
1076 chmod(filename, mode);
1077 pth_cancel_point();
1081 if (client && lstat(filename, &st) == 0)
1082 client->mtime = st.st_mtime;
1084 pth_cancel_point();
1085 return 0;
1088 static gpg_error_t save_command_finalize(assuan_context_t ctx, guchar *key,
1089 gboolean cached)
1091 struct client_s *client = assuan_get_pointer(ctx);
1092 gpointer xmlbuf;
1093 gulong len, outsize = 0;
1094 guint iter;
1095 gint timeout;
1096 gpointer outbuf;
1097 gint zrc;
1098 gpg_error_t rc;
1100 if (client->crypto->key && client->crypto->key != key)
1101 gcry_free(client->crypto->key);
1103 client->crypto->key = key;
1104 xmlDocDumpFormatMemory(client->doc, (xmlChar **)&xmlbuf, (gint *)&len, 0);
1105 iter = (guint)get_key_file_integer(client->filename, "compression_level");
1107 if (iter < 0)
1108 iter = 0;
1110 if (do_compress(ctx, (gint)iter, xmlbuf, len, &outbuf, &outsize, &zrc)
1111 == FALSE) {
1112 xmlFree(xmlbuf);
1113 cleanup_crypto(&client->crypto);
1115 if (zrc == Z_MEM_ERROR)
1116 return send_syserror(ctx, ENOMEM);
1117 else
1118 return send_error(ctx, GPG_ERR_COMPR_ALGO);
1120 else {
1121 gcry_free(xmlbuf);
1122 xmlbuf = outbuf;
1123 len = outsize;
1126 client->crypto->fh = g_malloc0(sizeof(file_header_internal_t));
1128 if (!client->crypto->fh) {
1129 cleanup_crypto(&client->crypto);
1130 gcry_free(outbuf);
1131 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1132 return send_syserror(ctx, ENOMEM);
1135 iter = get_key_file_integer(client->filename, "iterations");
1136 client->crypto->fh->fh2.iter = iter < 0 ? 0 : iter;
1137 client->crypto->inbuf = xmlbuf;
1138 client->crypto->insize = len;
1139 rc = do_xml_encrypt(client, client->crypto, client->filename);
1141 if (rc) {
1142 cleanup_crypto(&client->crypto);
1143 return send_error(ctx, rc);
1146 timeout = get_key_file_integer(client->filename, "cache_timeout");
1147 CACHE_LOCK(client->ctx);
1149 if (cached) {
1150 cache_reset_timeout(client->md5file, timeout);
1151 CACHE_UNLOCK;
1153 if (client->new == TRUE)
1154 send_status_all(STATUS_CACHE);
1156 client->new = FALSE;
1157 cleanup_crypto(&client->crypto);
1158 return send_error(ctx, 0);
1161 if (cache_update_key(client->md5file, client->crypto->key) == FALSE) {
1162 CACHE_UNLOCK;
1163 cleanup_crypto(&client->crypto);
1164 return send_syserror(ctx, ENOMEM);
1167 client->new = FALSE;
1168 cache_reset_timeout(client->md5file, timeout);
1169 CACHE_UNLOCK;
1170 send_status_all(STATUS_CACHE);
1171 cleanup_crypto(&client->crypto);
1172 return send_error(ctx, 0);
1175 static int save_command(assuan_context_t ctx, char *line)
1177 gboolean cached = FALSE;
1178 struct stat st;
1179 struct client_s *client = assuan_get_pointer(ctx);
1180 gpg_error_t rc;
1182 rc = lock_file_mutex(client);
1184 if (rc)
1185 return send_error(ctx, rc);
1187 rc = file_modified(client);
1189 if (rc)
1190 return send_error(ctx, rc);
1192 if (lstat(client->filename, &st) == -1 && errno != ENOENT)
1193 return send_syserror(ctx, errno);
1195 if (errno != ENOENT && !S_ISREG(st.st_mode)) {
1196 log_write("%s: %s", client->filename, pwmd_strerror(GPG_ERR_ENOANO));
1197 return send_error(ctx, GPG_ERR_ENOANO);
1200 CACHE_LOCK(ctx);
1201 cached = cache_iscached(client->md5file);
1202 CACHE_UNLOCK;
1205 * If a cache entry doesn't exist for this file and the file has a
1206 * "key_file" or "key" parameter, then it's an error. The reason is that
1207 * cache expiration would be useless.
1209 if (cached == FALSE) {
1210 gchar *tmp = get_key_file_string(client->filename, "key_file");
1212 if (tmp) {
1213 g_free(tmp);
1214 return send_error(ctx, GPG_ERR_WRONG_KEY_USAGE);
1218 cached = FALSE;
1219 client->crypto = init_client_crypto();
1221 if (!client->crypto) {
1222 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1223 return send_syserror(ctx, ENOMEM);
1226 client->crypto->key = gcry_malloc(gcrykeysize);
1228 if (!client->crypto->key) {
1229 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1230 cleanup_crypto(&client->crypto);
1231 return send_syserror(ctx, ENOMEM);
1234 memset(client->crypto->key, '!', gcrykeysize);
1236 if (get_key_file_integer(client->filename, "iterations") <= 0)
1237 goto done;
1239 if (!line || !*line) {
1240 client->crypto->tkey = gcry_malloc(gcrykeysize);
1242 if (!client->crypto->tkey) {
1243 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1244 cleanup_crypto(&client->crypto);
1245 return send_syserror(ctx, ENOMEM);
1248 memset(client->crypto->tkey, '!', gcrykeysize);
1249 CACHE_LOCK(ctx);
1251 if (cache_get_key(client->md5file, client->crypto->key) == FALSE ||
1252 memcmp(client->crypto->key, client->crypto->tkey,
1253 gcrykeysize) == 0) {
1254 CACHE_UNLOCK;
1256 #ifdef WITH_PINENTRY
1257 if (client->pinentry->enable == FALSE ||
1258 get_key_file_boolean(client->filename, "enable_pinentry") == FALSE) {
1259 /* Empty keys are allowed. */
1260 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, "", 1);
1261 goto done;
1264 lock_pin_mutex(client);
1265 client->pinentry->which = PINENTRY_SAVE;
1266 rc = pinentry_fork(ctx);
1268 if (rc) {
1269 unlock_pin_mutex(client->pinentry);
1270 return send_error(ctx, rc);
1273 client->pinentry->cb = save_command_finalize;
1274 client->pinentry->status = PINENTRY_INIT;
1275 return 0;
1276 #else
1277 /* Empty keys are allowed. */
1278 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, "", 1);
1279 goto done;
1280 #endif
1282 else {
1283 CACHE_UNLOCK;
1284 cached = TRUE;
1287 else {
1288 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, line,
1289 strlen(line));
1290 memset(line, 0, strlen(line));
1293 done:
1294 return save_command_finalize(ctx, client->crypto->key, cached);
1297 static int delete_command(assuan_context_t ctx, char *line)
1299 struct client_s *client = assuan_get_pointer(ctx);
1300 gchar **req;
1301 gpg_error_t rc;
1302 xmlNodePtr n;
1304 rc = file_modified(client);
1306 if (rc)
1307 return send_error(ctx, rc);
1309 if (strchr(line, '\t'))
1310 req = split_input_line(line, "\t", -1);
1311 else
1312 req = split_input_line(line, " ", -1);
1314 if (!req || !*req)
1315 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
1317 n = find_account(client->doc, &req, &rc, NULL, 0);
1319 if (!n) {
1320 g_strfreev(req);
1321 return send_error(ctx, rc);
1325 * No sub-node defined. Remove the entire node (account).
1327 if (!req[1]) {
1328 if (n) {
1329 xmlUnlinkNode(n);
1330 xmlFreeNode(n);
1333 g_strfreev(req);
1334 return send_error(ctx, 0);
1337 n = find_elements(client->doc, n->children, req+1, &rc, NULL, NULL, NULL, FALSE, 0, NULL);
1338 g_strfreev(req);
1340 if (!n)
1341 return send_error(ctx, rc);
1343 if (n) {
1344 xmlUnlinkNode(n);
1345 xmlFreeNode(n);
1348 return send_error(ctx, 0);
1352 * Don't return with assuan_process_done() here. This has been called from
1353 * assuan_process_next() and the command should be finished in
1354 * client_thread().
1356 static int store_command_finalize(gpointer data, gint assuan_rc, guchar *line,
1357 gsize len)
1359 assuan_context_t ctx = data;
1360 struct client_s *client = assuan_get_pointer(ctx);
1361 gchar **req;
1362 xmlNodePtr n;
1363 gpg_error_t rc = file_modified(client);
1365 if (assuan_rc || rc) {
1366 if (line)
1367 xfree(line);
1368 return assuan_rc ? assuan_rc : rc;
1371 req = split_input_line((gchar *)line, "\t", 0);
1372 xfree(line);
1374 if (!req || !*req)
1375 return EPWMD_COMMAND_SYNTAX;
1377 if (valid_xml_element((xmlChar *)*req) == FALSE) {
1378 g_strfreev(req);
1379 return EPWMD_INVALID_ELEMENT;
1382 if (valid_element_path(req+1, TRUE) == FALSE) {
1383 g_strfreev(req);
1384 return EPWMD_INVALID_ELEMENT;
1387 again:
1388 n = find_account(client->doc, &req, &rc, NULL, 0);
1390 if (rc && rc == EPWMD_ELEMENT_NOT_FOUND) {
1391 rc = new_account(client->doc, *req);
1393 if (rc) {
1394 g_strfreev(req);
1395 return rc;
1398 goto again;
1401 if (!n) {
1402 g_strfreev(req);
1403 return rc;
1406 if (req[1]) {
1407 if (!n->children)
1408 create_elements_cb(n, req+1, &rc, NULL);
1409 else
1410 find_elements(client->doc, n->children, req+1, &rc,
1411 NULL, NULL, create_elements_cb, FALSE, 0, NULL);
1414 g_strfreev(req);
1415 client->inquire_status = INQUIRE_DONE;
1416 return rc;
1419 static int store_command(assuan_context_t ctx, char *line)
1421 struct client_s *client = assuan_get_pointer(ctx);
1422 gpg_error_t rc = file_modified(client);
1424 if (rc)
1425 return send_error(ctx, rc);
1427 pth_cancel_point();
1428 rc = assuan_inquire_ext(ctx, "STORE", 0, store_command_finalize, ctx);
1429 pth_cancel_point();
1431 if (rc)
1432 return send_error(ctx, rc);
1434 /* Don't return with assuan_process_done() here. This is an INQUIRE. */
1435 client->inquire_status = INQUIRE_BUSY;
1436 return 0;
1439 static void *send_data_cb(void *arg)
1441 struct assuan_cmd_s *data = arg;
1442 gpg_error_t rc = assuan_send_data(data->ctx, data->line, data->line_len);
1443 pth_exit((void *)rc);
1444 return NULL;
1447 /* For every assuan command that needs to be sent to the client, a timeout is
1448 * needed to determine if the client lost the connection. The timeout is the
1449 * same as the "keepalive" configuration parameter or a default if unset.
1451 gpg_error_t do_assuan_command(assuan_context_t ctx,
1452 void *(*cb)(void *data), void *data)
1454 pth_attr_t attr = pth_attr_new();
1455 pth_t tid;
1456 gint n;
1457 gint to = get_key_file_integer("global", "keepalive");
1458 pth_event_t ev, tev;
1459 pth_status_t st;
1460 gpg_error_t rc;
1462 pth_attr_init(attr);
1463 pth_attr_set(attr, PTH_ATTR_JOINABLE, TRUE);
1464 tid = pth_spawn(attr, cb, data);
1465 n = errno;
1466 pth_attr_destroy(attr);
1468 if (!tid) {
1469 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
1470 _gpg_strerror(gpg_error_from_errno(n)));
1471 return gpg_error_from_errno(n);
1474 to = to <= 0 ? DEFAULT_KEEPALIVE_TO : to;
1475 ev = pth_event(PTH_EVENT_TID|PTH_UNTIL_TID_DEAD, tid);
1476 tev = pth_event(PTH_EVENT_TIME, pth_timeout(to, 0));
1477 ev = pth_event_concat(ev, tev, NULL);
1478 pth_yield(tid);
1479 pth_wait(ev);
1480 st = pth_event_status(ev);
1482 if (st == PTH_STATUS_FAILED) {
1483 pth_cancel(tid);
1484 rc = GPG_ERR_ASS_WRITE_ERROR;
1486 else if (st == PTH_STATUS_OCCURRED) {
1487 pth_join(tid, (void **)&rc);
1489 else {
1490 st = pth_event_status(tev);
1492 if (st == PTH_STATUS_OCCURRED) {
1493 pth_cancel(tid);
1494 rc = GPG_ERR_ASS_WRITE_ERROR;
1498 return rc;
1501 static gpg_error_t xfer_data(assuan_context_t ctx, const gchar *line,
1502 gint total)
1504 int to_send;
1505 int sent = 0;
1506 gpg_error_t rc;
1507 struct assuan_cmd_s data;
1509 if (total < ASSUAN_LINELENGTH)
1510 to_send = total;
1511 else
1512 to_send = ASSUAN_LINELENGTH;
1514 data.ctx = ctx;
1516 do {
1517 if (sent + to_send > total)
1518 to_send = total - sent;
1520 data.line = (gchar *)line+sent;
1521 data.line_len = to_send;
1522 rc = do_assuan_command(ctx, send_data_cb, &data);
1524 if (!rc) {
1525 sent += to_send;
1526 rc = send_status(ctx, STATUS_XFER, "%li %li", sent, total);
1528 } while (!rc && sent < total);
1530 return rc;
1533 static int get_command(assuan_context_t ctx, char *line)
1535 struct client_s *client = assuan_get_pointer(ctx);
1536 gchar **req;
1537 gpg_error_t rc;
1538 xmlNodePtr n;
1540 rc = file_modified(client);
1542 if (rc)
1543 return send_error(ctx, rc);
1545 req = split_input_line(line, "\t", -1);
1547 if (!req || !*req) {
1548 g_strfreev(req);
1549 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
1552 n = find_account(client->doc, &req, &rc, NULL, 0);
1554 if (!n) {
1555 g_strfreev(req);
1556 return send_error(ctx, rc);
1559 if (req[1])
1560 n = find_elements(client->doc, n->children, req+1, &rc, NULL, NULL, NULL, FALSE, 0, NULL);
1562 g_strfreev(req);
1564 if (rc)
1565 return send_error(ctx, rc);
1567 if (!n || !n->children)
1568 return send_error(ctx, EPWMD_EMPTY_ELEMENT);
1570 n = find_text_node(n->children);
1572 if (!n || !n->content || !*n->content)
1573 return send_error(ctx, EPWMD_EMPTY_ELEMENT);
1575 pth_cancel_point();
1576 rc = xfer_data(ctx, (gchar *)n->content, xmlStrlen(n->content));
1577 return send_error(ctx, rc);
1580 static xmlNodePtr realpath_elements_cb(xmlNodePtr node, gchar **target,
1581 gpg_error_t *rc, gchar **req_orig, void *data)
1583 gchar *path = *(gchar **)data;
1584 gchar *tmp = NULL, *result;
1586 if (path) {
1587 g_free(path);
1588 *(gchar **)data = NULL;
1591 path = g_strjoinv("\t", target);
1593 if (!path) {
1594 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1595 *rc = gpg_error_from_errno(ENOMEM);
1596 return NULL;
1599 if (req_orig) {
1600 tmp = g_strjoinv("\t", req_orig);
1602 if (!tmp) {
1603 g_free(path);
1604 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1605 *rc = gpg_error_from_errno(ENOMEM);
1606 return NULL;
1610 if (tmp && *tmp)
1611 result = g_strdup_printf("%s\t%s", path, tmp);
1612 else
1613 result = g_strdup(path);
1615 if (!result) {
1616 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1617 *rc = gpg_error_from_errno(ENOMEM);
1618 g_free(path);
1619 g_free(tmp);
1620 return NULL;
1623 g_free(path);
1624 g_free(tmp);
1625 *(gchar **)data = result;
1626 return node;
1629 static void list_command_cleanup1(void *arg);
1630 static int realpath_command(assuan_context_t ctx, char *line)
1632 gpg_error_t rc;
1633 struct client_s *client = assuan_get_pointer(ctx);
1634 gchar **req;
1635 gchar *t;
1636 gint i;
1637 xmlNodePtr n;
1638 GString *string;
1639 gchar *rp = NULL;
1641 rc = file_modified(client);
1643 if (rc)
1644 return send_error(ctx, rc);
1646 if (strchr(line, '\t') != NULL) {
1647 if ((req = split_input_line(line, "\t", 0)) == NULL)
1648 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
1650 else {
1651 if ((req = split_input_line(line, " ", 0)) == NULL)
1652 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
1655 n = find_account(client->doc, &req, &rc, NULL, 0);
1657 if (!n) {
1658 g_strfreev(req);
1659 return send_error(ctx, rc);
1662 rp = g_strjoinv("\t", req);
1664 if (!rp) {
1665 g_strfreev(req);
1666 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1667 return send_syserror(ctx, ENOMEM);
1670 if (req[1]) {
1671 n = find_elements(client->doc, n->children, req+1, &rc,
1672 NULL, realpath_elements_cb, NULL, FALSE, 0, &rp);
1674 if (!n) {
1675 g_free(rp);
1676 g_strfreev(req);
1677 return send_error(ctx, rc);
1681 string = g_string_new(rp);
1682 g_free(rp);
1683 g_strfreev(req);
1685 if (!string) {
1686 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1687 return send_syserror(ctx, ENOMEM);
1690 again:
1691 for (i = 0, t = string->str + i; *t; t++, i++) {
1692 if ((!i && *t != '!') || (*t == '\t' && *(t+1) && *(t+1) != '!')) {
1693 string = g_string_insert_c(string, !i ? i++ : ++i, '!');
1694 goto again;
1698 rc = xfer_data(ctx, string->str, string->len);
1699 list_command_cleanup1(string);
1700 return send_error(ctx, rc);
1703 static void list_command_cleanup1(void *arg)
1705 g_string_free((GString *)arg, TRUE);
1708 static void list_command_cleanup2(void *arg)
1710 struct element_list_s *elements = arg;
1712 if (elements) {
1713 gint total = g_slist_length(elements->list);
1714 gint i;
1716 for (i = 0; i < total; i++) {
1717 gchar *tmp = g_slist_nth_data(elements->list, i);
1718 g_free(tmp);
1721 g_slist_free(elements->list);
1723 if (elements->prefix)
1724 g_free(elements->prefix);
1726 g_free(elements);
1730 static int list_command(assuan_context_t ctx, char *line)
1732 struct client_s *client = assuan_get_pointer(ctx);
1733 gpg_error_t rc;
1734 struct element_list_s *elements = NULL;
1735 gchar *tmp;
1737 if (disable_list_and_dump == TRUE)
1738 return send_error(ctx, GPG_ERR_NOT_IMPLEMENTED);
1740 rc = file_modified(client);
1742 if (rc)
1743 return send_error(ctx, rc);
1745 if (!*line) {
1746 GString *str;
1748 rc = list_accounts(client->doc, &str);
1750 if (rc)
1751 return send_error(ctx, rc);
1753 rc = xfer_data(ctx, str->str, str->len);
1754 list_command_cleanup1(str);
1755 return send_error(ctx, rc);
1758 elements = g_malloc0(sizeof(struct element_list_s));
1760 if (!elements) {
1761 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1762 rc = gpg_err_code_from_errno(ENOMEM);
1763 goto fail;
1766 rc = create_path_list(client->doc, elements, line);
1768 if (rc)
1769 goto fail;
1771 if (elements) {
1772 gint total = g_slist_length(elements->list);
1773 gint i;
1774 GString *str;
1776 if (!total) {
1777 rc = EPWMD_EMPTY_ELEMENT;
1778 goto fail;
1781 str = g_string_new(NULL);
1783 if (!str) {
1784 rc = gpg_err_code_from_errno(ENOMEM);
1785 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1786 goto fail;
1789 for (i = 0; i < total; i++) {
1790 tmp = g_slist_nth_data(elements->list, i);
1791 g_string_append_printf(str, "%s%s", tmp, i+1 == total ? "" : "\n");
1794 rc = xfer_data(ctx, str->str, str->len);
1795 list_command_cleanup1(str);
1797 else
1798 rc = EPWMD_EMPTY_ELEMENT;
1800 fail:
1801 list_command_cleanup2(elements);
1802 return send_error(ctx, rc);
1805 static gpg_error_t add_attribute(xmlNodePtr node, const gchar *name,
1806 const gchar *value)
1808 xmlAttrPtr a;
1810 if ((a = xmlHasProp(node, (xmlChar *)name)) == NULL) {
1811 a = xmlNewProp(node, (xmlChar *)name, (xmlChar *)value);
1813 if (!a)
1814 return EPWMD_LIBXML_ERROR;
1816 else
1817 xmlNodeSetContent(a->children, (xmlChar *)value);
1819 return 0;
1823 * req[0] - element path
1825 static int attribute_list(assuan_context_t ctx, gchar **req)
1827 struct client_s *client = assuan_get_pointer(ctx);
1828 gchar **attrlist = NULL;
1829 gint i = 0;
1830 gchar **path = NULL;
1831 xmlAttrPtr a;
1832 xmlNodePtr n, an;
1833 gchar *line;
1834 gpg_error_t rc;
1836 if (!req || !req[0])
1837 return EPWMD_COMMAND_SYNTAX;
1839 if ((path = split_input_line(req[0], "\t", 0)) == NULL) {
1841 * The first argument may be only an account.
1843 if ((path = split_input_line(req[0], " ", 0)) == NULL)
1844 return EPWMD_COMMAND_SYNTAX;
1847 n = find_account(client->doc, &path, &rc, NULL, 0);
1849 if (!n) {
1850 g_strfreev(path);
1851 return rc;
1854 if (path[1]) {
1855 n = find_elements(client->doc, n->children, path+1, &rc,
1856 NULL, NULL, NULL, FALSE, 0, NULL);
1858 if (!n) {
1859 g_strfreev(path);
1860 return rc;
1864 g_strfreev(path);
1866 for (a = n->properties; a; a = a->next) {
1867 gchar **pa;
1869 if ((pa = g_realloc(attrlist, (i + 2) * sizeof(gchar *))) == NULL) {
1870 if (attrlist)
1871 g_strfreev(attrlist);
1873 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1874 return gpg_error_from_errno(ENOMEM);
1877 attrlist = pa;
1878 an = a->children;
1879 attrlist[i] = g_strdup_printf("%s %s", (gchar *)a->name, (gchar *)an->content);
1881 if (!attrlist[i]) {
1882 g_strfreev(attrlist);
1883 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1884 return gpg_error_from_errno(ENOMEM);
1887 attrlist[++i] = NULL;
1890 if (!attrlist)
1891 return EPWMD_EMPTY_ELEMENT;
1893 line = g_strjoinv("\n", attrlist);
1895 if (!line) {
1896 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1897 g_strfreev(attrlist);
1898 return gpg_error_from_errno(ENOMEM);
1901 rc = xfer_data(ctx, line, strlen(line));
1902 g_free(line);
1903 req_cleanup(attrlist);
1904 return rc;
1908 * req[0] - attribute
1909 * req[1] - element path
1911 static int attribute_delete(struct client_s *client, gchar **req)
1913 xmlAttrPtr a;
1914 xmlNodePtr n;
1915 gchar **path = NULL;
1916 gpg_error_t rc;
1918 if (!req || !req[0] || !req[1])
1919 return EPWMD_COMMAND_SYNTAX;
1921 if ((path = split_input_line(req[1], "\t", 0)) == NULL) {
1923 * The first argument may be only an account.
1925 if ((path = split_input_line(req[1], " ", 0)) == NULL)
1926 return EPWMD_COMMAND_SYNTAX;
1930 * Don't remove the "name" attribute for the account element. To remove an
1931 * account use DELETE <account>.
1933 if (!path[1] && xmlStrEqual((xmlChar *)req[0], (xmlChar *)"name")) {
1934 rc = EPWMD_ATTR_SYNTAX;
1935 goto fail;
1938 n = find_account(client->doc, &path, &rc, NULL, 0);
1940 if (!n)
1941 goto fail;
1943 if (path[1]) {
1944 n = find_elements(client->doc, n->children, path+1, &rc,
1945 NULL, NULL, NULL, FALSE, 0, NULL);
1947 if (!n)
1948 goto fail;
1951 g_strfreev(path);
1953 if ((a = xmlHasProp(n, (xmlChar *)req[0])) == NULL)
1954 return EPWMD_ATTR_NOT_FOUND;
1956 if (xmlRemoveProp(a) == -1)
1957 return EPWMD_LIBXML_ERROR;
1959 return 0;
1961 fail:
1962 g_strfreev(path);
1963 return rc;
1966 static xmlNodePtr create_element_path(struct client_s *client, gchar ***path,
1967 gpg_error_t *rc)
1969 gchar **src = *path;
1970 gchar **src_orig = g_strdupv(src);
1971 xmlNodePtr n = NULL;
1973 *rc = 0;
1975 if (!src_orig) {
1976 *rc = gpg_error_from_errno(ENOMEM);
1977 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1978 goto fail;
1981 again:
1982 n = find_account(client->doc, &src, rc, NULL, 0);
1984 if (!n) {
1985 if (*rc == EPWMD_ELEMENT_NOT_FOUND) {
1986 *rc = new_account(client->doc, src[0]);
1988 if (*rc)
1989 goto fail;
1991 goto again;
1993 else
1994 goto fail;
1997 if (src[1]) {
1998 if (!n->children)
1999 n = create_target_elements_cb(n, src+1, rc, NULL);
2000 else
2001 n = find_elements(client->doc, n->children, src+1, rc,
2002 NULL, NULL, create_target_elements_cb, FALSE, 0, NULL);
2004 if (!n)
2005 goto fail;
2008 * Reset the position of the element tree now that the elements
2009 * have been created.
2011 g_strfreev(src);
2012 src = src_orig;
2013 src_orig = NULL;
2014 n = find_account(client->doc, &src, rc, NULL, 0);
2016 if (!n)
2017 goto fail;
2019 n = find_elements(client->doc, n->children, src+1, rc,
2020 NULL, NULL, NULL, FALSE, 0, NULL);
2022 if (!n)
2023 goto fail;
2026 fail:
2027 if (src_orig)
2028 g_strfreev(src_orig);
2030 *path = src;
2031 return n;
2035 * Creates a "target" attribute. When other commands encounter an element with
2036 * this attribute, the element path is modified to the target value. If the
2037 * source element path doesn't exist when using 'ATTR SET target', it is
2038 * created, but the destination element path must exist.
2040 * req[0] - source element path
2041 * req[1] - destination element path
2043 static gpg_error_t target_attribute(struct client_s *client, gchar **req)
2045 gchar **src, **dst, *line = NULL;
2046 gpg_error_t rc;
2047 xmlNodePtr n;
2049 if (!req || !req[0] || !req[1])
2050 return EPWMD_COMMAND_SYNTAX;
2052 if ((src = split_input_line(req[0], "\t", 0)) == NULL) {
2054 * The first argument may be only an account.
2056 if ((src = split_input_line(req[0], " ", 0)) == NULL)
2057 return EPWMD_COMMAND_SYNTAX;
2060 if (valid_element_path(src, FALSE) == FALSE) {
2061 g_strfreev(src);
2062 return EPWMD_INVALID_ELEMENT;
2065 if ((dst = split_input_line(req[1], "\t", 0)) == NULL) {
2067 * The first argument may be only an account.
2069 if ((dst = split_input_line(req[1], " ", 0)) == NULL) {
2070 rc = EPWMD_COMMAND_SYNTAX;
2071 goto fail;
2075 n = find_account(client->doc, &dst, &rc, NULL, 0);
2078 * Make sure the destination element path exists.
2080 if (!n)
2081 goto fail;
2083 if (dst[1]) {
2084 n = find_elements(client->doc, n->children, dst+1, &rc,
2085 NULL, NULL, NULL, FALSE, 0, NULL);
2087 if (!n)
2088 goto fail;
2091 n = create_element_path(client, &src, &rc);
2093 if (rc)
2094 goto fail;
2096 line = g_strjoinv("\t", dst);
2098 if (!line) {
2099 rc = gpg_error_from_errno(ENOMEM);
2100 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2101 goto fail;
2104 rc = add_attribute(n, "target", line);
2106 fail:
2107 g_free(line);
2108 g_strfreev(src);
2109 g_strfreev(dst);
2110 return rc;
2114 * req[0] - account name
2115 * req[1] - new name
2117 static gpg_error_t name_attribute(struct client_s *client, gchar **req)
2119 gpg_error_t rc;
2120 gchar **tmp;
2121 xmlNodePtr n;
2123 tmp = g_strdupv(req);
2125 if (!tmp) {
2126 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2127 return gpg_error_from_errno(ENOMEM);
2130 n = find_account(client->doc, &tmp, &rc, NULL, 0);
2131 g_strfreev(tmp);
2133 if (!n)
2134 return rc;
2136 if (g_utf8_collate(req[0], req[1]) == 0)
2137 return 0;
2140 * Will not overwrite an existing account.
2142 tmp = g_strdupv(req+1);
2144 if (!tmp) {
2145 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2146 return gpg_error_from_errno(ENOMEM);
2149 n = find_account(client->doc, &tmp, &rc, NULL, 0);
2150 g_strfreev(tmp);
2152 if (rc && rc != EPWMD_ELEMENT_NOT_FOUND)
2153 return rc;
2155 if (n)
2156 return EPWMD_ACCOUNT_EXISTS;
2159 * Whitespace not allowed in account names.
2161 if (contains_whitespace(req[1]) == TRUE)
2162 return EPWMD_ATTR_SYNTAX;
2164 tmp = g_strdupv(req);
2166 if (!tmp) {
2167 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2168 return gpg_error_from_errno(ENOMEM);
2171 n = find_account(client->doc, &tmp, &rc, NULL, 0);
2172 g_strfreev(tmp);
2174 if (!n)
2175 return EPWMD_ELEMENT_NOT_FOUND;
2177 return add_attribute(n, "name", req[1]);
2181 * req[0] - attribute
2182 * req[1] - element path
2184 static int attribute_get(assuan_context_t ctx, gchar **req)
2186 struct client_s *client = assuan_get_pointer(ctx);
2187 xmlNodePtr n;
2188 xmlChar *a;
2189 gchar **path= NULL;
2190 gpg_error_t rc;
2192 if (!req || !req[0] || !req[1])
2193 return EPWMD_COMMAND_SYNTAX;
2195 if (strchr(req[1], '\t')) {
2196 if ((path = split_input_line(req[1], "\t", 0)) == NULL)
2197 return EPWMD_COMMAND_SYNTAX;
2199 else {
2200 if ((path = split_input_line(req[1], " ", 0)) == NULL)
2201 return EPWMD_COMMAND_SYNTAX;
2204 n = find_account(client->doc, &path, &rc, NULL, 0);
2206 if (!n)
2207 goto fail;
2209 if (path[1]) {
2210 n = find_elements(client->doc, n->children, path+1, &rc,
2211 NULL, NULL, NULL, FALSE, 0, NULL);
2213 if (!n)
2214 goto fail;
2217 g_strfreev(path);
2219 if ((a = xmlGetProp(n, (xmlChar *)req[0])) == NULL)
2220 return EPWMD_ATTR_NOT_FOUND;
2222 rc = xfer_data(ctx, (gchar *)a, xmlStrlen(a));
2223 xmlFree(a);
2224 return rc;
2226 fail:
2227 g_strfreev(path);
2228 return rc;
2232 * req[0] - attribute
2233 * req[1] - element path
2234 * req[2] - value
2236 static int attribute_set(struct client_s *client, gchar **req)
2238 gchar **path = NULL;
2239 gpg_error_t rc;
2240 xmlNodePtr n;
2242 if (!req || !req[0] || !req[1] || !req[2])
2243 return EPWMD_COMMAND_SYNTAX;
2246 * Reserved attribute names.
2248 if (g_utf8_collate(req[0], "name") == 0) {
2250 * Only reserved for the account element. Not the rest of the
2251 * document.
2253 if (strchr(req[1], '\t') == NULL)
2254 return name_attribute(client, req + 1);
2256 else if (g_utf8_collate(req[0], "target") == 0)
2257 return target_attribute(client, req + 1);
2259 if ((path = split_input_line(req[1], "\t", 0)) == NULL) {
2261 * The first argument may be only an account.
2263 if ((path = split_input_line(req[1], " ", 0)) == NULL)
2264 return EPWMD_COMMAND_SYNTAX;
2267 n = find_account(client->doc, &path, &rc, NULL, 0);
2269 if (!n)
2270 goto fail;
2272 if (path[1]) {
2273 n = find_elements(client->doc, n->children, path+1, &rc,
2274 NULL, NULL, NULL, FALSE, 0, NULL);
2276 if (!n)
2277 goto fail;
2280 g_strfreev(path);
2281 return add_attribute(n, req[0], req[2]);
2283 fail:
2284 g_strfreev(path);
2285 return rc;
2289 * req[0] - command
2290 * req[1] - attribute name or element path if command is LIST
2291 * req[2] - element path
2292 * req[2] - element path or value
2294 static int attr_command(assuan_context_t ctx, char *line)
2296 struct client_s *client = assuan_get_pointer(ctx);
2297 gchar **req;
2298 gpg_error_t rc = 0;
2300 rc = file_modified(client);
2302 if (rc)
2303 return send_error(ctx, rc);
2305 req = split_input_line(line, " ", 4);
2307 if (!req || !req[0] || !req[1]) {
2308 g_strfreev(req);
2309 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2312 if (g_ascii_strcasecmp(req[0], "SET") == 0)
2313 rc = attribute_set(client, req+1);
2314 else if (g_ascii_strcasecmp(req[0], "GET") == 0)
2315 rc = attribute_get(ctx, req+1);
2316 else if (g_ascii_strcasecmp(req[0], "DELETE") == 0)
2317 rc = attribute_delete(client, req+1);
2318 else if (g_ascii_strcasecmp(req[0], "LIST") == 0)
2319 rc = attribute_list(ctx, req+1);
2320 else
2321 rc = EPWMD_COMMAND_SYNTAX;
2323 req_cleanup(req);
2324 return send_error(ctx, rc);
2327 static int iscached_command(assuan_context_t ctx, char *line)
2329 gchar **req = split_input_line(line, " ", 0);
2330 guchar md5file[16];
2331 gchar *path, *tmp;
2333 if (!req || !*req) {
2334 g_strfreev(req);
2335 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2338 if (!valid_filename(req[0])) {
2339 g_strfreev(req);
2340 return EPWMD_INVALID_FILENAME;
2343 tmp = get_key_file_string("global", "data_directory");
2345 if (!tmp) {
2346 g_strfreev(req);
2347 return gpg_error_from_errno(ENOMEM);
2350 path = expand_homedir(tmp);
2352 if (!path) {
2353 g_strfreev(req);
2354 g_free(tmp);
2355 return gpg_error_from_errno(ENOMEM);
2358 g_free(tmp);
2359 tmp = path;
2360 path = g_strdup_printf("%s/%s", tmp, req[0]);
2361 g_free(tmp);
2363 if (!path) {
2364 g_strfreev(req);
2365 return gpg_error_from_errno(ENOMEM);
2368 if (access(path, R_OK) == -1) {
2369 gpg_error_t rc = gpg_error_from_syserror();
2371 g_free(path);
2372 g_strfreev(req);
2373 return send_error(ctx, rc);
2376 g_free(path);
2377 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, req[0], strlen(req[0]));
2378 g_strfreev(req);
2379 CACHE_LOCK(ctx);
2381 if (cache_iscached(md5file) == FALSE) {
2382 CACHE_UNLOCK;
2383 return send_error(ctx, EPWMD_CACHE_NOT_FOUND);
2386 CACHE_UNLOCK;
2387 return send_error(ctx, 0);
2390 static int clearcache_command(assuan_context_t ctx, char *line)
2392 struct client_s *client = assuan_get_pointer(ctx);
2393 gchar **req = split_input_line(line, " ", 0);
2394 guchar md5file[16];
2396 CACHE_LOCK(ctx);
2398 if (!req || !*req) {
2399 g_strfreev(req);
2400 cache_clear(client->md5file, 2);
2401 CACHE_UNLOCK;
2402 return send_error(ctx, 0);
2405 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, req[0], strlen(req[0]));
2406 g_strfreev(req);
2408 if (cache_clear(md5file, 1) == FALSE) {
2409 CACHE_UNLOCK;
2410 return send_error(ctx, EPWMD_CACHE_NOT_FOUND);
2413 CACHE_UNLOCK;
2414 return send_error(ctx, 0);
2417 static int cachetimeout_command(assuan_context_t ctx, char *line)
2419 guchar md5file[16];
2420 glong timeout;
2421 gchar **req = split_input_line(line, " ", 0);
2422 gchar *p;
2424 if (!req || !*req || !req[1]) {
2425 g_strfreev(req);
2426 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2429 errno = 0;
2430 timeout = strtol(req[0], &p, 10);
2432 if (errno != 0 || *p != 0) {
2433 g_strfreev(req);
2434 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2437 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, req[1], strlen(req[1]));
2438 CACHE_LOCK(client->ctx);
2440 if (cache_set_timeout(md5file, timeout) == FALSE) {
2441 CACHE_UNLOCK;
2442 return send_error(ctx, EPWMD_CACHE_NOT_FOUND);
2445 CACHE_UNLOCK;
2446 return send_error(ctx, 0);
2449 static int dump_command(assuan_context_t ctx, char *line)
2451 xmlChar *xml;
2452 gssize len;
2453 struct client_s *client = assuan_get_pointer(ctx);
2454 gpg_error_t rc;
2456 if (disable_list_and_dump == TRUE)
2457 return send_error(ctx, GPG_ERR_NOT_IMPLEMENTED);
2459 rc = file_modified(client);
2461 if (rc)
2462 return send_error(ctx, rc);
2464 xmlDocDumpFormatMemory(client->doc, &xml, &len, 1);
2466 if (!xml) {
2467 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2468 return send_syserror(ctx, ENOMEM);
2471 rc = xfer_data(ctx, (gchar *)xml, len);
2472 xmlFree(xml);
2473 return send_error(ctx, rc);
2476 static int getconfig_command(assuan_context_t ctx, gchar *line)
2478 struct client_s *client = assuan_get_pointer(ctx);
2479 gpg_error_t rc = 0;
2480 gchar filename[255]={0}, param[747]={0};
2481 gchar *p, *tmp, *fp = client->filename, *paramp = line;
2483 if (strchr(line, ' ')) {
2484 sscanf(line, " %254[^ ] %746c", filename, param);
2485 fp = filename;
2486 paramp = param;
2489 if (fp && !valid_filename(fp))
2490 return send_error(ctx, EPWMD_INVALID_FILENAME);
2492 paramp = g_ascii_strdown(paramp, -1);
2494 if (!paramp) {
2495 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2496 return send_syserror(ctx, ENOMEM);
2499 p = get_key_file_string(fp ? fp : "global", paramp);
2500 g_free(paramp);
2502 if (!p)
2503 return send_error(ctx, GPG_ERR_NO_VALUE);
2505 tmp = expand_homedir(p);
2506 g_free(p);
2508 if (!tmp) {
2509 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2510 return send_syserror(ctx, ENOMEM);
2513 p = tmp;
2514 rc = xfer_data(ctx, p, strlen(p));
2515 g_free(p);
2516 return send_error(ctx, rc);
2519 struct xpath_s {
2520 xmlXPathContextPtr xp;
2521 xmlXPathObjectPtr result;
2522 xmlBufferPtr buf;
2523 gchar **req;
2526 static void xpath_command_cleanup(void *arg)
2528 struct xpath_s *xpath = arg;
2530 req_cleanup(xpath->req);
2532 if (xpath->buf)
2533 xmlBufferFree(xpath->buf);
2535 if (xpath->result)
2536 xmlXPathFreeObject(xpath->result);
2538 if (xpath->xp)
2539 xmlXPathFreeContext(xpath->xp);
2542 static int xpath_command(assuan_context_t ctx, gchar *line)
2544 struct client_s *client = assuan_get_pointer(ctx);
2545 gpg_error_t rc;
2546 struct xpath_s xpath;
2548 if (disable_list_and_dump == TRUE)
2549 return send_error(ctx, GPG_ERR_NOT_IMPLEMENTED);
2551 rc = file_modified(client);
2553 if (rc)
2554 return send_error(ctx, rc);
2556 if (!line || !*line)
2557 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2559 memset(&xpath, 0, sizeof(struct xpath_s));
2561 if ((xpath.req = split_input_line(line, "\t", 2)) == NULL) {
2562 if (strv_printf(&xpath.req, "%s", line) == FALSE)
2563 return send_syserror(ctx, ENOMEM);
2566 xpath.xp = xmlXPathNewContext(client->doc);
2568 if (!xpath.xp) {
2569 xpath_command_cleanup(&xpath);
2570 return send_error(ctx, EPWMD_LIBXML_ERROR);
2573 xpath.result = xmlXPathEvalExpression((xmlChar *)xpath.req[0], xpath.xp);
2575 if (!xpath.result) {
2576 xpath_command_cleanup(&xpath);
2577 return send_error(ctx, EPWMD_LIBXML_ERROR);
2580 if (xmlXPathNodeSetIsEmpty(xpath.result->nodesetval)) {
2581 rc = EPWMD_EMPTY_ELEMENT;
2582 goto fail;
2585 rc = recurse_xpath_nodeset(client->doc, xpath.result->nodesetval,
2586 (xmlChar *)xpath.req[1], &xpath.buf);
2588 if (rc)
2589 goto fail;
2590 else if (!xpath.req[1] && !xmlBufferLength(xpath.buf)) {
2591 rc = EPWMD_EMPTY_ELEMENT;
2592 goto fail;
2594 else if (xpath.req[1])
2595 goto fail;
2597 pth_cancel_point();
2598 rc = xfer_data(ctx, (gchar *)xmlBufferContent(xpath.buf),
2599 xmlBufferLength(xpath.buf));
2601 fail:
2602 xpath_command_cleanup(&xpath);
2603 return send_error(ctx, rc);
2606 static int import_command_finalize(gpointer data, gint assuan_rc, guchar *line,
2607 gsize len)
2609 struct client_s *client = assuan_get_pointer((assuan_context_t)data);
2610 gpg_error_t rc = file_modified(client);
2611 gchar **req, **path = NULL, **path_orig = NULL, *content;
2612 xmlDocPtr doc;
2613 xmlNodePtr n, root, copy;
2615 if (assuan_rc || rc) {
2616 if (line)
2617 xfree(line);
2618 return assuan_rc ? assuan_rc : rc;
2621 req = split_input_line((gchar *)line, " ", 2);
2622 xfree(line);
2624 if (!req || !*req)
2625 return EPWMD_COMMAND_SYNTAX;
2627 if ((path = split_input_line(req[0], "\t", 0)) == NULL) {
2628 if ((path = split_input_line(req[0], " ", 0)) == NULL)
2629 return EPWMD_COMMAND_SYNTAX;
2632 content = req[1];
2634 if (!content || !*content) {
2635 rc = EPWMD_COMMAND_SYNTAX;
2636 goto fail;
2639 if (valid_xml_element((xmlChar *)*path) == FALSE) {
2640 rc = EPWMD_INVALID_ELEMENT;
2641 goto fail;
2644 if (valid_element_path(path+1, FALSE) == FALSE) {
2645 rc = EPWMD_INVALID_ELEMENT;
2646 goto fail;
2649 doc = xmlReadDoc((xmlChar *)content, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2651 if (!doc) {
2652 rc = EPWMD_LIBXML_ERROR;
2653 goto fail;
2656 root = xmlDocGetRootElement(doc);
2657 path_orig = g_strdupv(path);
2659 if (!path_orig) {
2660 xmlFreeDoc(doc);
2661 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2662 rc = gpg_error_from_errno(ENOMEM);
2663 goto fail;
2666 if (strv_printf(&path, "%s", (gchar *)root->name) == FALSE) {
2667 g_strfreev(path_orig);
2668 xmlFreeDoc(doc);
2669 rc = gpg_error_from_errno(ENOMEM);
2670 goto fail;
2673 n = find_account(client->doc, &path, &rc, NULL, 0);
2675 if (rc && rc != EPWMD_ELEMENT_NOT_FOUND) {
2676 g_strfreev(path_orig);
2677 xmlFreeDoc(doc);
2678 goto fail;
2680 else if (!rc) {
2681 n = find_elements(client->doc, n->children, path+1, &rc, NULL, NULL, NULL, FALSE, 0, NULL);
2683 if (rc && rc != EPWMD_ELEMENT_NOT_FOUND) {
2684 g_strfreev(path_orig);
2685 xmlFreeDoc(doc);
2686 goto fail;
2688 else if (!rc) {
2689 xmlNodePtr parent = n->parent;
2691 xmlUnlinkNode(n);
2692 xmlFreeNode(n);
2693 n = parent;
2697 g_strfreev(path);
2698 path = path_orig;
2700 if (rc == EPWMD_ELEMENT_NOT_FOUND) {
2701 n = create_element_path(client, &path, &rc);
2703 if (rc) {
2704 xmlFreeDoc(doc);
2705 goto fail;
2709 copy = xmlCopyNode(root, 1);
2710 n = xmlAddChild(n, copy);
2711 xmlFreeDoc(doc);
2713 if (!n)
2714 rc = EPWMD_LIBXML_ERROR;
2716 fail:
2717 g_strfreev(path);
2718 g_strfreev(req);
2719 client->inquire_status = INQUIRE_DONE;
2720 return rc;
2723 static int import_command(assuan_context_t ctx, gchar *line)
2725 gpg_error_t rc;
2726 struct client_s *client = assuan_get_pointer(ctx);
2728 rc = file_modified(client);
2730 if (rc)
2731 return send_error(ctx, rc);
2733 pth_cancel_point();
2734 rc = assuan_inquire_ext(ctx, "IMPORT", 0, import_command_finalize, ctx);
2735 pth_cancel_point();
2737 if (rc)
2738 return send_error(ctx, rc);
2740 /* Don't return with assuan_process_done() here. This is an INQUIRE. */
2741 client->inquire_status = INQUIRE_BUSY;
2742 return 0;
2745 static int lock_command(assuan_context_t ctx, gchar *line)
2747 gpg_error_t rc;
2748 struct client_s *client = assuan_get_pointer(ctx);
2750 rc = file_modified(client);
2752 if (rc)
2753 return send_error(ctx, rc);
2755 rc = lock_file_mutex(client);
2757 if (!rc)
2758 client->is_lock_cmd = TRUE;
2760 return send_error(ctx, rc);
2763 static int unlock_command(assuan_context_t ctx, gchar *line)
2765 struct client_s *client = assuan_get_pointer(ctx);
2766 gpg_error_t rc = file_modified(client);
2768 if (rc)
2769 return send_error(ctx, rc);
2771 unlock_file_mutex(client);
2772 return send_error(ctx, 0);
2775 static int getpid_command(assuan_context_t ctx, gchar *line)
2777 gpg_error_t rc;
2778 gchar buf[32];
2779 pid_t pid = getpid();
2781 print_fmt(buf, sizeof(buf), "%i", pid);
2782 pth_cancel_point();
2783 rc = xfer_data(ctx, buf, strlen(buf));
2784 pth_cancel_point();
2785 return send_error(ctx, rc);
2788 static int version_command(assuan_context_t ctx, gchar *line)
2790 gpg_error_t rc;
2791 gchar buf[32];
2793 print_fmt(buf, sizeof(buf), "%s", PACKAGE_VERSION);
2794 pth_cancel_point();
2795 rc = xfer_data(ctx, buf, strlen(buf));
2796 pth_cancel_point();
2797 return send_error(ctx, rc);
2800 static void bye_notify(assuan_context_t ctx)
2802 struct client_s *cl = assuan_get_pointer(ctx);
2804 /* This will let assuan_process_next() return. */
2805 fcntl(cl->thd->fd, F_SETFL, O_NONBLOCK);
2808 static void reset_notify(assuan_context_t ctx)
2810 struct client_s *cl = assuan_get_pointer(ctx);
2812 if (cl)
2813 cleanup_client(cl);
2816 static gpg_error_t parse_client_option(assuan_context_t ctx, const gchar *line)
2818 gchar name[32] = {0}, value[256] = {0};
2819 struct client_s *cl = assuan_get_pointer(ctx);
2821 if (sscanf(line, " %31[a-zA-Z] = %255c", name, value) != 2)
2822 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_SYNTAX);
2824 if (g_strcasecmp(name, (gchar *)"NAME") == 0) {
2825 pth_attr_t attr = pth_attr_of(pth_self());
2826 gchar buf[41];
2828 if (!strcmp(value, "NULL")) {
2829 pth_attr_set(attr, PTH_ATTR_NAME, NULL);
2830 pth_attr_destroy(attr);
2831 return 0;
2834 print_fmt(buf, sizeof(buf), "%s", value);
2835 pth_attr_set(attr, PTH_ATTR_NAME, buf);
2836 pth_attr_destroy(attr);
2837 #ifdef WITH_PINENTRY
2838 if (cl->pinentry->name)
2839 g_free(cl->pinentry->name);
2841 cl->pinentry->name = g_strdup(buf);
2842 #endif
2843 log_write("OPTION CLIENT %s=%s", name, buf);
2845 else
2846 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_UNKNOWN_OPTION);
2848 return 0;
2851 static void set_option_value(gchar **opt, const gchar *val)
2853 if (opt)
2854 g_free(*opt);
2856 *opt = NULL;
2858 if (val && strcmp(val, "NULL"))
2859 *opt = g_strdup(val);
2862 static int option_handler(assuan_context_t ctx, const gchar *name,
2863 const gchar *value)
2865 struct client_s *client = assuan_get_pointer(ctx);
2867 if (!value || !*value)
2868 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_INV_VALUE);
2870 if (g_strcasecmp(name, (gchar *)"client") == 0)
2871 return parse_client_option(ctx, value);
2873 if (g_strcasecmp(name, (gchar *)"iterations") == 0) {
2874 long n;
2875 gchar *p = NULL;
2877 errno = 0;
2878 n = strtol(value, &p, 10);
2880 if (errno || (p && *p) || n < 0)
2881 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_INV_VALUE);
2883 MUTEX_LOCK(&rcfile_mutex);
2884 g_key_file_set_integer(keyfileh, client->filename ? client->filename : "global", "iterations", (guint)n);
2885 MUTEX_UNLOCK(&rcfile_mutex);
2886 send_status_all(STATUS_CONFIG);
2888 #ifdef WITH_PINENTRY
2889 else if (g_strcasecmp(name, (gchar *)"lc_messages") == 0)
2890 set_option_value(&client->pinentry->lcmessages, value);
2891 else if (g_strcasecmp(name, (gchar *)"lc_ctype") == 0)
2892 set_option_value(&client->pinentry->lcctype, value);
2893 else if (g_strcasecmp(name, (gchar *)"ttyname") == 0)
2894 set_option_value(&client->pinentry->ttyname, value);
2895 else if (g_strcasecmp(name, (gchar *)"ttytype") == 0)
2896 set_option_value(&client->pinentry->ttytype, value);
2897 else if (g_strcasecmp(name, (gchar *)"display") == 0)
2898 set_option_value(&client->pinentry->display, value);
2899 else if (g_strcasecmp(name, (gchar *)"path") == 0)
2900 set_option_value(&client->pinentry->path, value);
2901 else if (g_strcasecmp(name, (gchar *)"title") == 0)
2902 set_option_value(&client->pinentry->title, value);
2903 else if (g_strcasecmp(name, (gchar *)"prompt") == 0)
2904 set_option_value(&client->pinentry->prompt, value);
2905 else if (g_strcasecmp(name, (gchar *)"desc") == 0)
2906 set_option_value(&client->pinentry->desc, value);
2908 * Look at client_thread() to see how this works.
2910 else if (g_strcasecmp(name, (gchar *)"timeout") == 0) {
2911 gchar *p = NULL;
2912 gint n = strtol(value, &p, 10);
2914 if (*p || n < 0)
2915 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_INV_VALUE);
2917 client->pinentry->timeout = n;
2919 else if (g_strcasecmp(name, (gchar *)"pinentry") == 0) {
2920 gchar *p = NULL;
2921 gint n = strtol(value, &p, 10);
2923 if (*p || n < 0 || n > 1)
2924 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_INV_VALUE);
2926 client->pinentry->enable = n == 0 ? FALSE : TRUE;
2928 #endif
2929 else
2930 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_UNKNOWN_OPTION);
2932 log_write("OPTION %s=%s", name, value);
2933 return 0;
2936 gpg_error_t register_commands(assuan_context_t ctx)
2938 static struct {
2939 const gchar *name;
2940 gint (*handler)(assuan_context_t, gchar *line);
2941 } table[] = {
2942 { "OPEN", open_command },
2943 { "SAVE", save_command },
2944 { "LIST", list_command },
2945 { "REALPATH", realpath_command },
2946 { "STORE", store_command },
2947 { "DELETE", delete_command },
2948 { "GET", get_command },
2949 { "ATTR", attr_command },
2950 { "ISCACHED", iscached_command },
2951 { "CLEARCACHE", clearcache_command },
2952 { "CACHETIMEOUT", cachetimeout_command },
2953 { "GETCONFIG", getconfig_command },
2954 { "DUMP", dump_command },
2955 { "XPATH", xpath_command },
2956 { "IMPORT", import_command },
2957 { "LOCK", lock_command },
2958 { "UNLOCK", unlock_command },
2959 { "GETPID", getpid_command },
2960 { "VERSION", version_command },
2961 { "INPUT", NULL },
2962 { "OUTPUT", NULL },
2963 { NULL, NULL }
2965 gint i, rc;
2967 for (i=0; table[i].name; i++) {
2968 rc = assuan_register_command (ctx, table[i].name, table[i].handler);
2970 if (rc)
2971 return rc;
2974 rc = assuan_register_bye_notify(ctx, bye_notify);
2976 if (rc)
2977 return rc;
2979 rc = assuan_register_option_handler(ctx, option_handler);
2981 if (rc)
2982 return rc;
2984 rc = assuan_register_reset_notify(ctx, reset_notify);
2986 if (rc)
2987 return rc;
2989 return assuan_register_post_cmd_notify(ctx, command_finalize);
2992 gpg_error_t try_xml_decrypt(assuan_context_t ctx, guchar *key,
2993 struct client_crypto_s *crypto, gpointer *dst, goffset *dst_len)
2995 goffset insize, len;
2996 struct client_s *client = ctx ? assuan_get_pointer(ctx) : NULL;
2997 guint64 iter = 0, n_iter = 0, iter_progress = 0;
2998 gint zrc = 0;
2999 gulong outsize = 0;
3000 gpg_error_t rc;
3001 gsize fh_size = crypto->fh->v1 ? sizeof(crypto->fh->fh1) : sizeof(crypto->fh->fh2);
3002 guint64 fh_iter = crypto->fh->v1 ? crypto->fh->fh1.iter : crypto->fh->fh2.iter;
3004 lseek(crypto->fh->fd, fh_size, SEEK_SET);
3005 insize = crypto->fh->st.st_size - fh_size;
3006 crypto->iv = gcry_malloc(gcryblocksize);
3008 if (!crypto->iv) {
3009 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
3010 return gpg_error_from_errno(ENOMEM);
3013 /* No encryption iterations. This is a plain (gzipped) file. */
3014 if ((crypto->fh->v1 && fh_iter < 0) || (!crypto->fh->v1 && fh_iter <= 0)) {
3016 * cache_file_count() needs both .used == TRUE and a valid key in
3017 * order for it to count as a used cache entry. Fixes CACHE status
3018 * messages.
3020 memset(key, '!', gcrykeysize);
3023 if (crypto->fh->v1)
3024 memcpy(crypto->iv, crypto->fh->fh1.iv, gcryblocksize);
3025 else
3026 memcpy(crypto->iv, crypto->fh->fh2.iv, gcryblocksize);
3028 crypto->inbuf = gcry_malloc(insize);
3030 if (!crypto->inbuf) {
3031 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
3032 return gpg_error_from_errno(ENOMEM);
3035 crypto->insize = insize;
3036 len = pth_read(crypto->fh->fd, crypto->inbuf, crypto->insize);
3037 pth_cancel_point();
3039 if (len != crypto->insize)
3040 return GPG_ERR_INV_LENGTH;
3042 if ((crypto->fh->v1 && fh_iter < 0) || (!crypto->fh->v1 && fh_iter <= 0))
3043 goto decompress;
3045 if ((rc = gcry_cipher_setiv(crypto->gh, crypto->iv, gcryblocksize))) {
3046 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3047 return rc;
3050 if ((rc = gcry_cipher_setkey(crypto->gh, key, gcrykeysize))) {
3051 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3052 return rc;
3055 iter_progress = (guint64)get_key_file_integer(client && client->filename ?
3056 client->filename : "global", "iteration_progress");
3058 if (iter_progress > 0 && fh_iter >= iter_progress) {
3059 rc = send_status(ctx, STATUS_DECRYPT, "0 %llu", fh_iter);
3060 pth_cancel_point();
3062 if (rc)
3063 return rc;
3066 rc = iterate_crypto_once(client, crypto, STATUS_DECRYPT);
3068 if (rc)
3069 return rc;
3071 crypto->tkey = gcry_malloc(gcrykeysize);
3073 if (!crypto->tkey) {
3074 log_write("%s(%i): %s", __FUNCTION__, __LINE__, strerror(ENOMEM));
3075 return gpg_error_from_errno(ENOMEM);
3078 memcpy(crypto->tkey, key, gcrykeysize);
3079 guchar *tkey = crypto->tkey;
3080 tkey[0] ^= 1;
3082 if ((rc = gcry_cipher_setkey(crypto->gh, crypto->tkey, gcrykeysize))) {
3083 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3084 return rc;
3087 while (iter < (crypto->fh->v1 ? fh_iter : fh_iter-1)) {
3088 if (iter_progress > 0 && iter >= iter_progress) {
3089 if (!(iter % iter_progress)) {
3090 rc = send_status(ctx, STATUS_DECRYPT, "%llu %llu",
3091 ++n_iter * iter_progress, fh_iter);
3092 pth_cancel_point();
3094 if (rc)
3095 return rc;
3099 if ((rc = gcry_cipher_setiv(crypto->gh, crypto->iv, gcryblocksize))) {
3100 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3101 return rc;
3104 rc = iterate_crypto_once(client, crypto, STATUS_DECRYPT);
3106 if (rc) {
3107 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3108 return rc;
3111 iter++;
3114 if (iter_progress && fh_iter >= iter_progress) {
3115 rc = send_status(ctx, STATUS_DECRYPT, "%llu %llu", fh_iter, fh_iter);
3116 pth_cancel_point();
3118 if (rc)
3119 return rc;
3122 decompress:
3123 if (do_decompress(ctx, crypto->inbuf, crypto->insize,
3124 (gpointer *)&crypto->outbuf, &outsize, &zrc) == FALSE) {
3125 if (zrc == Z_MEM_ERROR)
3126 return gpg_error_from_errno(ENOMEM);
3127 else
3128 return EPWMD_BADKEY; // Not a valid gzip header. Must be a bad key.
3131 if (g_strncasecmp(crypto->outbuf, "<?xml version=", 14) != 0) {
3132 gcry_free(crypto->outbuf);
3133 crypto->outbuf = NULL;
3134 return EPWMD_BADKEY;
3137 if (ctx) {
3138 client->xml = crypto->outbuf;
3139 client->len = outsize;
3140 crypto->outbuf = NULL;
3142 else if (dst) {
3143 *dst = crypto->outbuf;
3144 *dst_len = outsize;
3145 crypto->outbuf = NULL;
3148 /* The calling function should free the crypto struct. */
3149 return 0;
3153 * This is called after every Assuan command.
3155 void command_finalize(assuan_context_t ctx, gint rc)
3157 struct client_s *client = assuan_get_pointer(ctx);
3159 if (!client->is_lock_cmd)
3160 unlock_file_mutex(client);