Added the RENAME command to rename a node.
[pwmd.git] / src / commands.c
blob26fca92a31af4eb828d9f6d1c951479fd4dc8d76
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 = (guchar *)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->ver.fh1) : sizeof(fh->ver.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(cleanup_fd_cb, &fd);
382 p = v1 ? (void *)&fh->ver.fh1 : (void *)&fh->ver.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 = init_client_crypto2(client->filename, client->crypto);
417 if (rc) {
418 cleanup_client(client);
419 return send_error(ctx, rc);
422 rc = try_xml_decrypt(ctx, key, client->crypto, NULL, NULL);
424 if (rc) {
425 cleanup_client(client);
426 return send_error(ctx, rc);
429 update_cache:
430 CACHE_LOCK(client->ctx);
432 if (cached == FALSE) {
433 if (cache_update_key(client->md5file, key) == FALSE) {
434 cleanup_client(client);
435 CACHE_UNLOCK;
436 return send_syserror(ctx, ENOMEM);
439 timeout = get_key_file_integer(client->filename, "cache_timeout");
440 cache_reset_timeout(client->md5file, timeout);
442 else
443 cache_set_timeout(client->md5file, -2);
445 CACHE_UNLOCK;
447 done:
448 rc = parse_xml(ctx);
450 if (client->xml) {
451 gcry_free(client->xml);
452 client->xml = NULL;
455 if (!rc) {
456 if (client->new == FALSE)
457 send_status_all(STATUS_CACHE);
459 client->state = STATE_OPEN;
462 if (!rc && client->new == FALSE &&
463 client->crypto->fh->ver.fh2.iter != (guint64)get_key_file_integer(client->filename, "iterations")) {
464 MUTEX_LOCK(&rcfile_mutex);
465 g_key_file_set_integer(keyfileh, client->filename, "iterations",
466 client->crypto->fh->ver.fh2.iter);
467 MUTEX_UNLOCK(&rcfile_mutex);
468 send_status_all(STATUS_CONFIG);
471 cleanup_crypto(&client->crypto);
472 return send_error(ctx, rc);
475 static void req_cleanup(void *arg)
477 if (!arg)
478 return;
480 g_strfreev((gchar **)arg);
483 static int open_command(assuan_context_t ctx, char *line)
485 gboolean cached = FALSE;
486 gpg_error_t rc;
487 struct client_s *client = assuan_get_pointer(ctx);
488 gchar **req;
489 gchar *filename = NULL;
490 guint hashlen = gcry_md_get_algo_dlen(GCRY_MD_SHA256);
492 if ((req = split_input_line(line, " ", 2)) != NULL)
493 filename = req[0];
495 pth_cleanup_push(req_cleanup, req);
497 if (!filename || !*filename) {
498 pth_cleanup_pop(1);
499 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
502 log_write2("ARGS=\"%s\" %s", filename, req[1] ? "<passphrase>" : "");
504 if (valid_filename(filename) == FALSE) {
505 pth_cleanup_pop(1);
506 return send_error(ctx, EPWMD_INVALID_FILENAME);
509 if (client->state == STATE_OPEN)
510 cleanup_client(client);
512 gcry_md_hash_buffer(GCRY_MD_MD5, client->md5file, filename, strlen(filename));
513 CACHE_LOCK(client->ctx);
515 if (cache_has_file(client->md5file) == FALSE) {
516 if (cache_add_file(client->md5file, NULL) == FALSE) {
517 pth_cleanup_pop(1);
518 CACHE_UNLOCK;
519 return send_syserror(ctx, ENOMEM);
523 cache_incr_refcount(client->md5file);
524 CACHE_UNLOCK;
525 rc = lock_file_mutex(client);
527 if (rc) {
528 pth_cleanup_pop(1);
529 return send_error(ctx, rc);
532 client->freed = FALSE;
533 client->crypto = init_client_crypto();
535 if (!client->crypto) {
536 pth_cleanup_pop(1);
537 cleanup_client(client);
538 return send_syserror(ctx, ENOMEM);
541 client->crypto->key = gcry_malloc(hashlen);
543 if (!client->crypto->key) {
544 pth_cleanup_pop(1);
545 log_write("%s(%i): %s", __FUNCTION__, __LINE__,
546 gpg_error_from_errno(ENOMEM));
547 cleanup_client(client);
548 return send_syserror(ctx, ENOMEM);
551 memset(client->crypto->key, 0, hashlen);
552 client->crypto->fh = read_file_header(filename, FALSE, &rc);
554 if (!client->crypto->fh) {
555 if (gpg_err_code_to_errno(rc) != ENOENT) {
556 log_write("%s: %s", filename, pwmd_strerror(rc));
557 pth_cleanup_pop(1);
558 cleanup_client(client);
559 return send_error(ctx, rc);
563 * New files don't need a key.
565 if ((client->xml = new_document()) == NULL) {
566 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
567 pth_cleanup_pop(1);
568 cleanup_client(client);
569 return send_syserror(ctx, ENOMEM);
572 client->len = xmlStrlen(client->xml);
573 client->new = TRUE;
574 client->filename = g_strdup(filename);
576 if (!client->filename) {
577 pth_cleanup_pop(1);
578 cleanup_client(client);
579 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
580 return send_syserror(ctx, ENOMEM);
583 if (req[1] && *req[1])
584 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, req[1],
585 strlen(req[1]));
587 pth_cleanup_pop(1);
588 #ifdef WITH_PINENTRY
589 client->pinentry->filename = g_strdup(client->filename);
591 if (!client->pinentry->filename) {
592 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
593 cleanup_client(client);
594 return send_syserror(ctx, ENOMEM);
596 #endif
597 return open_command_finalize(ctx, client->crypto->key, cached);
599 else
600 client->mtime = client->crypto->fh->st.st_mtime;
602 client->filename = g_strdup(filename);
604 if (!client->filename) {
605 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
606 pth_cleanup_pop(1);
607 cleanup_client(client);
608 return send_syserror(ctx, ENOMEM);
611 #ifdef WITH_PINENTRY
612 client->pinentry->filename = g_strdup(client->filename);
614 if (!client->pinentry->filename) {
615 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
616 pth_cleanup_pop(1);
617 cleanup_client(client);
618 return send_syserror(ctx, ENOMEM);
620 #endif
622 if (client->crypto->fh->ver.fh2.iter <= 0)
623 goto done;
625 CACHE_LOCK(client->ctx);
626 cached = cache_get_key(client->md5file, client->crypto->key);
627 CACHE_UNLOCK;
629 if (cached == FALSE) {
630 gchar *tmp = get_key_file_string(filename, "key_file");
632 if (tmp) {
633 g_free(tmp);
634 pth_cleanup_pop(1);
635 cleanup_client(client);
636 return send_error(ctx, GPG_ERR_WRONG_KEY_USAGE);
640 * No key specified and no matching filename found in the cache. Use
641 * pinentry to retrieve the key. Cannot return assuan_process_done()
642 * here otherwise the command will be interrupted. The event loop in
643 * client_thread() will poll the file descriptor waiting for it to
644 * become ready to read a pinentry_key_s which will contain the
645 * entered key or an error code. It will then call
646 * open_command_finalize() to to finish the command.
648 if (!req[1] || !*req[1]) {
649 #ifdef WITH_PINENTRY
650 gboolean b = get_key_file_boolean(filename, "enable_pinentry");
652 /* From set_pinentry_defaults(). */
653 if (client->pinentry->enable == FALSE ||
654 (client->pinentry->enable == -1 && b == FALSE)) {
655 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, "", 1);
656 goto done;
659 pth_cleanup_pop(1);
660 rc = lock_pin_mutex(client);
662 if (rc) {
663 unlock_pin_mutex(client->pinentry);
664 cleanup_client(client);
665 return send_error(ctx, rc);
668 client->pinentry->which = PINENTRY_OPEN;
669 rc = pinentry_fork(ctx);
671 if (rc) {
672 unlock_pin_mutex(client->pinentry);
673 cleanup_client(client);
674 return send_error(ctx, rc);
677 // Called from pinentry iterate.
678 client->pinentry->cb = open_command_finalize;
679 client->pinentry->status = PINENTRY_INIT;
680 return 0;
681 #else
682 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, "", 1);
683 goto done;
684 #endif
687 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, req[1],
688 strlen(req[1]));
690 else if (req[1] || *req[1]) {
691 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, req[1],
692 strlen(req[1]) ? strlen(req[1]) : 1);
695 done:
696 pth_cleanup_pop(1);
697 return open_command_finalize(ctx, client->crypto->key, cached);
700 gboolean do_compress(assuan_context_t ctx, gint level, gpointer data,
701 gulong size, gpointer *out, gulong *outsize, gint *rc)
703 struct gz_s *gz;
704 gz_header h;
705 gchar buf[17];
706 gint cmd = Z_NO_FLUSH;
708 gz = g_malloc0(sizeof(struct gz_s));
710 if (!gz) {
711 *rc = gpg_error_from_errno(ENOMEM);
712 return FALSE;
715 pth_cleanup_push(gz_cleanup, &gz);
716 gz->which = STATUS_COMPRESS;
717 gz->z.zalloc = z_alloc;
718 gz->z.zfree = z_free;
719 gz->z.next_in = data;
720 gz->z.avail_in = size < zlib_bufsize ? (uInt)size : (uInt)zlib_bufsize;
721 gz->z.avail_out = (uInt)zlib_bufsize;
722 gz->z.next_out = gz->out = gcry_malloc(zlib_bufsize);
724 if (!gz->out) {
725 log_write("%s(%i): %s", __FUNCTION__, __LINE__, strerror(ENOMEM));
726 *rc = Z_MEM_ERROR;
727 pth_cleanup_pop(1);
728 return FALSE;
731 *rc = deflateInit2(&gz->z, level, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY);
733 if (*rc != Z_OK) {
734 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
735 pth_cleanup_pop(1);
736 return FALSE;
739 /* Rather than store the size of the uncompressed data in the file header,
740 * store it in the comment field of the gzip header. Don't give anyone too
741 * much information. Not sure why really, but it seems the right way. :)
743 memset(&h, 0, sizeof(gz_header));
744 g_snprintf(buf, sizeof(buf), "%li", size);
745 h.comment = (guchar *)buf;
746 *rc = deflateSetHeader(&gz->z, &h);
748 if (*rc != Z_OK) {
749 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
750 pth_cleanup_pop(1);
751 return FALSE;
754 do {
755 gpointer p;
757 *rc = deflate(&gz->z, cmd);
759 switch (*rc) {
760 case Z_OK:
761 break;
762 case Z_BUF_ERROR:
763 if (!gz->z.avail_out) {
764 p = gcry_realloc(gz->out, gz->z.total_out + zlib_bufsize);
766 if (!p) {
767 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
768 *rc = Z_MEM_ERROR;
769 goto fail;
772 gz->out = p;
773 gz->z.next_out = (guchar *)gz->out + gz->z.total_out;
774 gz->z.avail_out = zlib_bufsize;
777 if (!gz->z.avail_in && gz->z.total_in < size) {
778 if (gz->z.total_in + zlib_bufsize > size)
779 gz->z.avail_in = size - gz->z.total_in;
780 else
781 gz->z.avail_in = zlib_bufsize;
783 *rc = send_status(ctx, STATUS_COMPRESS, "%li %li",
784 gz->z.total_in, size);
786 if (*rc)
787 goto fail;
790 if (gz->z.total_in >= size)
791 cmd = Z_FINISH;
793 break;
794 case Z_STREAM_END:
795 break;
796 default:
797 goto fail;
799 } while (*rc != Z_STREAM_END);
801 *rc = send_status(ctx, STATUS_COMPRESS, "%li %li", gz->z.total_in, size);
803 if (*rc)
804 goto fail;
806 *out = gz->out;
807 *outsize = gz->z.total_out;
808 *rc = 0;
809 gz->done = TRUE;
810 pth_cleanup_pop(1);
811 return TRUE;
813 fail:
814 log_write("%s(%i): %s", __FUNCTION__, __LINE__, gz->z.msg);
815 pth_cleanup_pop(1);
816 return FALSE;
819 #define CRYPTO_BLOCKSIZE(c) (c->blocksize * 1024)
821 static gpg_error_t iterate_crypto_once(struct client_s *client,
822 struct client_crypto_s *crypto, status_msg_t which)
824 gpg_error_t rc = 0;
825 goffset len = CRYPTO_BLOCKSIZE(crypto);
826 gpointer p = gcry_malloc(len);
827 goffset total = 0;
828 gpointer inbuf;
830 if (!p)
831 return gpg_err_code_from_errno(ENOMEM);
833 if (crypto->insize < CRYPTO_BLOCKSIZE(crypto))
834 len = crypto->insize;
836 pth_cleanup_push(gcry_free, p);
838 for (;;) {
839 inbuf = (guchar *)crypto->inbuf + total;
840 guchar *tmp;
842 if (len + total > crypto->insize)
843 len = crypto->blocksize;
845 if (which == STATUS_ENCRYPT)
846 rc = gcry_cipher_encrypt(crypto->gh, p, len, inbuf, len);
847 else
848 rc = gcry_cipher_decrypt(crypto->gh, p, len, inbuf, len);
850 if (rc)
851 goto done;
853 tmp = (guchar *)crypto->inbuf + total;
854 memmove(tmp, p, len);
855 total += len;
857 if (total >= crypto->insize)
858 break;
860 pth_cancel_point();
863 done:
864 pth_cleanup_pop(1);
865 return rc;
868 /* The crypto struct must be setup for iterations and .key. */
869 gpg_error_t do_xml_encrypt(struct client_s *client,
870 struct client_crypto_s *crypto, const gchar *filename)
872 goffset len = crypto->insize;
873 gpointer inbuf;
874 gchar *p;
875 gpg_error_t rc;
876 guint64 iter_progress = 0, n_iter = 0, xiter = 0;
877 gchar tmp[FILENAME_MAX];
878 struct stat st;
879 mode_t mode = 0;
880 guint hashlen = gcry_md_get_algo_dlen(GCRY_MD_SHA256);
882 if (!crypto->fh->ver.fh2.iter) {
884 * cache_file_count() needs both .used == TRUE and a valid key in
885 * order for it to count as a used cache entry. Fixes CACHE status
886 * messages.
888 memset(crypto->key, '!', hashlen);
889 goto write_file;
893 * Resize the existing xml buffer to the block size required by gcrypt
894 * rather than duplicating it and wasting memory.
896 len = (crypto->insize / crypto->blocksize) * crypto->blocksize;
898 if (crypto->insize % crypto->blocksize)
899 len += crypto->blocksize;
901 inbuf = gcry_realloc(crypto->inbuf, len);
903 if (!inbuf) {
904 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
905 return gpg_error_from_errno(ENOMEM);
908 crypto->inbuf = inbuf;
909 crypto->insize = len;
910 gcry_create_nonce(crypto->fh->ver.fh2.iv, crypto->blocksize);
911 crypto->tkey = gcry_malloc(hashlen);
913 if (!crypto->tkey) {
914 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
915 return gpg_error_from_errno(ENOMEM);
918 memcpy(crypto->tkey, crypto->key, hashlen);
919 guchar *tkey = crypto->tkey;
920 tkey[0] ^= 1;
922 if ((rc = gcry_cipher_setkey(crypto->gh, crypto->tkey, crypto->keysize))) {
923 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
924 return rc;
927 iter_progress = (guint64)get_key_file_integer(
928 client ? client->filename : "global", "iteration_progress");
930 if (iter_progress && crypto->fh->ver.fh2.iter >= iter_progress) {
931 rc = send_status(client ? client->ctx : NULL, STATUS_ENCRYPT,
932 "0 %llu", crypto->fh->ver.fh2.iter);
934 if (rc)
935 return rc;
938 while (xiter < crypto->fh->ver.fh2.iter-1) {
939 if (iter_progress > 0 && xiter >= iter_progress) {
940 if (!(xiter % iter_progress)) {
941 rc = send_status(client ? client->ctx : NULL, STATUS_ENCRYPT,
942 "%llu %llu", ++n_iter * iter_progress,
943 crypto->fh->ver.fh2.iter);
945 if (rc)
946 return rc;
950 if ((rc = gcry_cipher_setiv(crypto->gh, crypto->fh->ver.fh2.iv,
951 crypto->blocksize))) {
952 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
953 return rc;
956 rc = iterate_crypto_once(client, crypto, STATUS_ENCRYPT);
958 if (rc) {
959 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
960 return rc;
963 xiter++;
966 if ((rc = gcry_cipher_setiv(crypto->gh, crypto->fh->ver.fh2.iv,
967 crypto->blocksize))) {
968 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
969 return rc;
972 if ((rc = gcry_cipher_setkey(crypto->gh, crypto->key, crypto->keysize))) {
973 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
974 return rc;
977 rc = iterate_crypto_once(client, crypto, STATUS_ENCRYPT);
979 if (rc)
980 return rc;
982 if (iter_progress && crypto->fh->ver.fh2.iter >= iter_progress) {
983 rc = send_status(client ? client->ctx : NULL, STATUS_ENCRYPT,
984 "%llu %llu", crypto->fh->ver.fh2.iter, crypto->fh->ver.fh2.iter);
986 if (rc)
987 return rc;
990 write_file:
991 tmp[0] = 0;
993 if (filename) {
994 if (!client && !g_ascii_strcasecmp(filename, "-")) {
995 crypto->fh->fd = STDOUT_FILENO;
996 goto do_write_file;
999 if (lstat(filename, &st) == 0) {
1000 mode = st.st_mode & (S_IRWXU|S_IRWXG|S_IRWXO);
1002 if (!(mode & S_IWUSR))
1003 return gpg_error_from_errno(EACCES);
1005 else if (errno != ENOENT)
1006 return gpg_error_from_errno(errno);
1008 g_snprintf(tmp, sizeof(tmp), "%s.XXXXXX", filename);
1009 crypto->fh->fd = mkstemp(tmp);
1011 if (crypto->fh->fd == -1) {
1012 rc = errno;
1013 p = strrchr(tmp, '/');
1014 p++;
1015 log_write("%s: %s", p, strerror(rc));
1016 return gpg_error_from_errno(rc);
1019 pth_cleanup_push(cleanup_unlink_cb, tmp);
1021 else
1023 * xml_import() or convert_file() from command line.
1025 crypto->fh->fd = STDOUT_FILENO;
1027 do_write_file:
1028 crypto->fh->ver.fh2.magic[0] = '\177';
1029 crypto->fh->ver.fh2.magic[1] = 'P';
1030 crypto->fh->ver.fh2.magic[2] = 'W';
1031 crypto->fh->ver.fh2.magic[3] = 'M';
1032 crypto->fh->ver.fh2.magic[4] = 'D';
1033 crypto->fh->ver.fh2.version = VERSION_HEX;
1034 len = pth_write(crypto->fh->fd, &crypto->fh->ver.fh2, sizeof(crypto->fh->ver.fh2));
1036 if (len != sizeof(crypto->fh->ver.fh2)) {
1037 len = errno;
1039 if (tmp[0])
1040 pth_cleanup_pop(1);
1042 return gpg_error_from_errno(len);
1045 len = pth_write(crypto->fh->fd, crypto->inbuf, crypto->insize);
1047 if (len != crypto->insize) {
1048 len = errno;
1050 if (tmp[0])
1051 pth_cleanup_pop(1);
1053 return gpg_error_from_errno(len);
1056 if (fsync(crypto->fh->fd) == -1) {
1057 len = errno;
1059 if (tmp[0])
1060 pth_cleanup_pop(1);
1062 return gpg_error_from_errno(len);
1065 if (tmp[0]) {
1066 #ifdef WITH_LIBACL
1067 acl_t acl;
1068 #endif
1069 if (mode && get_key_file_boolean(filename, "backup") == TRUE) {
1070 gchar tmp2[FILENAME_MAX];
1072 g_snprintf(tmp2, sizeof(tmp2), "%s.backup", filename);
1073 #ifdef WITH_LIBACL
1074 acl = acl_get_file(filename, ACL_TYPE_ACCESS);
1076 if (!acl)
1077 log_write("ACL: %s: %s", filename, strerror(errno));
1078 #endif
1080 if (rename(filename, tmp2) == -1) {
1081 len = errno;
1082 pth_cleanup_pop(1);
1083 #ifdef WITH_LIBACL
1084 if (acl)
1085 acl_free(acl);
1086 #endif
1087 return gpg_error_from_errno(len);
1090 #ifdef WITH_LIBACL
1091 else {
1092 acl = acl_get_file(".", ACL_TYPE_DEFAULT);
1094 if (!acl)
1095 log_write("ACL: %s: %s", filename, strerror(errno));
1097 #endif
1099 if (rename(tmp, filename) == -1) {
1100 len = errno;
1101 pth_cleanup_pop(1);
1102 #ifdef WITH_LIBACL
1103 if (acl)
1104 acl_free(acl);
1105 #endif
1106 return gpg_error_from_errno(len);
1109 pth_cleanup_pop(0);
1111 if (mode)
1112 chmod(filename, mode);
1114 #ifdef WITH_LIBACL
1115 if (acl && acl_set_file(filename, ACL_TYPE_ACCESS, acl))
1116 log_write("ACL: %s: %s", filename, strerror(errno));
1118 if (acl)
1119 acl_free(acl);
1120 #endif
1123 if (client && lstat(filename, &st) == 0)
1124 client->mtime = st.st_mtime;
1126 return 0;
1129 gpg_error_t update_save_flags(const gchar *filename,
1130 struct client_crypto_s *crypto)
1132 gpg_error_t rc;
1133 guint64 iter;
1135 /* New file? */
1136 if (!crypto->fh) {
1137 crypto->fh = g_malloc0(sizeof(file_header_internal_t));
1139 if (!crypto->fh)
1140 return GPG_ERR_ENOMEM;
1143 rc = init_client_crypto2(filename, crypto);
1145 if (rc)
1146 return rc;
1148 iter = get_key_file_integer(filename, "iterations");
1149 crypto->fh->ver.fh2.iter = iter < 0 ? 0 : iter;
1150 return 0;
1153 static gpg_error_t save_command_finalize(assuan_context_t ctx, guchar *key,
1154 gboolean cached)
1156 struct client_s *client = assuan_get_pointer(ctx);
1157 gpointer xmlbuf;
1158 gulong len, outsize = 0;
1159 guint iter;
1160 gint timeout;
1161 gpointer outbuf;
1162 gint zrc;
1163 gpg_error_t rc;
1165 if (client->crypto->key && client->crypto->key != key)
1166 gcry_free(client->crypto->key);
1168 client->crypto->key = key;
1169 rc = update_timestamp(client->doc);
1171 if (rc)
1172 return send_error(ctx, rc);
1174 xmlDocDumpFormatMemory(client->doc, (xmlChar **)&xmlbuf, (gint *)&len, 0);
1175 pth_cleanup_push(xmlFree, xmlbuf);
1176 iter = (guint)get_key_file_integer(client->filename, "compression_level");
1178 if (iter < 0)
1179 iter = 0;
1181 if (do_compress(ctx, (gint)iter, xmlbuf, len, &outbuf, &outsize, &zrc)
1182 == FALSE) {
1183 pth_cleanup_pop(1);
1184 cleanup_crypto(&client->crypto);
1186 if (zrc == Z_MEM_ERROR)
1187 return send_syserror(ctx, ENOMEM);
1188 else
1189 return send_error(ctx, GPG_ERR_COMPR_ALGO);
1191 else {
1192 pth_cleanup_pop(1);
1193 xmlbuf = outbuf;
1194 len = outsize;
1197 client->crypto->inbuf = xmlbuf;
1198 client->crypto->insize = len;
1199 rc = update_save_flags(client->filename, client->crypto);
1201 if (rc) {
1202 cleanup_crypto(&client->crypto);
1203 log_write("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror(rc));
1204 return send_error(ctx, rc);
1207 rc = do_xml_encrypt(client, client->crypto, client->filename);
1209 if (rc) {
1210 cleanup_crypto(&client->crypto);
1211 return send_error(ctx, rc);
1214 timeout = get_key_file_integer(client->filename, "cache_timeout");
1215 CACHE_LOCK(client->ctx);
1217 if (cached) {
1218 cache_reset_timeout(client->md5file, timeout);
1219 CACHE_UNLOCK;
1221 if (client->new == TRUE)
1222 send_status_all(STATUS_CACHE);
1224 client->new = FALSE;
1225 cleanup_crypto(&client->crypto);
1226 return send_error(ctx, 0);
1229 if (cache_update_key(client->md5file, client->crypto->key) == FALSE) {
1230 CACHE_UNLOCK;
1231 cleanup_crypto(&client->crypto);
1232 return send_syserror(ctx, ENOMEM);
1235 client->new = FALSE;
1236 cache_reset_timeout(client->md5file, timeout);
1237 CACHE_UNLOCK;
1238 send_status_all(STATUS_CACHE);
1239 cleanup_crypto(&client->crypto);
1240 return send_error(ctx, 0);
1243 static int save_command(assuan_context_t ctx, char *line)
1245 gboolean cached = FALSE;
1246 struct stat st;
1247 struct client_s *client = assuan_get_pointer(ctx);
1248 guint hashlen = gcry_md_get_algo_dlen(GCRY_MD_SHA256);
1250 if (line && *line)
1251 log_write2("ARGS=%s", "<passphrase>");
1253 if (lstat(client->filename, &st) == -1 && errno != ENOENT)
1254 return send_syserror(ctx, errno);
1256 if (errno != ENOENT && !S_ISREG(st.st_mode)) {
1257 log_write("%s: %s", client->filename, pwmd_strerror(GPG_ERR_ENOANO));
1258 return send_error(ctx, GPG_ERR_ENOANO);
1261 CACHE_LOCK(ctx);
1262 cached = cache_iscached(client->md5file);
1263 CACHE_UNLOCK;
1266 * If a cache entry doesn't exist for this file and the file has a
1267 * "key_file" or "key" parameter, then it's an error. The reason is that
1268 * cache expiration would be useless.
1270 if (cached == FALSE) {
1271 gchar *tmp = get_key_file_string(client->filename, "key_file");
1273 if (tmp) {
1274 g_free(tmp);
1275 return send_error(ctx, GPG_ERR_WRONG_KEY_USAGE);
1279 cached = FALSE;
1281 /* New file? */
1282 if (!client->crypto) {
1283 client->crypto = init_client_crypto();
1285 if (!client->crypto) {
1286 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1287 return send_syserror(ctx, ENOMEM);
1291 client->crypto->key = gcry_malloc(hashlen);
1293 if (!client->crypto->key) {
1294 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1295 cleanup_crypto(&client->crypto);
1296 return send_syserror(ctx, ENOMEM);
1299 memset(client->crypto->key, '!', hashlen);
1301 if (get_key_file_integer(client->filename, "iterations") <= 0)
1302 goto done;
1304 if (!line || !*line) {
1305 client->crypto->tkey = gcry_malloc(hashlen);
1307 if (!client->crypto->tkey) {
1308 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1309 cleanup_crypto(&client->crypto);
1310 return send_syserror(ctx, ENOMEM);
1313 memset(client->crypto->tkey, '!', hashlen);
1314 CACHE_LOCK(ctx);
1316 if (cache_get_key(client->md5file, client->crypto->key) == FALSE ||
1317 !memcmp(client->crypto->key, client->crypto->tkey, hashlen)) {
1318 CACHE_UNLOCK;
1320 #ifdef WITH_PINENTRY
1321 gpg_error_t rc;
1323 if (client->pinentry->enable == FALSE ||
1324 get_key_file_boolean(client->filename, "enable_pinentry") == FALSE) {
1325 /* Empty keys are allowed. */
1326 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, "", 1);
1327 goto done;
1330 lock_pin_mutex(client);
1331 client->pinentry->which = PINENTRY_SAVE;
1332 rc = pinentry_fork(ctx);
1334 if (rc) {
1335 unlock_pin_mutex(client->pinentry);
1336 return send_error(ctx, rc);
1339 client->pinentry->cb = save_command_finalize;
1340 client->pinentry->status = PINENTRY_INIT;
1341 return 0;
1342 #else
1343 /* Empty keys are allowed. */
1344 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, "", 1);
1345 goto done;
1346 #endif
1348 else {
1349 CACHE_UNLOCK;
1350 cached = TRUE;
1353 else
1354 gcry_md_hash_buffer(GCRY_MD_SHA256, client->crypto->key, line,
1355 strlen(line));
1357 done:
1358 return save_command_finalize(ctx, client->crypto->key, cached);
1361 static int delete_command(assuan_context_t ctx, char *line)
1363 struct client_s *client = assuan_get_pointer(ctx);
1364 gchar **req;
1365 gpg_error_t rc;
1366 xmlNodePtr n;
1368 log_write2("ARGS=\"%s\"", line);
1370 if (strchr(line, '\t'))
1371 req = split_input_line(line, "\t", -1);
1372 else
1373 req = split_input_line(line, " ", -1);
1375 if (!req || !*req)
1376 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
1378 n = find_account(client->doc, &req, &rc, NULL, 0);
1380 if (!n) {
1381 g_strfreev(req);
1382 return send_error(ctx, rc);
1386 * No sub-node defined. Remove the entire node (account).
1388 if (!req[1]) {
1389 if (n) {
1390 xmlUnlinkNode(n);
1391 xmlFreeNode(n);
1394 g_strfreev(req);
1395 return send_error(ctx, 0);
1398 n = find_elements(client->doc, n->children, req+1, &rc, NULL, NULL, NULL, FALSE, 0, NULL);
1399 g_strfreev(req);
1401 if (!n)
1402 return send_error(ctx, rc);
1404 if (n) {
1405 xmlUnlinkNode(n);
1406 xmlFreeNode(n);
1409 return send_error(ctx, 0);
1413 * Don't return with assuan_process_done() here. This has been called from
1414 * assuan_process_next() and the command should be finished in
1415 * client_thread().
1417 static int store_command_finalize(gpointer data, gint assuan_rc, guchar *line,
1418 gsize len)
1420 assuan_context_t ctx = data;
1421 struct client_s *client = assuan_get_pointer(ctx);
1422 gchar **req;
1423 xmlNodePtr n;
1424 gpg_error_t rc = file_modified(client);
1426 if (assuan_rc || rc) {
1427 if (line)
1428 xfree(line);
1429 return assuan_rc ? assuan_rc : rc;
1432 req = split_input_line((gchar *)line, "\t", 0);
1433 xfree(line);
1435 if (!req || !*req)
1436 return EPWMD_COMMAND_SYNTAX;
1438 if (valid_xml_element((xmlChar *)*req) == FALSE) {
1439 g_strfreev(req);
1440 return EPWMD_INVALID_ELEMENT;
1443 if (valid_element_path(req+1, TRUE) == FALSE) {
1444 g_strfreev(req);
1445 return EPWMD_INVALID_ELEMENT;
1448 again:
1449 n = find_account(client->doc, &req, &rc, NULL, 0);
1451 if (rc && rc == EPWMD_ELEMENT_NOT_FOUND) {
1452 rc = new_account(client->doc, *req);
1454 if (rc) {
1455 g_strfreev(req);
1456 return rc;
1459 goto again;
1462 if (!n) {
1463 g_strfreev(req);
1464 return rc;
1467 if (req[1]) {
1468 if (!n->children)
1469 create_elements_cb(n, req+1, &rc, NULL);
1470 else
1471 find_elements(client->doc, n->children, req+1, &rc,
1472 NULL, NULL, create_elements_cb, FALSE, 0, NULL);
1475 g_strfreev(req);
1476 client->inquire_status = INQUIRE_DONE;
1477 return rc;
1480 static int store_command(assuan_context_t ctx, char *line)
1482 struct client_s *client = assuan_get_pointer(ctx);
1483 gpg_error_t rc;
1485 rc = assuan_inquire_ext(ctx, "STORE", 0, store_command_finalize, ctx);
1487 if (rc)
1488 return send_error(ctx, rc);
1490 /* Don't return with assuan_process_done() here. This is an INQUIRE. */
1491 client->inquire_status = INQUIRE_BUSY;
1492 return 0;
1495 static void *send_data_cb(void *arg)
1497 struct assuan_cmd_s *data = arg;
1498 gint old;
1499 gpg_error_t rc;
1501 pth_cancel_state(PTH_CANCEL_ENABLE|PTH_CANCEL_ASYNCHRONOUS, &old);
1502 rc = assuan_send_data(data->ctx, data->line, data->line_len);
1503 pth_cancel_state(old, NULL);
1504 pth_exit((void *)rc);
1505 return NULL;
1508 /* For every assuan command that needs to be sent to the client, a timeout is
1509 * needed to determine if the client lost the connection. The timeout is the
1510 * same as the "keepalive" configuration parameter or a default if unset.
1512 gpg_error_t do_assuan_command(assuan_context_t ctx,
1513 void *(*cb)(void *data), void *data)
1515 pth_attr_t attr = pth_attr_new();
1516 pth_t tid;
1517 gint n;
1518 gint to = get_key_file_integer("global", "keepalive");
1519 pth_event_t ev, tev;
1520 pth_status_t st;
1521 gpg_error_t rc;
1523 pth_attr_init(attr);
1524 pth_attr_set(attr, PTH_ATTR_JOINABLE, TRUE);
1525 tid = pth_spawn(attr, cb, data);
1526 n = errno;
1527 pth_attr_destroy(attr);
1529 if (!tid) {
1530 log_write("%s(%i): pth_spawn(): %s", __FILE__, __LINE__,
1531 _gpg_strerror(gpg_error_from_errno(n)));
1532 return gpg_error_from_errno(n);
1535 pth_cleanup_push(cleanup_cancel_cb, tid);
1536 to = to <= 0 ? DEFAULT_KEEPALIVE_TO : to;
1537 ev = pth_event(PTH_EVENT_TID|PTH_UNTIL_TID_DEAD, tid);
1538 tev = pth_event(PTH_EVENT_TIME, pth_timeout(to, 0));
1539 ev = pth_event_concat(ev, tev, NULL);
1540 pth_cleanup_push(cleanup_ev_cb, ev);
1541 pth_yield(tid);
1542 pth_wait(ev);
1543 st = pth_event_status(ev);
1545 if (st == PTH_STATUS_FAILED) {
1546 pth_cancel(tid);
1547 rc = GPG_ERR_ASS_WRITE_ERROR;
1549 else if (st == PTH_STATUS_OCCURRED)
1550 pth_join(tid, (void **)&rc);
1551 else {
1552 st = pth_event_status(tev);
1554 if (st == PTH_STATUS_OCCURRED) {
1555 pth_cancel(tid);
1556 rc = GPG_ERR_ASS_WRITE_ERROR;
1560 pth_cleanup_pop(1);
1561 pth_cleanup_pop(0);
1562 return rc;
1565 static gpg_error_t xfer_data(assuan_context_t ctx, const gchar *line,
1566 gint total)
1568 int to_send;
1569 int sent = 0;
1570 gpg_error_t rc;
1571 struct assuan_cmd_s data;
1572 int progress = get_key_file_integer("global", "xfer_progress");
1573 int flush = 0;
1575 progress = progress>0 ? (progress/ASSUAN_LINELENGTH)*ASSUAN_LINELENGTH : 0;
1576 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1577 data.ctx = ctx;
1578 rc = send_status(ctx, STATUS_XFER, "%li %li", sent, total);
1580 if (rc)
1581 return rc;
1583 again:
1584 do {
1585 if (sent + to_send > total)
1586 to_send = total - sent;
1588 data.line = flush ? NULL : (gchar *)line+sent;
1589 data.line_len = flush ? 0 : to_send;
1590 rc = do_assuan_command(ctx, send_data_cb, &data);
1592 if (!rc) {
1593 sent += flush ? 0 : to_send;
1595 if ((progress && !(sent % progress) && sent != total) ||
1596 (sent == total && flush))
1597 rc = send_status(ctx, STATUS_XFER, "%li %li", sent, total);
1599 if (!flush && !rc && sent == total) {
1600 flush = 1;
1601 goto again;
1604 } while (!rc && sent < total);
1606 return rc;
1609 static int get_command(assuan_context_t ctx, char *line)
1611 struct client_s *client = assuan_get_pointer(ctx);
1612 gchar **req;
1613 gpg_error_t rc;
1614 xmlNodePtr n;
1616 log_write2("ARGS=\"%s\"", line);
1617 req = split_input_line(line, "\t", -1);
1619 if (!req || !*req) {
1620 g_strfreev(req);
1621 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
1624 n = find_account(client->doc, &req, &rc, NULL, 0);
1626 if (!n) {
1627 g_strfreev(req);
1628 return send_error(ctx, rc);
1631 if (req[1])
1632 n = find_elements(client->doc, n->children, req+1, &rc, NULL, NULL, NULL, FALSE, 0, NULL);
1634 g_strfreev(req);
1636 if (rc)
1637 return send_error(ctx, rc);
1639 if (!n || !n->children)
1640 return send_error(ctx, EPWMD_EMPTY_ELEMENT);
1642 n = find_text_node(n->children);
1644 if (!n || !n->content || !*n->content)
1645 return send_error(ctx, EPWMD_EMPTY_ELEMENT);
1647 rc = xfer_data(ctx, (gchar *)n->content, xmlStrlen(n->content));
1648 return send_error(ctx, rc);
1651 static xmlNodePtr realpath_elements_cb(xmlNodePtr node, gchar **target,
1652 gpg_error_t *rc, gchar **req_orig, void *data)
1654 gchar *path = *(gchar **)data;
1655 gchar *tmp = NULL, *result;
1657 if (path) {
1658 g_free(path);
1659 *(gchar **)data = NULL;
1662 path = g_strjoinv("\t", target);
1664 if (!path) {
1665 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1666 *rc = gpg_error_from_errno(ENOMEM);
1667 return NULL;
1670 if (req_orig) {
1671 tmp = g_strjoinv("\t", req_orig);
1673 if (!tmp) {
1674 g_free(path);
1675 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1676 *rc = gpg_error_from_errno(ENOMEM);
1677 return NULL;
1681 if (tmp && *tmp)
1682 result = g_strdup_printf("%s\t%s", path, tmp);
1683 else
1684 result = g_strdup(path);
1686 if (!result) {
1687 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1688 *rc = gpg_error_from_errno(ENOMEM);
1689 g_free(path);
1690 g_free(tmp);
1691 return NULL;
1694 g_free(path);
1695 g_free(tmp);
1696 *(gchar **)data = result;
1697 return node;
1700 static void list_command_cleanup1(void *arg);
1701 static int realpath_command(assuan_context_t ctx, char *line)
1703 gpg_error_t rc;
1704 struct client_s *client = assuan_get_pointer(ctx);
1705 gchar **req;
1706 gchar *t;
1707 gint i;
1708 xmlNodePtr n;
1709 GString *string;
1710 gchar *rp = NULL;
1712 log_write2("ARGS=\"%s\"", line);
1714 if (strchr(line, '\t') != NULL) {
1715 if ((req = split_input_line(line, "\t", 0)) == NULL)
1716 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
1718 else {
1719 if ((req = split_input_line(line, " ", 0)) == NULL)
1720 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
1723 n = find_account(client->doc, &req, &rc, NULL, 0);
1725 if (!n) {
1726 g_strfreev(req);
1727 return send_error(ctx, rc);
1730 rp = g_strjoinv("\t", req);
1732 if (!rp) {
1733 g_strfreev(req);
1734 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1735 return send_syserror(ctx, ENOMEM);
1738 if (req[1]) {
1739 n = find_elements(client->doc, n->children, req+1, &rc,
1740 NULL, realpath_elements_cb, NULL, FALSE, 0, &rp);
1742 if (!n) {
1743 g_free(rp);
1744 g_strfreev(req);
1745 return send_error(ctx, rc);
1749 string = g_string_new(rp);
1750 g_free(rp);
1751 g_strfreev(req);
1753 if (!string) {
1754 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1755 return send_syserror(ctx, ENOMEM);
1758 again:
1759 for (i = 0, t = string->str + i; *t; t++, i++) {
1760 if ((!i && *t != '!') || (*t == '\t' && *(t+1) && *(t+1) != '!')) {
1761 string = g_string_insert_c(string, !i ? i++ : ++i, '!');
1762 goto again;
1766 pth_cleanup_push(list_command_cleanup1, string);
1767 rc = xfer_data(ctx, string->str, string->len);
1768 pth_cleanup_pop(1);
1769 return send_error(ctx, rc);
1772 static void list_command_cleanup1(void *arg)
1774 g_string_free((GString *)arg, TRUE);
1777 static void list_command_cleanup2(void *arg)
1779 struct element_list_s *elements = arg;
1781 if (elements) {
1782 gint total = g_slist_length(elements->list);
1783 gint i;
1785 for (i = 0; i < total; i++) {
1786 gchar *tmp = g_slist_nth_data(elements->list, i);
1787 g_free(tmp);
1790 g_slist_free(elements->list);
1792 if (elements->prefix)
1793 g_free(elements->prefix);
1795 g_free(elements);
1799 static int list_command(assuan_context_t ctx, char *line)
1801 struct client_s *client = assuan_get_pointer(ctx);
1802 gpg_error_t rc;
1803 struct element_list_s *elements = NULL;
1804 gchar *tmp;
1806 if (disable_list_and_dump == TRUE)
1807 return send_error(ctx, GPG_ERR_NOT_IMPLEMENTED);
1809 log_write2("ARGS=\"%s\"", line);
1811 if (!*line) {
1812 GString *str;
1814 rc = list_accounts(client->doc, &str);
1816 if (rc)
1817 return send_error(ctx, rc);
1819 pth_cleanup_push(list_command_cleanup1, str);
1820 rc = xfer_data(ctx, str->str, str->len);
1821 pth_cleanup_pop(1);
1822 return send_error(ctx, rc);
1825 elements = g_malloc0(sizeof(struct element_list_s));
1827 if (!elements) {
1828 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1829 rc = gpg_err_code_from_errno(ENOMEM);
1830 goto fail;
1833 pth_cleanup_push(list_command_cleanup2, elements);
1834 rc = create_path_list(client->doc, elements, line);
1836 if (rc)
1837 goto fail;
1839 if (elements) {
1840 gint total = g_slist_length(elements->list);
1841 gint i;
1842 GString *str;
1844 if (!total) {
1845 rc = EPWMD_EMPTY_ELEMENT;
1846 goto fail;
1849 str = g_string_new(NULL);
1851 if (!str) {
1852 rc = gpg_err_code_from_errno(ENOMEM);
1853 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1854 goto fail;
1857 for (i = 0; i < total; i++) {
1858 tmp = g_slist_nth_data(elements->list, i);
1859 g_string_append_printf(str, "%s%s", tmp, i+1 == total ? "" : "\n");
1862 pth_cleanup_push(list_command_cleanup1, str);
1863 rc = xfer_data(ctx, str->str, str->len);
1864 pth_cleanup_pop(1);
1866 else
1867 rc = EPWMD_EMPTY_ELEMENT;
1869 fail:
1870 pth_cleanup_pop(1);
1871 return send_error(ctx, rc);
1875 * req[0] - element path
1877 static int attribute_list(assuan_context_t ctx, gchar **req)
1879 struct client_s *client = assuan_get_pointer(ctx);
1880 gchar **attrlist = NULL;
1881 gint i = 0;
1882 gchar **path = NULL;
1883 xmlAttrPtr a;
1884 xmlNodePtr n, an;
1885 gchar *line;
1886 gpg_error_t rc;
1888 if (!req || !req[0])
1889 return EPWMD_COMMAND_SYNTAX;
1891 if ((path = split_input_line(req[0], "\t", 0)) == NULL) {
1893 * The first argument may be only an account.
1895 if ((path = split_input_line(req[0], " ", 0)) == NULL)
1896 return EPWMD_COMMAND_SYNTAX;
1899 n = find_account(client->doc, &path, &rc, NULL, 0);
1901 if (!n) {
1902 g_strfreev(path);
1903 return rc;
1906 if (path[1]) {
1907 n = find_elements(client->doc, n->children, path+1, &rc,
1908 NULL, NULL, NULL, FALSE, 0, NULL);
1910 if (!n) {
1911 g_strfreev(path);
1912 return rc;
1916 g_strfreev(path);
1918 for (a = n->properties; a; a = a->next) {
1919 gchar **pa;
1921 if ((pa = g_realloc(attrlist, (i + 2) * sizeof(gchar *))) == NULL) {
1922 if (attrlist)
1923 g_strfreev(attrlist);
1925 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1926 return gpg_error_from_errno(ENOMEM);
1929 attrlist = pa;
1930 an = a->children;
1931 attrlist[i] = g_strdup_printf("%s %s", (gchar *)a->name, (gchar *)an->content);
1933 if (!attrlist[i]) {
1934 g_strfreev(attrlist);
1935 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1936 return gpg_error_from_errno(ENOMEM);
1939 attrlist[++i] = NULL;
1942 if (!attrlist)
1943 return EPWMD_EMPTY_ELEMENT;
1945 line = g_strjoinv("\n", attrlist);
1947 if (!line) {
1948 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
1949 g_strfreev(attrlist);
1950 return gpg_error_from_errno(ENOMEM);
1953 pth_cleanup_push(g_free, line);
1954 pth_cleanup_push(req_cleanup, attrlist);
1955 rc = xfer_data(ctx, line, strlen(line));
1956 pth_cleanup_pop(1);
1957 pth_cleanup_pop(1);
1958 return rc;
1962 * req[0] - attribute
1963 * req[1] - element path
1965 static int attribute_delete(struct client_s *client, gchar **req)
1967 xmlAttrPtr a;
1968 xmlNodePtr n;
1969 gchar **path = NULL;
1970 gpg_error_t rc;
1972 if (!req || !req[0] || !req[1])
1973 return EPWMD_COMMAND_SYNTAX;
1975 if ((path = split_input_line(req[1], "\t", 0)) == NULL) {
1977 * The first argument may be only an account.
1979 if ((path = split_input_line(req[1], " ", 0)) == NULL)
1980 return EPWMD_COMMAND_SYNTAX;
1984 * Don't remove the "name" attribute for the account element. To remove an
1985 * account use DELETE <account>.
1987 if (!path[1] && xmlStrEqual((xmlChar *)req[0], (xmlChar *)"name")) {
1988 rc = EPWMD_ATTR_SYNTAX;
1989 goto fail;
1992 n = find_account(client->doc, &path, &rc, NULL, 0);
1994 if (!n)
1995 goto fail;
1997 if (path[1]) {
1998 n = find_elements(client->doc, n->children, path+1, &rc,
1999 NULL, NULL, NULL, FALSE, 0, NULL);
2001 if (!n)
2002 goto fail;
2005 g_strfreev(path);
2007 if ((a = xmlHasProp(n, (xmlChar *)req[0])) == NULL)
2008 return EPWMD_ATTR_NOT_FOUND;
2010 if (xmlRemoveProp(a) == -1)
2011 return EPWMD_LIBXML_ERROR;
2013 return 0;
2015 fail:
2016 g_strfreev(path);
2017 return rc;
2020 static xmlNodePtr create_element_path(struct client_s *client, gchar ***path,
2021 gpg_error_t *rc)
2023 gchar **src = *path;
2024 gchar **src_orig = g_strdupv(src);
2025 xmlNodePtr n = NULL;
2027 *rc = 0;
2029 if (!src_orig) {
2030 *rc = gpg_error_from_errno(ENOMEM);
2031 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2032 goto fail;
2035 again:
2036 n = find_account(client->doc, &src, rc, NULL, 0);
2038 if (!n) {
2039 if (*rc == EPWMD_ELEMENT_NOT_FOUND) {
2040 *rc = new_account(client->doc, src[0]);
2042 if (*rc)
2043 goto fail;
2045 goto again;
2047 else
2048 goto fail;
2051 if (src[1]) {
2052 if (!n->children)
2053 n = create_target_elements_cb(n, src+1, rc, NULL);
2054 else
2055 n = find_elements(client->doc, n->children, src+1, rc,
2056 NULL, NULL, create_target_elements_cb, FALSE, 0, NULL);
2058 if (!n)
2059 goto fail;
2062 * Reset the position of the element tree now that the elements
2063 * have been created.
2065 g_strfreev(src);
2066 src = src_orig;
2067 src_orig = NULL;
2068 n = find_account(client->doc, &src, rc, NULL, 0);
2070 if (!n)
2071 goto fail;
2073 n = find_elements(client->doc, n->children, src+1, rc,
2074 NULL, NULL, NULL, FALSE, 0, NULL);
2076 if (!n)
2077 goto fail;
2080 fail:
2081 if (src_orig)
2082 g_strfreev(src_orig);
2084 *path = src;
2085 return n;
2089 * Creates a "target" attribute. When other commands encounter an element with
2090 * this attribute, the element path is modified to the target value. If the
2091 * source element path doesn't exist when using 'ATTR SET target', it is
2092 * created, but the destination element path must exist.
2094 * req[0] - source element path
2095 * req[1] - destination element path
2097 static gpg_error_t target_attribute(struct client_s *client, gchar **req)
2099 gchar **src, **dst, *line = NULL;
2100 gpg_error_t rc;
2101 xmlNodePtr n;
2103 if (!req || !req[0] || !req[1])
2104 return EPWMD_COMMAND_SYNTAX;
2106 if ((src = split_input_line(req[0], "\t", 0)) == NULL) {
2108 * The first argument may be only an account.
2110 if ((src = split_input_line(req[0], " ", 0)) == NULL)
2111 return EPWMD_COMMAND_SYNTAX;
2114 if (valid_element_path(src, FALSE) == FALSE) {
2115 g_strfreev(src);
2116 return EPWMD_INVALID_ELEMENT;
2119 if ((dst = split_input_line(req[1], "\t", 0)) == NULL) {
2121 * The first argument may be only an account.
2123 if ((dst = split_input_line(req[1], " ", 0)) == NULL) {
2124 rc = EPWMD_COMMAND_SYNTAX;
2125 goto fail;
2129 n = find_account(client->doc, &dst, &rc, NULL, 0);
2132 * Make sure the destination element path exists.
2134 if (!n)
2135 goto fail;
2137 if (dst[1]) {
2138 n = find_elements(client->doc, n->children, dst+1, &rc,
2139 NULL, NULL, NULL, FALSE, 0, NULL);
2141 if (!n)
2142 goto fail;
2145 n = create_element_path(client, &src, &rc);
2147 if (rc)
2148 goto fail;
2150 line = g_strjoinv("\t", dst);
2152 if (!line) {
2153 rc = gpg_error_from_errno(ENOMEM);
2154 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2155 goto fail;
2158 rc = add_attribute(n, "target", line);
2160 fail:
2161 g_free(line);
2162 g_strfreev(src);
2163 g_strfreev(dst);
2164 return rc;
2168 * req[0] - account name
2169 * req[1] - new name
2171 static gpg_error_t name_attribute(struct client_s *client, gchar **req)
2173 gpg_error_t rc;
2174 gchar **tmp;
2175 xmlNodePtr n;
2177 tmp = g_strdupv(req);
2179 if (!tmp) {
2180 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2181 return gpg_error_from_errno(ENOMEM);
2184 n = find_account(client->doc, &tmp, &rc, NULL, 0);
2185 g_strfreev(tmp);
2187 if (!n)
2188 return rc;
2190 if (g_utf8_collate(req[0], req[1]) == 0)
2191 return 0;
2194 * Will not overwrite an existing account.
2196 tmp = g_strdupv(req+1);
2198 if (!tmp) {
2199 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2200 return gpg_error_from_errno(ENOMEM);
2203 n = find_account(client->doc, &tmp, &rc, NULL, 0);
2204 g_strfreev(tmp);
2206 if (rc && rc != EPWMD_ELEMENT_NOT_FOUND)
2207 return rc;
2209 if (n)
2210 return EPWMD_ACCOUNT_EXISTS;
2213 * Whitespace not allowed in account names.
2215 if (contains_whitespace(req[1]) == TRUE)
2216 return EPWMD_ATTR_SYNTAX;
2218 tmp = g_strdupv(req);
2220 if (!tmp) {
2221 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2222 return gpg_error_from_errno(ENOMEM);
2225 n = find_account(client->doc, &tmp, &rc, NULL, 0);
2226 g_strfreev(tmp);
2228 if (!n)
2229 return EPWMD_ELEMENT_NOT_FOUND;
2231 return add_attribute(n, "name", req[1]);
2235 * req[0] - attribute
2236 * req[1] - element path
2238 static int attribute_get(assuan_context_t ctx, gchar **req)
2240 struct client_s *client = assuan_get_pointer(ctx);
2241 xmlNodePtr n;
2242 xmlChar *a;
2243 gchar **path= NULL;
2244 gpg_error_t rc;
2246 if (!req || !req[0] || !req[1])
2247 return EPWMD_COMMAND_SYNTAX;
2249 if (strchr(req[1], '\t')) {
2250 if ((path = split_input_line(req[1], "\t", 0)) == NULL)
2251 return EPWMD_COMMAND_SYNTAX;
2253 else {
2254 if ((path = split_input_line(req[1], " ", 0)) == NULL)
2255 return EPWMD_COMMAND_SYNTAX;
2258 n = find_account(client->doc, &path, &rc, NULL, 0);
2260 if (!n)
2261 goto fail;
2263 if (path[1]) {
2264 n = find_elements(client->doc, n->children, path+1, &rc,
2265 NULL, NULL, NULL, FALSE, 0, NULL);
2267 if (!n)
2268 goto fail;
2271 g_strfreev(path);
2273 if ((a = xmlGetProp(n, (xmlChar *)req[0])) == NULL)
2274 return EPWMD_ATTR_NOT_FOUND;
2276 pth_cleanup_push(xmlFree, a);
2277 rc = xfer_data(ctx, (gchar *)a, xmlStrlen(a));
2278 pth_cleanup_pop(1);
2279 return rc;
2281 fail:
2282 g_strfreev(path);
2283 return rc;
2287 * req[0] - attribute
2288 * req[1] - element path
2289 * req[2] - value
2291 static int attribute_set(struct client_s *client, gchar **req)
2293 gchar **path = NULL;
2294 gpg_error_t rc;
2295 xmlNodePtr n;
2297 if (!req || !req[0] || !req[1] || !req[2])
2298 return EPWMD_COMMAND_SYNTAX;
2301 * Reserved attribute names.
2303 if (g_utf8_collate(req[0], "name") == 0) {
2305 * Only reserved for the account element. Not the rest of the
2306 * document.
2308 if (strchr(req[1], '\t') == NULL)
2309 return name_attribute(client, req + 1);
2311 else if (g_utf8_collate(req[0], "target") == 0)
2312 return target_attribute(client, req + 1);
2314 if ((path = split_input_line(req[1], "\t", 0)) == NULL) {
2316 * The first argument may be only an account.
2318 if ((path = split_input_line(req[1], " ", 0)) == NULL)
2319 return EPWMD_COMMAND_SYNTAX;
2322 n = find_account(client->doc, &path, &rc, NULL, 0);
2324 if (!n)
2325 goto fail;
2327 if (path[1]) {
2328 n = find_elements(client->doc, n->children, path+1, &rc,
2329 NULL, NULL, NULL, FALSE, 0, NULL);
2331 if (!n)
2332 goto fail;
2335 g_strfreev(path);
2336 return add_attribute(n, req[0], req[2]);
2338 fail:
2339 g_strfreev(path);
2340 return rc;
2344 * req[0] - command
2345 * req[1] - attribute name or element path if command is LIST
2346 * req[2] - element path
2347 * req[2] - element path or value
2349 static int attr_command(assuan_context_t ctx, char *line)
2351 struct client_s *client = assuan_get_pointer(ctx);
2352 gchar **req;
2353 gpg_error_t rc = 0;
2355 log_write2("ARGS=\"%s\"", line);
2356 req = split_input_line(line, " ", 4);
2358 if (!req || !req[0] || !req[1]) {
2359 g_strfreev(req);
2360 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2363 pth_cleanup_push(req_cleanup, req);
2365 if (g_ascii_strcasecmp(req[0], "SET") == 0)
2366 rc = attribute_set(client, req+1);
2367 else if (g_ascii_strcasecmp(req[0], "GET") == 0)
2368 rc = attribute_get(ctx, req+1);
2369 else if (g_ascii_strcasecmp(req[0], "DELETE") == 0)
2370 rc = attribute_delete(client, req+1);
2371 else if (g_ascii_strcasecmp(req[0], "LIST") == 0)
2372 rc = attribute_list(ctx, req+1);
2373 else
2374 rc = EPWMD_COMMAND_SYNTAX;
2376 pth_cleanup_pop(1);
2377 return send_error(ctx, rc);
2380 static int iscached_command(assuan_context_t ctx, char *line)
2382 gchar **req = split_input_line(line, " ", 0);
2383 guchar md5file[16];
2384 gchar *path, *tmp;
2386 if (!req || !*req) {
2387 g_strfreev(req);
2388 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2391 log_write2("ARGS=\"%s\"", line);
2393 if (!valid_filename(req[0])) {
2394 g_strfreev(req);
2395 return EPWMD_INVALID_FILENAME;
2398 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, req[0], strlen(req[0]));
2399 CACHE_LOCK(ctx);
2401 if (cache_iscached(md5file)) {
2402 g_strfreev(req);
2403 CACHE_UNLOCK;
2404 return send_error(ctx, 0);
2407 CACHE_UNLOCK;
2408 tmp = get_key_file_string("global", "data_directory");
2410 if (!tmp) {
2411 g_strfreev(req);
2412 return gpg_error_from_errno(ENOMEM);
2415 path = expand_homedir(tmp);
2417 if (!path) {
2418 g_strfreev(req);
2419 g_free(tmp);
2420 return gpg_error_from_errno(ENOMEM);
2423 g_free(tmp);
2424 tmp = path;
2425 path = g_strdup_printf("%s/%s", tmp, req[0]);
2426 g_free(tmp);
2428 if (!path) {
2429 g_strfreev(req);
2430 return gpg_error_from_errno(ENOMEM);
2433 if (access(path, R_OK) == -1) {
2434 gpg_error_t rc = gpg_error_from_syserror();
2436 g_free(path);
2437 g_strfreev(req);
2438 return send_error(ctx, rc);
2441 g_free(path);
2442 return send_error(ctx, EPWMD_CACHE_NOT_FOUND);
2445 static int clearcache_command(assuan_context_t ctx, char *line)
2447 struct client_s *client = assuan_get_pointer(ctx);
2448 gchar **req = split_input_line(line, " ", 0);
2449 guchar md5file[16];
2451 log_write2("ARGS=\"%s\"", line);
2452 CACHE_LOCK(ctx);
2454 if (!req || !*req) {
2455 g_strfreev(req);
2456 cache_clear(client->md5file, 2);
2457 CACHE_UNLOCK;
2458 return send_error(ctx, 0);
2461 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, req[0], strlen(req[0]));
2462 g_strfreev(req);
2464 if (cache_clear(md5file, 1) == FALSE) {
2465 CACHE_UNLOCK;
2466 return send_error(ctx, EPWMD_CACHE_NOT_FOUND);
2469 CACHE_UNLOCK;
2470 return send_error(ctx, 0);
2473 static int cachetimeout_command(assuan_context_t ctx, char *line)
2475 guchar md5file[16];
2476 glong timeout;
2477 gchar **req = split_input_line(line, " ", 0);
2478 gchar *p;
2480 if (!req || !*req || !req[1]) {
2481 g_strfreev(req);
2482 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2485 errno = 0;
2486 timeout = strtol(req[1], &p, 10);
2488 if (errno != 0 || *p != 0 || timeout < -1) {
2489 g_strfreev(req);
2490 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2493 gcry_md_hash_buffer(GCRY_MD_MD5, md5file, req[0], strlen(req[0]));
2494 CACHE_LOCK(client->ctx);
2496 if (cache_set_timeout(md5file, timeout) == FALSE) {
2497 CACHE_UNLOCK;
2498 return send_error(ctx, EPWMD_CACHE_NOT_FOUND);
2501 CACHE_UNLOCK;
2502 return send_error(ctx, 0);
2505 static int dump_command(assuan_context_t ctx, char *line)
2507 xmlChar *xml;
2508 gssize len;
2509 struct client_s *client = assuan_get_pointer(ctx);
2510 gpg_error_t rc;
2512 if (disable_list_and_dump == TRUE)
2513 return send_error(ctx, GPG_ERR_NOT_IMPLEMENTED);
2515 xmlDocDumpFormatMemory(client->doc, &xml, &len, 1);
2517 if (!xml) {
2518 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2519 return send_syserror(ctx, ENOMEM);
2522 pth_cleanup_push(xmlFree, xml);
2523 rc = xfer_data(ctx, (gchar *)xml, len);
2524 pth_cleanup_pop(1);
2525 return send_error(ctx, rc);
2528 static int getconfig_command(assuan_context_t ctx, gchar *line)
2530 struct client_s *client = assuan_get_pointer(ctx);
2531 gpg_error_t rc = 0;
2532 gchar filename[255]={0}, param[747]={0};
2533 gchar *p, *tmp, *fp = client->filename, *paramp = line;
2535 log_write2("ARGS=\"%s\"", line);
2537 if (strchr(line, ' ')) {
2538 sscanf(line, " %254[^ ] %746c", filename, param);
2539 paramp = param;
2540 fp = filename;
2543 if (fp && !valid_filename(fp))
2544 return send_error(ctx, EPWMD_INVALID_FILENAME);
2546 paramp = g_ascii_strdown(paramp, -1);
2548 if (!paramp) {
2549 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2550 return send_syserror(ctx, ENOMEM);
2553 if (fp && !g_ascii_strcasecmp(paramp, "iterations")) {
2554 if (!(client->opts & OPT_ITERATIONS) || fp != client->filename) {
2555 file_header_internal_t *fh = read_file_header(fp, FALSE, &rc);
2557 if (!fh && rc != GPG_ERR_ENOENT)
2558 return send_error(ctx, rc);
2560 if (!rc) {
2561 g_free(paramp);
2562 p = g_strdup_printf("%llu", fh->ver.fh2.iter);
2563 close_file_header(fh);
2565 if (!p) {
2566 log_write("%s(%i): %s", __FILE__, __LINE__,
2567 strerror(ENOMEM));
2568 return send_syserror(ctx, ENOMEM);
2571 goto done;
2575 else if (!g_ascii_strcasecmp(paramp, "enable_pinentry")) {
2576 #ifdef WITH_PINENTRY
2577 gboolean n;
2579 if (fp == client->filename && (client->opts & OPT_PINENTRY))
2580 n = client->pinentry->enable;
2581 else
2582 n = get_key_file_boolean(fp, "enable_pinentry");
2584 p = g_strdup_printf("%s", n ? "true" : "false");
2586 if (!p) {
2587 log_write("%s(%i): %s", __FILE__, __LINE__,
2588 strerror(ENOMEM));
2589 return send_syserror(ctx, ENOMEM);
2592 goto done;
2593 #else
2594 return send_error(ctx, GPG_ERR_NOT_IMPLEMENTED);
2595 #endif
2597 else if (!g_ascii_strcasecmp(paramp, "pinentry_timeout")) {
2598 #ifdef WITH_PINENTRY
2599 if (fp == client->filename && (client->opts & OPT_PINENTRY_TO))
2600 p = g_strdup_printf("%i", client->pinentry->timeout);
2601 else
2602 p = g_strdup_printf("%i",
2603 get_key_file_integer(fp, "pinentry_timeout"));
2605 if (!p) {
2606 log_write("%s(%i): %s", __FILE__, __LINE__,
2607 strerror(ENOMEM));
2608 return send_syserror(ctx, ENOMEM);
2611 goto done;
2612 #else
2613 return send_error(ctx, GPG_ERR_NOT_IMPLEMENTED);
2614 #endif
2617 p = get_key_file_string(fp ? fp : "global", paramp);
2618 g_free(paramp);
2620 if (!p)
2621 return send_error(ctx, GPG_ERR_NO_VALUE);
2623 tmp = expand_homedir(p);
2624 g_free(p);
2626 if (!tmp) {
2627 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2628 return send_syserror(ctx, ENOMEM);
2631 p = tmp;
2632 done:
2633 pth_cleanup_push(g_free, p);
2634 rc = xfer_data(ctx, p, strlen(p));
2635 pth_cleanup_pop(1);
2636 return send_error(ctx, rc);
2639 struct xpath_s {
2640 xmlXPathContextPtr xp;
2641 xmlXPathObjectPtr result;
2642 xmlBufferPtr buf;
2643 gchar **req;
2646 static void xpath_command_cleanup(void *arg)
2648 struct xpath_s *xpath = arg;
2650 req_cleanup(xpath->req);
2652 if (xpath->buf)
2653 xmlBufferFree(xpath->buf);
2655 if (xpath->result)
2656 xmlXPathFreeObject(xpath->result);
2658 if (xpath->xp)
2659 xmlXPathFreeContext(xpath->xp);
2662 static int xpath_command(assuan_context_t ctx, gchar *line)
2664 struct client_s *client = assuan_get_pointer(ctx);
2665 gpg_error_t rc;
2666 struct xpath_s xpath;
2668 log_write2("ARGS=\"%s\"", line);
2670 if (disable_list_and_dump == TRUE)
2671 return send_error(ctx, GPG_ERR_NOT_IMPLEMENTED);
2673 if (!line || !*line)
2674 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
2676 memset(&xpath, 0, sizeof(struct xpath_s));
2678 if ((xpath.req = split_input_line(line, "\t", 2)) == NULL) {
2679 if (strv_printf(&xpath.req, "%s", line) == FALSE)
2680 return send_syserror(ctx, ENOMEM);
2683 xpath.xp = xmlXPathNewContext(client->doc);
2685 if (!xpath.xp) {
2686 xpath_command_cleanup(&xpath);
2687 return send_error(ctx, EPWMD_LIBXML_ERROR);
2690 xpath.result = xmlXPathEvalExpression((xmlChar *)xpath.req[0], xpath.xp);
2692 if (!xpath.result) {
2693 xpath_command_cleanup(&xpath);
2694 return send_error(ctx, EPWMD_LIBXML_ERROR);
2697 if (xmlXPathNodeSetIsEmpty(xpath.result->nodesetval)) {
2698 rc = EPWMD_EMPTY_ELEMENT;
2699 goto fail;
2702 rc = recurse_xpath_nodeset(client->doc, xpath.result->nodesetval,
2703 (xmlChar *)xpath.req[1], &xpath.buf);
2705 if (rc)
2706 goto fail;
2707 else if (!xpath.req[1] && !xmlBufferLength(xpath.buf)) {
2708 rc = EPWMD_EMPTY_ELEMENT;
2709 goto fail;
2711 else if (xpath.req[1])
2712 goto fail;
2714 pth_cleanup_push(xpath_command_cleanup, &xpath);
2715 rc = xfer_data(ctx, (gchar *)xmlBufferContent(xpath.buf),
2716 xmlBufferLength(xpath.buf));
2717 pth_cleanup_pop(0);
2719 fail:
2720 xpath_command_cleanup(&xpath);
2721 return send_error(ctx, rc);
2724 static int import_command_finalize(gpointer data, gint assuan_rc, guchar *line,
2725 gsize len)
2727 struct client_s *client = assuan_get_pointer((assuan_context_t)data);
2728 gpg_error_t rc = file_modified(client);
2729 gchar **req, **path = NULL, **path_orig = NULL, *content;
2730 xmlDocPtr doc;
2731 xmlNodePtr n, root, copy;
2733 if (assuan_rc || rc) {
2734 if (line)
2735 xfree(line);
2736 return assuan_rc ? assuan_rc : rc;
2739 req = split_input_line((gchar *)line, " ", 2);
2740 xfree(line);
2742 if (!req || !*req)
2743 return EPWMD_COMMAND_SYNTAX;
2745 if ((path = split_input_line(req[0], "\t", 0)) == NULL) {
2746 if ((path = split_input_line(req[0], " ", 0)) == NULL)
2747 return EPWMD_COMMAND_SYNTAX;
2750 content = req[1];
2752 if (!content || !*content) {
2753 rc = EPWMD_COMMAND_SYNTAX;
2754 goto fail;
2757 if (valid_xml_element((xmlChar *)*path) == FALSE) {
2758 rc = EPWMD_INVALID_ELEMENT;
2759 goto fail;
2762 if (valid_element_path(path+1, FALSE) == FALSE) {
2763 rc = EPWMD_INVALID_ELEMENT;
2764 goto fail;
2767 doc = xmlReadDoc((xmlChar *)content, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2769 if (!doc) {
2770 rc = EPWMD_LIBXML_ERROR;
2771 goto fail;
2774 root = xmlDocGetRootElement(doc);
2775 path_orig = g_strdupv(path);
2777 if (!path_orig) {
2778 xmlFreeDoc(doc);
2779 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
2780 rc = gpg_error_from_errno(ENOMEM);
2781 goto fail;
2784 if (strv_printf(&path, "%s", (gchar *)root->name) == FALSE) {
2785 g_strfreev(path_orig);
2786 xmlFreeDoc(doc);
2787 rc = gpg_error_from_errno(ENOMEM);
2788 goto fail;
2791 n = find_account(client->doc, &path, &rc, NULL, 0);
2793 if (rc && rc != EPWMD_ELEMENT_NOT_FOUND) {
2794 g_strfreev(path_orig);
2795 xmlFreeDoc(doc);
2796 goto fail;
2798 else if (!rc) {
2799 n = find_elements(client->doc, n->children, path+1, &rc, NULL, NULL, NULL, FALSE, 0, NULL);
2801 if (rc && rc != EPWMD_ELEMENT_NOT_FOUND) {
2802 g_strfreev(path_orig);
2803 xmlFreeDoc(doc);
2804 goto fail;
2806 else if (!rc) {
2807 xmlNodePtr parent = n->parent;
2809 xmlUnlinkNode(n);
2810 xmlFreeNode(n);
2811 n = parent;
2815 g_strfreev(path);
2816 path = path_orig;
2818 if (rc == EPWMD_ELEMENT_NOT_FOUND) {
2819 n = create_element_path(client, &path, &rc);
2821 if (rc) {
2822 xmlFreeDoc(doc);
2823 goto fail;
2827 copy = xmlCopyNode(root, 1);
2828 n = xmlAddChild(n, copy);
2829 xmlFreeDoc(doc);
2831 if (!n)
2832 rc = EPWMD_LIBXML_ERROR;
2834 fail:
2835 g_strfreev(path);
2836 g_strfreev(req);
2837 client->inquire_status = INQUIRE_DONE;
2838 return rc;
2841 static int import_command(assuan_context_t ctx, gchar *line)
2843 gpg_error_t rc;
2844 struct client_s *client = assuan_get_pointer(ctx);
2846 rc = assuan_inquire_ext(ctx, "IMPORT", 0, import_command_finalize, ctx);
2848 if (rc)
2849 return send_error(ctx, rc);
2851 /* Don't return with assuan_process_done() here. This is an INQUIRE. */
2852 client->inquire_status = INQUIRE_BUSY;
2853 return 0;
2856 static int lock_command(assuan_context_t ctx, gchar *line)
2858 gpg_error_t rc;
2859 struct client_s *client = assuan_get_pointer(ctx);
2861 rc = lock_file_mutex(client);
2863 if (!rc)
2864 client->is_lock_cmd = TRUE;
2866 return send_error(ctx, rc);
2869 static int unlock_command(assuan_context_t ctx, gchar *line)
2871 struct client_s *client = assuan_get_pointer(ctx);
2873 unlock_file_mutex(client);
2874 return send_error(ctx, 0);
2877 static int getpid_command(assuan_context_t ctx, gchar *line)
2879 gpg_error_t rc;
2880 gchar buf[32];
2881 pid_t pid = getpid();
2883 print_fmt(buf, sizeof(buf), "%i", pid);
2884 rc = xfer_data(ctx, buf, strlen(buf));
2885 return send_error(ctx, rc);
2888 static int version_command(assuan_context_t ctx, gchar *line)
2890 gpg_error_t rc;
2891 gchar buf[32];
2893 print_fmt(buf, sizeof(buf), "0x%X", VERSION_HEX);
2894 rc = xfer_data(ctx, buf, strlen(buf));
2895 return send_error(ctx, rc);
2898 #ifdef WITH_PINENTRY
2899 static void set_option_value(gchar **opt, const gchar *value)
2901 if (opt)
2902 g_free(*opt);
2904 *opt = NULL;
2906 if (value)
2907 *opt = g_strdup(value);
2909 #endif
2911 static int set_unset_common(assuan_context_t ctx, const gchar *name,
2912 const gchar *value)
2914 struct client_s *client = assuan_get_pointer(ctx);
2916 if (g_ascii_strcasecmp(name, (gchar *)"log_level") == 0) {
2917 glong l = 0;
2919 if (value) {
2920 l = strtol(value, NULL, 10);
2922 if (l < 0 || l > 2)
2923 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_INV_VALUE);
2926 log_write1("log_level=%li", l);
2927 MUTEX_LOCK(&rcfile_mutex);
2928 g_key_file_set_integer(keyfileh, "global", "log_level", (gint)l);
2929 MUTEX_UNLOCK(&rcfile_mutex);
2930 goto done;
2932 else if (g_ascii_strcasecmp(name, (gchar *)"cipher") == 0) {
2933 guint64 flags;
2934 const gchar *p = value;
2936 if (!client->filename)
2937 return EPWMD_NO_FILE;
2939 if (value) {
2940 flags = pwmd_cipher_str_to_cipher(value);
2942 if (!flags)
2943 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_INV_VALUE);
2945 else if (!value)
2946 p = get_key_file_string("global", "cipher");
2948 MUTEX_LOCK(&rcfile_mutex);
2949 g_key_file_set_string(keyfileh, client->filename, "cipher", p);
2950 MUTEX_UNLOCK(&rcfile_mutex);
2951 log_write1("cipher=%s", p);
2953 if (!value)
2954 g_free((gchar *)p);
2956 goto done;
2958 else if (g_ascii_strcasecmp(name, (gchar *)"iterations") == 0) {
2959 long n;
2960 gchar *p = NULL;
2962 if (!client->filename)
2963 return EPWMD_NO_FILE;
2965 if (!value) {
2966 MUTEX_LOCK(&rcfile_mutex);
2967 g_key_file_set_integer(keyfileh, client->filename, "iterations",
2968 get_key_file_integer("global", "iterations"));
2969 MUTEX_UNLOCK(&rcfile_mutex);
2970 log_write1("iterations=%u",
2971 get_key_file_integer(client->filename, "iterations"));
2972 goto done;
2975 errno = 0;
2976 n = strtol(value, &p, 10);
2978 if (errno || (p && *p) || n < 0)
2979 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_INV_VALUE);
2981 MUTEX_LOCK(&rcfile_mutex);
2982 g_key_file_set_integer(keyfileh,
2983 client->filename ? client->filename : "global", "iterations",
2984 (guint)n);
2985 MUTEX_UNLOCK(&rcfile_mutex);
2987 if (client->filename)
2988 client->opts |= OPT_ITERATIONS;
2990 log_write1("iterations=%u", n);
2991 goto done;
2993 else if (g_ascii_strcasecmp(name, (gchar *)"NAME") == 0) {
2994 pth_attr_t attr = pth_attr_of(pth_self());
2995 gchar buf[41];
2997 if (!value) {
2998 pth_attr_destroy(attr);
2999 goto done;
3002 print_fmt(buf, sizeof(buf), "%s", value);
3003 pth_attr_set(attr, PTH_ATTR_NAME, buf);
3004 pth_attr_destroy(attr);
3005 log_write1("name=%s", buf);
3006 #ifdef WITH_PINENTRY
3007 if (client->pinentry->name)
3008 g_free(client->pinentry->name);
3010 client->pinentry->name = g_strdup(buf);
3012 if (!client->pinentry->name)
3013 return gpg_error_from_errno(ENOMEM);
3014 #endif
3016 goto done;
3018 #ifdef WITH_PINENTRY
3019 else if (g_ascii_strcasecmp(name, (gchar *)"lc_messages") == 0)
3020 set_option_value(&client->pinentry->lcmessages, value);
3021 else if (g_ascii_strcasecmp(name, (gchar *)"lc_ctype") == 0)
3022 set_option_value(&client->pinentry->lcctype, value);
3023 else if (g_ascii_strcasecmp(name, (gchar *)"ttyname") == 0)
3024 set_option_value(&client->pinentry->ttyname, value);
3025 else if (g_ascii_strcasecmp(name, (gchar *)"ttytype") == 0)
3026 set_option_value(&client->pinentry->ttytype, value);
3027 else if (g_ascii_strcasecmp(name, (gchar *)"display") == 0)
3028 set_option_value(&client->pinentry->display, value);
3029 else if (g_ascii_strcasecmp(name, (gchar *)"pinentry_path") == 0)
3030 set_option_value(&client->pinentry->path, value);
3031 else if (g_ascii_strcasecmp(name, (gchar *)"title") == 0)
3032 set_option_value(&client->pinentry->title, value);
3033 else if (g_ascii_strcasecmp(name, (gchar *)"prompt") == 0)
3034 set_option_value(&client->pinentry->prompt, value);
3035 else if (g_ascii_strcasecmp(name, (gchar *)"desc") == 0)
3036 set_option_value(&client->pinentry->desc, value);
3037 else if (g_ascii_strcasecmp(name, "pinentry_timeout") == 0) {
3038 gchar *p = NULL;
3039 gint n;
3041 if (!value) {
3042 client->pinentry->timeout =
3043 get_key_file_integer(client->filename, "pinentry_timeout");
3044 client->opts &= ~(OPT_PINENTRY_TO);
3045 log_write1("pinentry_timeout=%i",
3046 get_key_file_integer(client->filename, "pinentry_timeout"));
3047 goto done;
3050 n = strtol(value, &p, 10);
3052 if (*p || n < 0)
3053 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_INV_VALUE);
3055 client->pinentry->timeout = n;
3056 client->opts |= OPT_PINENTRY_TO;
3057 log_write1("pinentry_timeout=%i", n);
3058 goto done;
3060 else if (g_ascii_strcasecmp(name, "enable_pinentry") == 0) {
3061 gchar *p = NULL;
3062 gint n;
3064 if (!value) {
3065 client->pinentry->enable = -1;
3066 client->opts &= ~(OPT_PINENTRY);
3067 goto done;
3070 n = strtol(value, &p, 10);
3072 if (*p || n < 0 || n > 1)
3073 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_INV_VALUE);
3075 client->pinentry->enable = n == 0 ? FALSE : TRUE;
3076 client->opts |= OPT_PINENTRY;
3077 log_write1("enable_pinentry=%i", n);
3078 goto done;
3080 #endif
3081 else
3082 return gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_UNKNOWN_OPTION);
3084 log_write1("%s=%s", name, value ? value : "");
3086 done:
3087 return 0;
3090 static int unset_command(assuan_context_t ctx, gchar *line)
3092 log_write2("ARGS=\"%s\"", line);
3093 return send_error(ctx, set_unset_common(ctx, line, NULL));
3096 static int set_command(assuan_context_t ctx, gchar *line)
3098 gchar name[64] = {0}, value[256] = {0};
3100 log_write2("ARGS=\"%s\"", line);
3102 if (sscanf(line, " %63[_a-zA-Z] = %255c", name, value) != 2)
3103 return send_error(ctx, gpg_err_make(PWMD_ERR_SOURCE, GPG_ERR_SYNTAX));
3105 return send_error(ctx, set_unset_common(ctx, name, value));
3108 static int rename_command(assuan_context_t ctx, gchar *line)
3110 struct client_s *client = assuan_get_pointer(ctx);
3111 gpg_error_t rc;
3112 gchar **req, **src, *dst;
3113 xmlNodePtr n;
3115 log_write2("ARGS=\"%s\"", line);
3116 req = split_input_line(line, " ", -1);
3118 if (!req || !req[0] || !req[1]) {
3119 g_strfreev(req);
3120 return send_error(ctx, EPWMD_COMMAND_SYNTAX);
3123 dst = req[1];
3125 if (!valid_xml_element((xmlChar *)dst)) {
3126 g_strfreev(req);
3127 return EPWMD_INVALID_ELEMENT;
3130 if (strchr(req[0], '\t'))
3131 src = split_input_line(req[0], "\t", -1);
3132 else
3133 src = split_input_line(req[0], " ", -1);
3135 if (!src || !*src) {
3136 rc = EPWMD_COMMAND_SYNTAX;
3137 goto fail;
3140 n = find_account(client->doc, &src, &rc, NULL, 0);
3142 if (src[1] && n)
3143 n = find_elements(client->doc, n->children, src+1, &rc, NULL, NULL, NULL, FALSE, 0, NULL);
3145 if (!n)
3146 goto fail;
3148 if (src[1])
3149 xmlNodeSetName(n, (xmlChar *)dst);
3150 else
3151 rc = add_attribute(n, "name", dst);
3153 fail:
3154 g_strfreev(req);
3155 g_strfreev(src);
3156 return send_error(ctx, rc);
3159 static void bye_notify(assuan_context_t ctx)
3161 struct client_s *cl = assuan_get_pointer(ctx);
3163 /* This will let assuan_process_next() return. */
3164 fcntl(cl->thd->fd, F_SETFL, O_NONBLOCK);
3167 static void reset_notify(assuan_context_t ctx)
3169 struct client_s *cl = assuan_get_pointer(ctx);
3171 if (cl)
3172 cleanup_client(cl);
3176 * This is called before every Assuan command.
3178 int command_startup(assuan_context_t ctx, const char *name)
3180 struct client_s *cl = assuan_get_pointer(ctx);
3181 gpg_error_t rc;
3183 log_write1("%s", name);
3185 if (!g_ascii_strcasecmp(name, "ISCACHED") ||
3186 !g_ascii_strcasecmp(name, "CLEARCACHE") ||
3187 !g_ascii_strcasecmp(name, "CACHETIMEOUT") ||
3188 !g_ascii_strcasecmp(name, "GETCONFIG") ||
3189 !g_ascii_strcasecmp(name, "GETPID") ||
3190 !g_ascii_strcasecmp(name, "VERSION") ||
3191 !g_ascii_strcasecmp(name, "SET") ||
3192 !g_ascii_strcasecmp(name, "BYE") ||
3193 !g_ascii_strcasecmp(name, "NOP") ||
3194 !g_ascii_strcasecmp(name, "CANCEL") ||
3195 !g_ascii_strcasecmp(name, "RESET") ||
3196 !g_ascii_strcasecmp(name, "END") ||
3197 !g_ascii_strcasecmp(name, "HELP") ||
3198 !g_ascii_strcasecmp(name, "OPTION") ||
3199 !g_ascii_strcasecmp(name, "INPUT") ||
3200 !g_ascii_strcasecmp(name, "OUTPUT") ||
3201 !g_ascii_strcasecmp(name, "UNSET"))
3202 return 0;
3204 cl->last_rc = rc = file_modified(cl);
3206 if (rc) {
3207 if ((rc == EPWMD_NO_FILE || rc == EPWMD_FILE_MODIFIED) &&
3208 !g_ascii_strcasecmp(name, "OPEN"))
3209 rc = 0;
3212 return rc;
3216 * This is called after every Assuan command.
3218 void command_finalize(assuan_context_t ctx, gint rc)
3220 struct client_s *client = assuan_get_pointer(ctx);
3222 if (!client->is_lock_cmd)
3223 unlock_file_mutex(client);
3225 log_write1(N_("command completed (rc=%u)"), client->last_rc);
3228 gpg_error_t register_commands(assuan_context_t ctx)
3230 static struct {
3231 const gchar *name;
3232 gint (*handler)(assuan_context_t, gchar *line);
3233 } table[] = {
3234 { "OPEN", open_command },
3235 { "SAVE", save_command },
3236 { "LIST", list_command },
3237 { "REALPATH", realpath_command },
3238 { "STORE", store_command },
3239 { "DELETE", delete_command },
3240 { "GET", get_command },
3241 { "ATTR", attr_command },
3242 { "ISCACHED", iscached_command },
3243 { "CLEARCACHE", clearcache_command },
3244 { "CACHETIMEOUT", cachetimeout_command },
3245 { "GETCONFIG", getconfig_command },
3246 { "DUMP", dump_command },
3247 { "XPATH", xpath_command },
3248 { "IMPORT", import_command },
3249 { "LOCK", lock_command },
3250 { "UNLOCK", unlock_command },
3251 { "GETPID", getpid_command },
3252 { "VERSION", version_command },
3253 { "SET", set_command },
3254 { "UNSET", unset_command },
3255 { "RENAME", rename_command },
3256 { "INPUT", NULL },
3257 { "OUTPUT", NULL },
3258 { NULL, NULL }
3260 gint i, rc;
3262 for (i=0; table[i].name; i++) {
3263 rc = assuan_register_command (ctx, table[i].name, table[i].handler);
3265 if (rc)
3266 return rc;
3269 rc = assuan_register_bye_notify(ctx, bye_notify);
3271 if (rc)
3272 return rc;
3274 rc = assuan_register_reset_notify(ctx, reset_notify);
3276 if (rc)
3277 return rc;
3279 rc = assuan_register_pre_cmd_notify(ctx, command_startup);
3281 if (rc)
3282 return rc;
3284 return assuan_register_post_cmd_notify(ctx, command_finalize);
3287 gpg_error_t try_xml_decrypt(assuan_context_t ctx, guchar *key,
3288 struct client_crypto_s *crypto, gpointer *dst, goffset *dst_len)
3290 goffset insize, len;
3291 struct client_s *client = ctx ? assuan_get_pointer(ctx) : NULL;
3292 guint64 iter = 0, n_iter = 0, iter_progress = 0;
3293 gint zrc = 0;
3294 gulong outsize = 0;
3295 gpg_error_t rc;
3296 gsize fh_size = crypto->fh->v1 ? sizeof(crypto->fh->ver.fh1) : sizeof(crypto->fh->ver.fh2);
3297 guint64 fh_iter = crypto->fh->v1 ? crypto->fh->ver.fh1.iter : crypto->fh->ver.fh2.iter;
3298 guint hashlen = gcry_md_get_algo_dlen(GCRY_MD_SHA256);
3300 lseek(crypto->fh->fd, fh_size, SEEK_SET);
3301 insize = crypto->fh->st.st_size - fh_size;
3302 crypto->iv = gcry_malloc(crypto->blocksize);
3304 if (!crypto->iv) {
3305 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
3306 return gpg_error_from_errno(ENOMEM);
3309 /* No encryption iterations. This is a plain (gzipped) file. */
3310 if ((crypto->fh->v1 && fh_iter < 0) || (!crypto->fh->v1 && fh_iter <= 0)) {
3312 * cache_file_count() needs both .used == TRUE and a valid key in
3313 * order for it to count as a used cache entry. Fixes CACHE status
3314 * messages.
3316 memset(key, '!', hashlen);
3319 if (crypto->fh->v1)
3320 memcpy(crypto->iv, crypto->fh->ver.fh1.iv, crypto->blocksize);
3321 else
3322 memcpy(crypto->iv, crypto->fh->ver.fh2.iv, crypto->blocksize);
3324 crypto->inbuf = gcry_malloc(insize);
3326 if (!crypto->inbuf) {
3327 log_write("%s(%i): %s", __FILE__, __LINE__, strerror(ENOMEM));
3328 return gpg_error_from_errno(ENOMEM);
3331 crypto->insize = insize;
3332 len = pth_read(crypto->fh->fd, crypto->inbuf, crypto->insize);
3334 if (len != crypto->insize)
3335 return GPG_ERR_INV_LENGTH;
3337 if ((crypto->fh->v1 && fh_iter < 0) || (!crypto->fh->v1 && fh_iter <= 0))
3338 goto decompress;
3340 if ((rc = gcry_cipher_setiv(crypto->gh, crypto->iv, crypto->blocksize))) {
3341 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3342 return rc;
3345 if ((rc = gcry_cipher_setkey(crypto->gh, key, crypto->keysize))) {
3346 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3347 return rc;
3350 iter_progress = (guint64)get_key_file_integer(client && client->filename ?
3351 client->filename : "global", "iteration_progress");
3353 if (iter_progress > 0 && fh_iter >= iter_progress) {
3354 rc = send_status(ctx, STATUS_DECRYPT, "0 %llu", fh_iter);
3356 if (rc)
3357 return rc;
3360 rc = iterate_crypto_once(client, crypto, STATUS_DECRYPT);
3362 if (rc)
3363 return rc;
3365 crypto->tkey = gcry_malloc(hashlen);
3367 if (!crypto->tkey) {
3368 log_write("%s(%i): %s", __FUNCTION__, __LINE__, strerror(ENOMEM));
3369 return gpg_error_from_errno(ENOMEM);
3372 memcpy(crypto->tkey, key, hashlen);
3373 guchar *tkey = crypto->tkey;
3374 tkey[0] ^= 1;
3376 if ((rc = gcry_cipher_setkey(crypto->gh, crypto->tkey, crypto->keysize))) {
3377 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3378 return rc;
3381 while (iter < (crypto->fh->v1 ? fh_iter : fh_iter-1)) {
3382 if (iter_progress > 0 && iter >= iter_progress) {
3383 if (!(iter % iter_progress)) {
3384 rc = send_status(ctx, STATUS_DECRYPT, "%llu %llu",
3385 ++n_iter * iter_progress, fh_iter);
3387 if (rc)
3388 return rc;
3392 if ((rc = gcry_cipher_setiv(crypto->gh, crypto->iv, crypto->blocksize))) {
3393 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3394 return rc;
3397 rc = iterate_crypto_once(client, crypto, STATUS_DECRYPT);
3399 if (rc) {
3400 log_write("%s(%i): %s", __FUNCTION__, __LINE__, _gpg_strerror(rc));
3401 return rc;
3404 iter++;
3407 if (iter_progress && fh_iter >= iter_progress) {
3408 rc = send_status(ctx, STATUS_DECRYPT, "%llu %llu", fh_iter, fh_iter);
3410 if (rc)
3411 return rc;
3414 decompress:
3415 if (do_decompress(ctx, crypto->inbuf, crypto->insize,
3416 (gpointer *)&crypto->outbuf, &outsize, &zrc) == FALSE) {
3417 if (zrc == Z_MEM_ERROR)
3418 return gpg_error_from_errno(ENOMEM);
3419 else
3420 return EPWMD_BADKEY; // Not a valid gzip header. Must be a bad key.
3423 if (g_strncasecmp(crypto->outbuf, "<?xml ", 6) != 0) {
3424 gcry_free(crypto->outbuf);
3425 crypto->outbuf = NULL;
3426 return EPWMD_BADKEY;
3429 if (ctx) {
3430 client->xml = crypto->outbuf;
3431 client->len = outsize;
3432 crypto->outbuf = NULL;
3434 else if (dst) {
3435 *dst = crypto->outbuf;
3436 *dst_len = outsize;
3437 crypto->outbuf = NULL;
3440 /* The calling function should free the crypto struct. */
3441 return 0;