forked from neomutt/neomutt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmuttlib.c
1844 lines (1675 loc) · 47.6 KB
/
muttlib.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file
* Some miscellaneous functions
*
* @authors
* Copyright (C) 1996-2000,2007,2010,2013 Michael R. Elkins <[email protected]>
* Copyright (C) 1999-2008 Thomas Roessler <[email protected]>
* Copyright (C) 2019 Pietro Cerutti <[email protected]>
*
* @copyright
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @page muttlib Some miscellaneous functions
*
* Some miscellaneous functions
*/
#include "config.h"
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <pwd.h>
#include <regex.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "mutt/mutt.h"
#include "address/lib.h"
#include "config/lib.h"
#include "email/lib.h"
#include "core/lib.h"
#include "gui/lib.h"
#include "mutt.h"
#include "muttlib.h"
#include "alias.h"
#include "format_flags.h"
#include "globals.h"
#include "hook.h"
#include "mx.h"
#include "ncrypt/ncrypt.h"
#include "protos.h"
#if defined(HAVE_SYSCALL_H)
#include <syscall.h>
#elif defined(HAVE_SYS_SYSCALL_H)
#include <sys/syscall.h>
#endif
#ifdef USE_IMAP
#include "imap/imap.h"
#endif
/* These Config Variables are only used in muttlib.c */
struct Regex *C_GecosMask; ///< Config: Regex for parsing GECOS field of /etc/passwd
static FILE *fp_random;
static const unsigned char base32[] = "abcdefghijklmnopqrstuvwxyz234567";
static const char *xdg_env_vars[] = {
[XDG_CONFIG_HOME] = "XDG_CONFIG_HOME",
[XDG_CONFIG_DIRS] = "XDG_CONFIG_DIRS",
};
static const char *xdg_defaults[] = {
[XDG_CONFIG_HOME] = "~/.config",
[XDG_CONFIG_DIRS] = "/etc/xdg",
};
/**
* mutt_adv_mktemp - Create a temporary file
* @param buf Buffer for the name
*
* Accept a "suggestion" for file name. If that file exists, then
* construct one with unique name but keep any extension.
* This might fail, I guess.
*/
void mutt_adv_mktemp(struct Buffer *buf)
{
if (!(buf->data && buf->data[0]))
{
mutt_buffer_mktemp(buf);
}
else
{
struct Buffer *prefix = mutt_buffer_pool_get();
mutt_buffer_strcpy(prefix, buf->data);
mutt_file_sanitize_filename(prefix->data, true);
mutt_buffer_printf(buf, "%s/%s", NONULL(C_Tmpdir), mutt_b2s(prefix));
struct stat sb;
if ((lstat(mutt_b2s(buf), &sb) == -1) && (errno == ENOENT))
goto out;
char *suffix = strchr(prefix->data, '.');
if (suffix)
{
*suffix = '\0';
suffix++;
}
mutt_buffer_mktemp_pfx_sfx(buf, prefix->data, suffix);
out:
mutt_buffer_pool_release(&prefix);
}
}
/**
* mutt_expand_path - Create the canonical path
* @param buf Buffer with path
* @param buflen Length of buffer
* @retval ptr The expanded string
*
* @note The path is expanded in-place
*/
char *mutt_expand_path(char *buf, size_t buflen)
{
return mutt_expand_path_regex(buf, buflen, false);
}
/**
* mutt_buffer_expand_path_regex - Create the canonical path (with regex char escaping)
* @param buf Buffer with path
* @param regex If true, escape any regex characters
*
* @note The path is expanded in-place
*/
void mutt_buffer_expand_path_regex(struct Buffer *buf, bool regex)
{
const char *s = NULL;
const char *tail = "";
bool recurse = false;
struct Buffer *p = mutt_buffer_pool_get();
struct Buffer *q = mutt_buffer_pool_get();
struct Buffer *tmp = mutt_buffer_pool_get();
do
{
recurse = false;
s = mutt_b2s(buf);
switch (*s)
{
case '~':
{
if ((s[1] == '/') || (s[1] == '\0'))
{
mutt_buffer_strcpy(p, HomeDir);
tail = s + 1;
}
else
{
char *t = strchr(s + 1, '/');
if (t)
*t = '\0';
struct passwd *pw = getpwnam(s + 1);
if (pw)
{
mutt_buffer_strcpy(p, pw->pw_dir);
if (t)
{
*t = '/';
tail = t;
}
else
tail = "";
}
else
{
/* user not found! */
if (t)
*t = '/';
mutt_buffer_reset(p);
tail = s;
}
}
break;
}
case '=':
case '+':
{
enum MailboxType mb_type = mx_path_probe(C_Folder, NULL);
/* if folder = {host} or imap[s]://host/: don't append slash */
if ((mb_type == MUTT_IMAP) && ((C_Folder[strlen(C_Folder) - 1] == '}') ||
(C_Folder[strlen(C_Folder) - 1] == '/')))
{
mutt_buffer_strcpy(p, NONULL(C_Folder));
}
else if (mb_type == MUTT_NOTMUCH)
mutt_buffer_strcpy(p, NONULL(C_Folder));
else if (C_Folder && (C_Folder[strlen(C_Folder) - 1] == '/'))
mutt_buffer_strcpy(p, NONULL(C_Folder));
else
mutt_buffer_printf(p, "%s/", NONULL(C_Folder));
tail = s + 1;
break;
}
/* elm compatibility, @ expands alias to user name */
case '@':
{
struct AddressList *al = mutt_alias_lookup(s + 1);
if (!TAILQ_EMPTY(al))
{
struct Email *e = email_new();
e->env = mutt_env_new();
mutt_addrlist_copy(&e->env->from, al, false);
mutt_addrlist_copy(&e->env->to, al, false);
/* TODO: fix mutt_default_save() to use Buffer */
mutt_buffer_alloc(p, PATH_MAX);
mutt_default_save(p->data, p->dsize, e);
mutt_buffer_fix_dptr(p);
email_free(&e);
/* Avoid infinite recursion if the resulting folder starts with '@' */
if (*p->data != '@')
recurse = true;
tail = "";
}
break;
}
case '>':
{
mutt_buffer_strcpy(p, C_Mbox);
tail = s + 1;
break;
}
case '<':
{
mutt_buffer_strcpy(p, C_Record);
tail = s + 1;
break;
}
case '!':
{
if (s[1] == '!')
{
mutt_buffer_strcpy(p, LastFolder);
tail = s + 2;
}
else
{
mutt_buffer_strcpy(p, C_Spoolfile);
tail = s + 1;
}
break;
}
case '-':
{
mutt_buffer_strcpy(p, LastFolder);
tail = s + 1;
break;
}
case '^':
{
mutt_buffer_strcpy(p, CurrentFolder);
tail = s + 1;
break;
}
default:
{
mutt_buffer_reset(p);
tail = s;
}
}
if (regex && *(mutt_b2s(p)) && !recurse)
{
mutt_file_sanitize_regex(q, mutt_b2s(p));
mutt_buffer_printf(tmp, "%s%s", mutt_b2s(q), tail);
}
else
mutt_buffer_printf(tmp, "%s%s", mutt_b2s(p), tail);
mutt_buffer_copy(buf, tmp);
} while (recurse);
mutt_buffer_pool_release(&p);
mutt_buffer_pool_release(&q);
mutt_buffer_pool_release(&tmp);
#ifdef USE_IMAP
/* Rewrite IMAP path in canonical form - aids in string comparisons of
* folders. May possibly fail, in which case buf should be the same. */
if (imap_path_probe(mutt_b2s(buf), NULL) == MUTT_IMAP)
imap_expand_path(buf);
else
#endif
{
/* Resolve symbolic links */
struct stat st;
int rc = lstat(mutt_b2s(buf), &st);
if ((rc != -1) && S_ISLNK(st.st_mode))
{
char path[PATH_MAX];
if (realpath(mutt_b2s(buf), path))
{
mutt_buffer_strcpy(buf, path);
}
}
}
}
/**
* mutt_buffer_expand_path - Create the canonical path
* @param buf Buffer with path
*
* @note The path is expanded in-place
*/
void mutt_buffer_expand_path(struct Buffer *buf)
{
mutt_buffer_expand_path_regex(buf, false);
}
/**
* mutt_expand_path_regex - Create the canonical path (with regex char escaping)
* @param buf Buffer with path
* @param buflen Length of buffer
* @param regex If true, escape any regex characters
* @retval ptr The expanded string
*
* @note The path is expanded in-place
*/
char *mutt_expand_path_regex(char *buf, size_t buflen, bool regex)
{
struct Buffer *tmp = mutt_buffer_pool_get();
mutt_buffer_addstr(tmp, NONULL(buf));
mutt_buffer_expand_path_regex(tmp, regex);
mutt_str_strfcpy(buf, mutt_b2s(tmp), buflen);
mutt_buffer_pool_release(&tmp);
return buf;
}
/**
* mutt_gecos_name - Lookup a user's real name in /etc/passwd
* @param dest Buffer for the result
* @param destlen Length of buffer
* @param pw Passwd entry
* @retval ptr Result buffer on success
*
* Extract the real name from /etc/passwd's GECOS field. When set, honor the
* regular expression in #C_GecosMask, otherwise assume that the GECOS field is a
* comma-separated list.
* Replace "&" by a capitalized version of the user's login name.
*/
char *mutt_gecos_name(char *dest, size_t destlen, struct passwd *pw)
{
regmatch_t pat_match[1];
size_t pwnl;
char *p = NULL;
if (!pw || !pw->pw_gecos)
return NULL;
memset(dest, 0, destlen);
if (mutt_regex_capture(C_GecosMask, pw->pw_gecos, 1, pat_match))
{
mutt_str_strfcpy(dest, pw->pw_gecos + pat_match[0].rm_so,
MIN(pat_match[0].rm_eo - pat_match[0].rm_so + 1, destlen));
}
else if ((p = strchr(pw->pw_gecos, ',')))
mutt_str_strfcpy(dest, pw->pw_gecos, MIN(destlen, p - pw->pw_gecos + 1));
else
mutt_str_strfcpy(dest, pw->pw_gecos, destlen);
pwnl = strlen(pw->pw_name);
for (int idx = 0; dest[idx]; idx++)
{
if (dest[idx] == '&')
{
memmove(&dest[idx + pwnl], &dest[idx + 1],
MAX((ssize_t)(destlen - idx - pwnl - 1), 0));
memcpy(&dest[idx], pw->pw_name, MIN(destlen - idx - 1, pwnl));
dest[idx] = toupper((unsigned char) dest[idx]);
}
}
return dest;
}
/**
* mutt_needs_mailcap - Does this type need a mailcap entry do display
* @param m Attachment body to be displayed
* @retval true NeoMutt requires a mailcap entry to display
* @retval false otherwise
*/
bool mutt_needs_mailcap(struct Body *m)
{
switch (m->type)
{
case TYPE_TEXT:
if (mutt_str_strcasecmp("plain", m->subtype) == 0)
return false;
break;
case TYPE_APPLICATION:
if (((WithCrypto & APPLICATION_PGP) != 0) && mutt_is_application_pgp(m))
return false;
if (((WithCrypto & APPLICATION_SMIME) != 0) && mutt_is_application_smime(m))
return false;
break;
case TYPE_MULTIPART:
case TYPE_MESSAGE:
return false;
}
return true;
}
/**
* mutt_is_text_part - Is this part of an email in plain text?
* @param b Part of an email
* @retval true If part is in plain text
*/
bool mutt_is_text_part(struct Body *b)
{
int t = b->type;
char *s = b->subtype;
if (((WithCrypto & APPLICATION_PGP) != 0) && mutt_is_application_pgp(b))
return false;
if (t == TYPE_TEXT)
return true;
if (t == TYPE_MESSAGE)
{
if (mutt_str_strcasecmp("delivery-status", s) == 0)
return true;
}
if (((WithCrypto & APPLICATION_PGP) != 0) && (t == TYPE_APPLICATION))
{
if (mutt_str_strcasecmp("pgp-keys", s) == 0)
return true;
}
return false;
}
/**
* mutt_randbuf - Fill a buffer with randomness
* @param buf Buffer for result
* @param buflen Size of buffer
* @retval 0 Success
* @retval -1 Error
*/
int mutt_randbuf(void *buf, size_t buflen)
{
if (buflen > 1048576)
{
mutt_error(_("mutt_randbuf buflen=%zu"), buflen);
return -1;
}
/* XXX switch to HAVE_GETRANDOM and getrandom() in about 2017 */
#if defined(SYS_getrandom) && defined(__linux__)
long ret;
do
{
ret = syscall(SYS_getrandom, buf, buflen, 0, 0, 0, 0);
} while ((ret == -1) && (errno == EINTR));
if (ret == buflen)
return 0;
#endif
/* let's try urandom in case we're on an old kernel, or the user has
* configured selinux, seccomp or something to not allow getrandom */
if (!fp_random)
{
fp_random = fopen("/dev/urandom", "rb");
if (!fp_random)
{
mutt_error(_("open /dev/urandom: %s"), strerror(errno));
return -1;
}
setbuf(fp_random, NULL);
}
if (fread(buf, 1, buflen, fp_random) != buflen)
{
mutt_error(_("read /dev/urandom: %s"), strerror(errno));
return -1;
}
return 0;
}
/**
* mutt_rand_base32 - Fill a buffer with a base32-encoded random string
* @param buf Buffer for result
* @param buflen Length of buffer
*/
void mutt_rand_base32(void *buf, size_t buflen)
{
uint8_t *p = buf;
if (mutt_randbuf(p, buflen) < 0)
mutt_exit(1);
for (size_t pos = 0; pos < buflen; pos++)
p[pos] = base32[p[pos] % 32];
}
/**
* mutt_rand32 - Create a 32-bit random number
* @retval num Random number
*/
uint32_t mutt_rand32(void)
{
uint32_t num = 0;
if (mutt_randbuf(&num, sizeof(num)) < 0)
mutt_exit(1);
return num;
}
/**
* mutt_rand64 - Create a 64-bit random number
* @retval num Random number
*/
uint64_t mutt_rand64(void)
{
uint64_t num = 0;
if (mutt_randbuf(&num, sizeof(num)) < 0)
mutt_exit(1);
return num;
}
/**
* mutt_buffer_mktemp_full - Create a temporary file
* @param buf Buffer for result
* @param prefix Prefix for filename
* @param suffix Suffix for filename
* @param src Source file of caller
* @param line Source line number of caller
*/
void mutt_buffer_mktemp_full(struct Buffer *buf, const char *prefix,
const char *suffix, const char *src, int line)
{
mutt_buffer_printf(buf, "%s/%s-%s-%d-%d-%" PRIu64 "%s%s", NONULL(C_Tmpdir),
NONULL(prefix), NONULL(ShortHostname), (int) getuid(),
(int) getpid(), mutt_rand64(), suffix ? "." : "", NONULL(suffix));
mutt_debug(LL_DEBUG3, "%s:%d: mutt_mktemp returns \"%s\"\n", src, line, mutt_b2s(buf));
if (unlink(mutt_b2s(buf)) && (errno != ENOENT))
{
mutt_debug(LL_DEBUG1, "%s:%d: ERROR: unlink(\"%s\"): %s (errno %d)\n", src,
line, mutt_b2s(buf), strerror(errno), errno);
}
}
/**
* mutt_mktemp_full - Create a temporary filename
* @param buf Buffer for result
* @param buflen Length of buffer
* @param prefix Prefix for filename
* @param suffix Suffix for filename
* @param src Source file of caller
* @param line Source line number of caller
*
* @note This doesn't create the file, only the name
*/
void mutt_mktemp_full(char *buf, size_t buflen, const char *prefix,
const char *suffix, const char *src, int line)
{
size_t n =
snprintf(buf, buflen, "%s/%s-%s-%d-%d-%" PRIu64 "%s%s", NONULL(C_Tmpdir),
NONULL(prefix), NONULL(ShortHostname), (int) getuid(),
(int) getpid(), mutt_rand64(), suffix ? "." : "", NONULL(suffix));
if (n >= buflen)
{
mutt_debug(LL_DEBUG1,
"%s:%d: ERROR: insufficient buffer space to hold temporary "
"filename! buflen=%zu but need %zu\n",
src, line, buflen, n);
}
mutt_debug(LL_DEBUG3, "%s:%d: mutt_mktemp returns \"%s\"\n", src, line, buf);
if (unlink(buf) && (errno != ENOENT))
{
mutt_debug(LL_DEBUG1, "%s:%d: ERROR: unlink(\"%s\"): %s (errno %d)\n", src,
line, buf, strerror(errno), errno);
}
}
/**
* mutt_pretty_mailbox - Shorten a mailbox path using '~' or '='
* @param buf Buffer containing string to shorten
* @param buflen Length of buffer
*
* Collapse the pathname using ~ or = when possible
*/
void mutt_pretty_mailbox(char *buf, size_t buflen)
{
if (!buf)
return;
char *p = buf, *q = buf;
size_t len;
enum UrlScheme scheme;
char tmp[PATH_MAX];
scheme = url_check_scheme(buf);
if ((scheme == U_IMAP) || (scheme == U_IMAPS))
{
imap_pretty_mailbox(buf, buflen, C_Folder);
return;
}
if (scheme == U_NOTMUCH)
return;
/* if buf is an url, only collapse path component */
if (scheme != U_UNKNOWN)
{
p = strchr(buf, ':') + 1;
if (strncmp(p, "//", 2) == 0)
q = strchr(p + 2, '/');
if (!q)
q = strchr(p, '\0');
p = q;
}
/* cleanup path */
if (strstr(p, "//") || strstr(p, "/./"))
{
/* first attempt to collapse the pathname, this is more
* lightweight than realpath() and doesn't resolve links */
while (*p)
{
if ((p[0] == '/') && (p[1] == '/'))
{
*q++ = '/';
p += 2;
}
else if ((p[0] == '/') && (p[1] == '.') && (p[2] == '/'))
{
*q++ = '/';
p += 3;
}
else
*q++ = *p++;
}
*q = '\0';
}
else if (strstr(p, "..") && ((scheme == U_UNKNOWN) || (scheme == U_FILE)) &&
realpath(p, tmp))
{
mutt_str_strfcpy(p, tmp, buflen - (p - buf));
}
if ((len = mutt_str_startswith(buf, C_Folder, CASE_MATCH)) && (buf[len] == '/'))
{
*buf++ = '=';
memmove(buf, buf + len, mutt_str_strlen(buf + len) + 1);
}
else if ((len = mutt_str_startswith(buf, HomeDir, CASE_MATCH)) && (buf[len] == '/'))
{
*buf++ = '~';
memmove(buf, buf + len - 1, mutt_str_strlen(buf + len - 1) + 1);
}
}
/**
* mutt_buffer_pretty_mailbox - Shorten a mailbox path using '~' or '='
* @param buf Buffer containing Mailbox name
*/
void mutt_buffer_pretty_mailbox(struct Buffer *buf)
{
if (!buf || !buf->data)
return;
/* This reduces the size of the Buffer, so we can pass it through.
* We adjust the size just to make sure buf->data is not NULL though */
mutt_buffer_alloc(buf, PATH_MAX);
mutt_pretty_mailbox(buf->data, buf->dsize);
mutt_buffer_fix_dptr(buf);
}
/**
* mutt_check_overwrite - Ask the user if overwriting is necessary
* @param[in] attname Attachment name
* @param[in] path Path to save the file
* @param[out] fname Buffer for filename
* @param[out] opt Save option, see #SaveAttach
* @param[out] directory Directory to save under (OPTIONAL)
* @retval 0 Success
* @retval -1 Abort
* @retval 1 Error
*/
int mutt_check_overwrite(const char *attname, const char *path, struct Buffer *fname,
enum SaveAttach *opt, char **directory)
{
struct stat st;
mutt_buffer_strcpy(fname, path);
if (access(mutt_b2s(fname), F_OK) != 0)
return 0;
if (stat(mutt_b2s(fname), &st) != 0)
return -1;
if (S_ISDIR(st.st_mode))
{
enum QuadOption ans = MUTT_NO;
if (directory)
{
switch (mutt_multi_choice
/* L10N: Means "The path you specified as the destination file is a directory."
See the msgid "Save to file: " (alias.c, recvattach.c)
These three letters correspond to the choices in the string. */
(_("File is a directory, save under it: (y)es, (n)o, (a)ll?"), _("yna")))
{
case 3: /* all */
mutt_str_replace(directory, mutt_b2s(fname));
break;
case 1: /* yes */
FREE(directory);
break;
case -1: /* abort */
FREE(directory);
return -1;
case 2: /* no */
FREE(directory);
return 1;
}
}
/* L10N: Means "The path you specified as the destination file is a directory."
See the msgid "Save to file: " (alias.c, recvattach.c) */
else if ((ans = mutt_yesorno(_("File is a directory, save under it?"), MUTT_YES)) != MUTT_YES)
return (ans == MUTT_NO) ? 1 : -1;
struct Buffer *tmp = mutt_buffer_pool_get();
mutt_buffer_strcpy(tmp, mutt_path_basename(NONULL(attname)));
if ((mutt_buffer_get_field(_("File under directory: "), tmp, MUTT_FILE | MUTT_CLEAR) != 0) ||
mutt_buffer_is_empty(tmp))
{
mutt_buffer_pool_release(&tmp);
return (-1);
}
mutt_buffer_concat_path(fname, path, mutt_b2s(tmp));
mutt_buffer_pool_release(&tmp);
}
if ((*opt == MUTT_SAVE_NO_FLAGS) && (access(mutt_b2s(fname), F_OK) == 0))
{
switch (
mutt_multi_choice(_("File exists, (o)verwrite, (a)ppend, or (c)ancel?"),
// L10N: Options for: File exists, (o)verwrite, (a)ppend, or (c)ancel?
_("oac")))
{
case -1: /* abort */
return -1;
case 3: /* cancel */
return 1;
case 2: /* append */
*opt = MUTT_SAVE_APPEND;
break;
case 1: /* overwrite */
*opt = MUTT_SAVE_OVERWRITE;
break;
}
}
return 0;
}
/**
* mutt_save_path - Turn an email address into a filename (for saving)
* @param buf Buffer for the result
* @param buflen Length of buffer
* @param addr Email address to use
*
* If the user hasn't set `$save_address` the name will be truncated to the '@'
* character.
*/
void mutt_save_path(char *buf, size_t buflen, const struct Address *addr)
{
if (addr && addr->mailbox)
{
mutt_str_strfcpy(buf, addr->mailbox, buflen);
if (!C_SaveAddress)
{
char *p = strpbrk(buf, "%@");
if (p)
*p = '\0';
}
mutt_str_strlower(buf);
}
else
*buf = '\0';
}
/**
* mutt_buffer_save_path - Make a safe filename from an email address
* @param dest Buffer for the result
* @param a Address to use
*/
void mutt_buffer_save_path(struct Buffer *dest, const struct Address *a)
{
if (a && a->mailbox)
{
mutt_buffer_strcpy(dest, a->mailbox);
if (!C_SaveAddress)
{
char *p = strpbrk(dest->data, "%@");
if (p)
{
*p = '\0';
mutt_buffer_fix_dptr(dest);
}
}
mutt_str_strlower(dest->data);
}
else
mutt_buffer_reset(dest);
}
/**
* mutt_safe_path - Make a safe filename from an email address
* @param dest Buffer for the result
* @param a Address to use
*
* The filename will be stripped of '/', space, etc to make it safe.
*/
void mutt_safe_path(struct Buffer *dest, const struct Address *a)
{
mutt_buffer_save_path(dest, a);
for (char *p = dest->data; *p; p++)
if ((*p == '/') || IS_SPACE(*p) || !IsPrint((unsigned char) *p))
*p = '_';
}
/**
* mutt_expando_format - Expand expandos (%x) in a string
* @param[out] buf Buffer in which to save string
* @param[in] buflen Buffer length
* @param[in] col Starting column
* @param[in] cols Number of screen columns
* @param[in] src Printf-like format string
* @param[in] callback Callback - Implements ::format_t
* @param[in] data Callback data
* @param[in] flags Callback flags
*/
void mutt_expando_format(char *buf, size_t buflen, size_t col, int cols, const char *src,
format_t *callback, unsigned long data, MuttFormatFlags flags)
{
char prefix[128], tmp[1024];
char *cp = NULL, *wptr = buf;
char ch;
char if_str[128], else_str[128];
size_t wlen, count, len, wid;
FILE *fp_filter = NULL;
char *recycler = NULL;
char src2[256];
mutt_str_strfcpy(src2, src, mutt_str_strlen(src) + 1);
src = src2;
prefix[0] = '\0';
buflen--; /* save room for the terminal \0 */
wlen = ((flags & MUTT_FORMAT_ARROWCURSOR) && C_ArrowCursor) ? 3 : 0;
col += wlen;
if ((flags & MUTT_FORMAT_NOFILTER) == 0)
{
int off = -1;
/* Do not consider filters if no pipe at end */
int n = mutt_str_strlen(src);
if ((n > 1) && (src[n - 1] == '|'))
{
/* Scan backwards for backslashes */
off = n;
while ((off > 0) && (src[off - 2] == '\\'))
off--;
}
/* If number of backslashes is even, the pipe is real. */
/* n-off is the number of backslashes. */
if ((off > 0) && (((n - off) % 2) == 0))
{
char srccopy[1024];
int i = 0;
mutt_debug(LL_DEBUG3, "fmtpipe = %s\n", src);
strncpy(srccopy, src, n);
srccopy[n - 1] = '\0';
/* prepare Buffers */
struct Buffer srcbuf = mutt_buffer_make(0);
mutt_buffer_addstr(&srcbuf, srccopy);
/* note: we are resetting dptr and *reading* from the buffer, so we don't
* want to use mutt_buffer_reset(). */
srcbuf.dptr = srcbuf.data;
struct Buffer word = mutt_buffer_make(0);
struct Buffer cmd = mutt_buffer_make(0);
/* Iterate expansions across successive arguments */
do
{
/* Extract the command name and copy to command line */
mutt_debug(LL_DEBUG3, "fmtpipe +++: %s\n", srcbuf.dptr);
if (word.data)
*word.data = '\0';
mutt_extract_token(&word, &srcbuf, MUTT_TOKEN_NO_FLAGS);
mutt_debug(LL_DEBUG3, "fmtpipe %2d: %s\n", i++, word.data);
mutt_buffer_addch(&cmd, '\'');
mutt_expando_format(tmp, sizeof(tmp), 0, cols, word.data, callback,
data, flags | MUTT_FORMAT_NOFILTER);
for (char *p = tmp; p && *p; p++)
{
if (*p == '\'')
{
/* shell quoting doesn't permit escaping a single quote within
* single-quoted material. double-quoting instead will lead
* shell variable expansions, so break out of the single-quoted
* span, insert a double-quoted single quote, and resume. */
mutt_buffer_addstr(&cmd, "'\"'\"'");
}
else
mutt_buffer_addch(&cmd, *p);
}
mutt_buffer_addch(&cmd, '\'');
mutt_buffer_addch(&cmd, ' ');
} while (MoreArgs(&srcbuf));
mutt_debug(LL_DEBUG3, "fmtpipe > %s\n", cmd.data);
col -= wlen; /* reset to passed in value */
wptr = buf; /* reset write ptr */
pid_t pid = filter_create(cmd.data, NULL, &fp_filter, NULL);
if (pid != -1)
{
int rc;
n = fread(buf, 1, buflen /* already decremented */, fp_filter);
mutt_file_fclose(&fp_filter);
rc = filter_wait(pid);
if (rc != 0)
mutt_debug(LL_DEBUG1, "format pipe cmd exited code %d\n", rc);
if (n > 0)
{
buf[n] = '\0';
while ((n > 0) && ((buf[n - 1] == '\n') || (buf[n - 1] == '\r')))
buf[--n] = '\0';
mutt_debug(LL_DEBUG5, "fmtpipe < %s\n", buf);
/* If the result ends with '%', this indicates that the filter
* generated %-tokens that neomutt can expand. Eliminate the '%'
* marker and recycle the string through mutt_expando_format().
* To literally end with "%", use "%%". */
if ((n > 0) && (buf[n - 1] == '%'))
{
n--;
buf[n] = '\0'; /* remove '%' */
if ((n > 0) && (buf[n - 1] != '%'))
{
recycler = mutt_str_strdup(buf);
if (recycler)
{
/* buflen is decremented at the start of this function
* to save space for the terminal nul char. We can add
* it back for the recursive call since the expansion of
* format pipes does not try to append a nul itself. */
mutt_expando_format(buf, buflen + 1, col, cols, recycler,
callback, data, flags);
FREE(&recycler);