1 /* This file is part of Mailfromd.
2    Copyright (C) 2005-2021 Sergey Poznyakoff
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3, or (at your option)
7    any later version.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16 
17 #ifdef HAVE_CONFIG_H
18 # include <config.h>
19 #endif
20 
21 #include <stdlib.h>
22 #include <mailutils/alloc.h>
23 
24 #include "libmf.h"
25 
26 struct namerec {
27 	struct namerec *next;
28 	char **nameptr;
29 };
30 
31 static struct namerec *head, *tail;
32 
33 void
mf_namefixup_register(char ** ptr,const char * initval)34 mf_namefixup_register(char **ptr, const char *initval)
35 {
36 	struct namerec *nrec = mu_alloc(sizeof(*nrec));
37 	nrec->next = NULL;
38 	nrec->nameptr = ptr;
39 	*ptr = initval ? mu_strdup(initval) : NULL;
40 
41 	if (tail)
42 		tail->next = nrec;
43 	else
44 		head = nrec;
45 	tail = nrec;
46 }
47 
48 void
mf_file_name_ptr_fixup(char ** ptr,char * dir,size_t dirlen)49 mf_file_name_ptr_fixup(char **ptr, char *dir, size_t dirlen)
50 {
51 	if (*ptr && **ptr != '/') {
52 		char *name = *ptr;
53 		size_t olen = strlen(name);
54 		size_t flen = dirlen + 1 + olen + 1;
55 		char *p = mu_realloc(name, flen);
56 		memmove(p + dirlen + 1, p, olen + 1);
57 		memcpy(p, dir, dirlen);
58 		p[dirlen] = '/';
59 		*ptr = p;
60 	}
61 }
62 
63 void
mf_namefixup_run(char * dir)64 mf_namefixup_run(char *dir)
65 {
66 	size_t dirlen = strlen(dir);
67 	struct namerec *p;
68 
69 	for (p = head; p; p = p->next)
70 		mf_file_name_ptr_fixup(p->nameptr, dir, dirlen);
71 }
72 
73 void
mf_namefixup_free()74 mf_namefixup_free()
75 {
76 	struct namerec *p = head;
77 
78 	while (p) {
79 		struct namerec *next = p->next;
80 		free(p);
81 		p = next;
82 	}
83 }
84 
85 
86 
87