forked from neomutt/neomutt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.c
1703 lines (1485 loc) · 39.1 KB
/
file.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
* File management functions
*
* @authors
* Copyright (C) 2017 Richard Russon <[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 mutt_file File management functions
*
* Commonly used file/dir management routines.
*/
#include "config.h"
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <utime.h>
#include "config/lib.h"
#include "core/lib.h"
#include "file.h"
#include "buffer.h"
#include "date.h"
#include "logging.h"
#include "memory.h"
#include "message.h"
#include "path.h"
#include "pool.h"
#include "string2.h"
#ifdef USE_FLOCK
#include <sys/file.h>
#endif
/* these characters must be escaped in regular expressions */
static const char rx_special_chars[] = "^.[$()|*+?{\\";
const char filename_safe_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+@{}._-:%/";
#define MAX_LOCK_ATTEMPTS 5
/* This is defined in POSIX:2008 which isn't a build requirement */
#ifndef O_NOFOLLOW
#define O_NOFOLLOW 0
#endif
/**
* compare_stat - Compare the struct stat's of two files/dirs
* @param st_old struct stat of the first file/dir
* @param st_new struct stat of the second file/dir
* @retval true They match
*
* This compares the device id (st_dev), inode number (st_ino) and special id
* (st_rdev) of the files/dirs.
*/
static bool compare_stat(struct stat *st_old, struct stat *st_new)
{
return (st_old->st_dev == st_new->st_dev) && (st_old->st_ino == st_new->st_ino) &&
(st_old->st_rdev == st_new->st_rdev);
}
/**
* mkwrapdir - Create a temporary directory next to a file name
* @param path Existing filename
* @param newfile New filename
* @param newdir New directory name
* @retval 0 Success
* @retval -1 Error
*/
static int mkwrapdir(const char *path, struct Buffer *newfile, struct Buffer *newdir)
{
const char *basename = NULL;
int rc = 0;
struct Buffer parent = mutt_buffer_make(PATH_MAX);
mutt_buffer_strcpy(&parent, NONULL(path));
char *p = strrchr(parent.data, '/');
if (p)
{
*p = '\0';
basename = p + 1;
}
else
{
mutt_buffer_strcpy(&parent, ".");
basename = path;
}
mutt_buffer_printf(newdir, "%s/%s", mutt_buffer_string(&parent), ".muttXXXXXX");
if (!mkdtemp(newdir->data))
{
mutt_debug(LL_DEBUG1, "mkdtemp() failed\n");
rc = -1;
goto cleanup;
}
mutt_buffer_printf(newfile, "%s/%s", newdir->data, NONULL(basename));
cleanup:
mutt_buffer_dealloc(&parent);
return rc;
}
/**
* put_file_in_place - Move a file into place
* @param path Destination path
* @param safe_file Current filename
* @param safe_dir Current directory name
* @retval 0 Success
* @retval -1 Error, see errno
*/
static int put_file_in_place(const char *path, const char *safe_file, const char *safe_dir)
{
int rc;
rc = mutt_file_safe_rename(safe_file, path);
unlink(safe_file);
rmdir(safe_dir);
return rc;
}
/**
* mutt_file_fclose - Close a FILE handle (and NULL the pointer)
* @param[out] fp FILE handle to close
* @retval 0 Success
* @retval EOF Error, see errno
*/
int mutt_file_fclose(FILE **fp)
{
if (!fp || !*fp)
return 0;
int rc = fclose(*fp);
*fp = NULL;
return rc;
}
/**
* mutt_file_fsync_close - Flush the data, before closing a file (and NULL the pointer)
* @param[out] fp FILE handle to close
* @retval 0 Success
* @retval EOF Error, see errno
*/
int mutt_file_fsync_close(FILE **fp)
{
if (!fp || !*fp)
return 0;
int rc = 0;
if (fflush(*fp) || fsync(fileno(*fp)))
{
int save_errno = errno;
rc = -1;
mutt_file_fclose(fp);
errno = save_errno;
}
else
rc = mutt_file_fclose(fp);
return rc;
}
/**
* mutt_file_unlink - Delete a file, carefully
* @param s Filename
*
* This won't follow symlinks.
*/
void mutt_file_unlink(const char *s)
{
if (!s)
return;
struct stat st = { 0 };
/* Defend against symlink attacks */
const bool is_regular_file = (lstat(s, &st) == 0) && S_ISREG(st.st_mode);
if (!is_regular_file)
return;
const int fd = open(s, O_RDWR | O_NOFOLLOW);
if (fd < 0)
return;
struct stat st2 = { 0 };
if ((fstat(fd, &st2) != 0) || !S_ISREG(st2.st_mode) ||
(st.st_dev != st2.st_dev) || (st.st_ino != st2.st_ino))
{
close(fd);
return;
}
unlink(s);
close(fd);
}
/**
* mutt_file_copy_bytes - Copy some content from one file to another
* @param fp_in Source file
* @param fp_out Destination file
* @param size Maximum number of bytes to copy
* @retval 0 Success
* @retval -1 Error, see errno
*/
int mutt_file_copy_bytes(FILE *fp_in, FILE *fp_out, size_t size)
{
if (!fp_in || !fp_out)
return -1;
while (size > 0)
{
char buf[2048] = { 0 };
size_t chunk = (size > sizeof(buf)) ? sizeof(buf) : size;
chunk = fread(buf, 1, chunk, fp_in);
if (chunk < 1)
break;
if (fwrite(buf, 1, chunk, fp_out) != chunk)
return -1;
size -= chunk;
}
if (fflush(fp_out) != 0)
return -1;
return 0;
}
/**
* mutt_file_copy_stream - Copy the contents of one file into another
* @param fp_in Source file
* @param fp_out Destination file
* @retval n Success, number of bytes copied
* @retval -1 Error, see errno
*/
int mutt_file_copy_stream(FILE *fp_in, FILE *fp_out)
{
if (!fp_in || !fp_out)
return -1;
size_t total = 0;
size_t l;
char buf[1024] = { 0 };
while ((l = fread(buf, 1, sizeof(buf), fp_in)) > 0)
{
if (fwrite(buf, 1, l, fp_out) != l)
return -1;
total += l;
}
if (fflush(fp_out) != 0)
return -1;
return total;
}
/**
* mutt_file_symlink - Create a symlink
* @param oldpath Existing pathname
* @param newpath New pathname
* @retval 0 Success
* @retval -1 Error, see errno
*/
int mutt_file_symlink(const char *oldpath, const char *newpath)
{
struct stat st_old = { 0 };
struct stat st_new = { 0 };
if (!oldpath || !newpath)
return -1;
if ((unlink(newpath) == -1) && (errno != ENOENT))
return -1;
if (oldpath[0] == '/')
{
if (symlink(oldpath, newpath) == -1)
return -1;
}
else
{
struct Buffer abs_oldpath = mutt_buffer_make(PATH_MAX);
if (!mutt_path_getcwd(&abs_oldpath))
{
mutt_buffer_dealloc(&abs_oldpath);
return -1;
}
mutt_buffer_addch(&abs_oldpath, '/');
mutt_buffer_addstr(&abs_oldpath, oldpath);
if (symlink(mutt_buffer_string(&abs_oldpath), newpath) == -1)
{
mutt_buffer_dealloc(&abs_oldpath);
return -1;
}
mutt_buffer_dealloc(&abs_oldpath);
}
if ((stat(oldpath, &st_old) == -1) || (stat(newpath, &st_new) == -1) ||
!compare_stat(&st_old, &st_new))
{
unlink(newpath);
return -1;
}
return 0;
}
/**
* mutt_file_safe_rename - NFS-safe renaming of files
* @param src Original filename
* @param target New filename
* @retval 0 Success
* @retval -1 Error, see errno
*
* Warning: We don't check whether src and target are equal.
*/
int mutt_file_safe_rename(const char *src, const char *target)
{
struct stat st_src = { 0 };
struct stat st_target = { 0 };
int link_errno;
if (!src || !target)
return -1;
if (link(src, target) != 0)
{
link_errno = errno;
/* It is historically documented that link can return -1 if NFS
* dies after creating the link. In that case, we are supposed
* to use stat to check if the link was created.
*
* Derek Martin notes that some implementations of link() follow a
* source symlink. It might be more correct to use stat() on src.
* I am not doing so to minimize changes in behavior: the function
* used lstat() further below for 20 years without issue, and I
* believe was never intended to be used on a src symlink. */
if ((lstat(src, &st_src) == 0) && (lstat(target, &st_target) == 0) &&
(compare_stat(&st_src, &st_target) == 0))
{
mutt_debug(LL_DEBUG1, "link (%s, %s) reported failure: %s (%d) but actually succeeded\n",
src, target, strerror(errno), errno);
goto success;
}
errno = link_errno;
/* Coda does not allow cross-directory links, but tells
* us it's a cross-filesystem linking attempt.
*
* However, the Coda rename call is allegedly safe to use.
*
* With other file systems, rename should just fail when
* the files reside on different file systems, so it's safe
* to try it here. */
mutt_debug(LL_DEBUG1, "link (%s, %s) failed: %s (%d)\n", src, target,
strerror(errno), errno);
/* FUSE may return ENOSYS. VFAT may return EPERM. FreeBSD's
* msdosfs may return EOPNOTSUPP. ENOTSUP can also appear. */
if ((errno == EXDEV) || (errno == ENOSYS) || errno == EPERM
#ifdef ENOTSUP
|| errno == ENOTSUP
#endif
#ifdef EOPNOTSUPP
|| errno == EOPNOTSUPP
#endif
)
{
mutt_debug(LL_DEBUG1, "trying rename\n");
if (rename(src, target) == -1)
{
mutt_debug(LL_DEBUG1, "rename (%s, %s) failed: %s (%d)\n", src, target,
strerror(errno), errno);
return -1;
}
mutt_debug(LL_DEBUG1, "rename succeeded\n");
return 0;
}
return -1;
}
/* Remove the compare_stat() check, because it causes problems with maildir
* on filesystems that don't properly support hard links, such as sshfs. The
* filesystem creates the link, but the resulting file is given a different
* inode number by the sshfs layer. This results in an infinite loop
* creating links. */
#if 0
/* Stat both links and check if they are equal. */
if (lstat(src, &st_src) == -1)
{
mutt_debug(LL_DEBUG1, "#1 can't stat %s: %s (%d)\n", src, strerror(errno), errno);
return -1;
}
if (lstat(target, &st_target) == -1)
{
mutt_debug(LL_DEBUG1, "#2 can't stat %s: %s (%d)\n", src, strerror(errno), errno);
return -1;
}
/* pretend that the link failed because the target file did already exist. */
if (!compare_stat(&st_src, &st_target))
{
mutt_debug(LL_DEBUG1, "stat blocks for %s and %s diverge; pretending EEXIST\n", src, target);
errno = EEXIST;
return -1;
}
#endif
success:
/* Unlink the original link.
* Should we really ignore the return value here? XXX */
if (unlink(src) == -1)
{
mutt_debug(LL_DEBUG1, "unlink (%s) failed: %s (%d)\n", src, strerror(errno), errno);
}
return 0;
}
/**
* mutt_file_rmtree - Recursively remove a directory
* @param path Directory to delete
* @retval 0 Success
* @retval -1 Error, see errno
*/
int mutt_file_rmtree(const char *path)
{
if (!path)
return -1;
struct dirent *de = NULL;
struct stat st = { 0 };
int rc = 0;
DIR *dirp = opendir(path);
if (!dirp)
{
mutt_debug(LL_DEBUG1, "error opening directory %s\n", path);
return -1;
}
/* We avoid using the buffer pool for this function, because it
* invokes recursively to an unknown depth. */
struct Buffer cur = mutt_buffer_make(PATH_MAX);
while ((de = readdir(dirp)))
{
if ((strcmp(".", de->d_name) == 0) || (strcmp("..", de->d_name) == 0))
continue;
mutt_buffer_printf(&cur, "%s/%s", path, de->d_name);
/* XXX make nonrecursive version */
if (stat(mutt_buffer_string(&cur), &st) == -1)
{
rc = 1;
continue;
}
if (S_ISDIR(st.st_mode))
rc |= mutt_file_rmtree(mutt_buffer_string(&cur));
else
rc |= unlink(mutt_buffer_string(&cur));
}
closedir(dirp);
rc |= rmdir(path);
mutt_buffer_dealloc(&cur);
return rc;
}
/**
* mutt_file_rotate - Rotate a set of numbered files
* @param path Template filename
* @param count Maximum number of files
* @retval ptr Name of the 0'th file
*
* Given a template 'temp', rename files numbered 0 to (count-1).
*
* Rename:
* - ...
* - temp1 -> temp2
* - temp0 -> temp1
*/
const char *mutt_file_rotate(const char *path, int count)
{
if (!path)
return NULL;
struct Buffer *old_file = mutt_buffer_pool_get();
struct Buffer *new_file = mutt_buffer_pool_get();
/* rotate the old debug logs */
for (count -= 2; count >= 0; count--)
{
mutt_buffer_printf(old_file, "%s%d", path, count);
mutt_buffer_printf(new_file, "%s%d", path, count + 1);
(void) rename(mutt_buffer_string(old_file), mutt_buffer_string(new_file));
}
path = mutt_buffer_strdup(old_file);
mutt_buffer_pool_release(&old_file);
mutt_buffer_pool_release(&new_file);
return path;
}
/**
* mutt_file_open - Open a file
* @param path Pathname to open
* @param flags Flags, e.g. O_EXCL
* @retval >0 Success, file handle
* @retval -1 Error
*/
int mutt_file_open(const char *path, uint32_t flags)
{
if (!path)
return -1;
int fd;
struct Buffer safe_file = mutt_buffer_make(0);
struct Buffer safe_dir = mutt_buffer_make(0);
if (flags & O_EXCL)
{
mutt_buffer_alloc(&safe_file, PATH_MAX);
mutt_buffer_alloc(&safe_dir, PATH_MAX);
if (mkwrapdir(path, &safe_file, &safe_dir) == -1)
{
fd = -1;
goto cleanup;
}
fd = open(mutt_buffer_string(&safe_file), flags, 0600);
if (fd < 0)
{
rmdir(mutt_buffer_string(&safe_dir));
goto cleanup;
}
/* NFS and I believe cygwin do not handle movement of open files well */
close(fd);
if (put_file_in_place(path, mutt_buffer_string(&safe_file),
mutt_buffer_string(&safe_dir)) == -1)
{
fd = -1;
goto cleanup;
}
}
fd = open(path, flags & ~O_EXCL, 0600);
if (fd < 0)
goto cleanup;
/* make sure the file is not symlink */
struct stat st_old = { 0 };
struct stat st_new = { 0 };
if (((lstat(path, &st_old) < 0) || (fstat(fd, &st_new) < 0)) ||
!compare_stat(&st_old, &st_new))
{
close(fd);
fd = -1;
goto cleanup;
}
cleanup:
mutt_buffer_dealloc(&safe_file);
mutt_buffer_dealloc(&safe_dir);
return fd;
}
/**
* mutt_file_fopen - Call fopen() safely
* @param path Filename
* @param mode Mode e.g. "r" readonly; "w" read-write
* @retval ptr FILE handle
* @retval NULL Error, see errno
*
* When opening files for writing, make sure the file doesn't already exist to
* avoid race conditions.
*/
FILE *mutt_file_fopen(const char *path, const char *mode)
{
if (!path || !mode)
return NULL;
if (mode[0] == 'w')
{
uint32_t flags = O_CREAT | O_EXCL | O_NOFOLLOW;
if (mode[1] == '+')
flags |= O_RDWR;
else
flags |= O_WRONLY;
int fd = mutt_file_open(path, flags);
if (fd < 0)
return NULL;
return fdopen(fd, mode);
}
else
return fopen(path, mode);
}
/**
* mutt_file_sanitize_filename - Replace unsafe characters in a filename
* @param path Filename to make safe
* @param slash Replace '/' characters too
*/
void mutt_file_sanitize_filename(char *path, bool slash)
{
if (!path)
return;
for (; *path; path++)
{
if ((slash && (*path == '/')) || !strchr(filename_safe_chars, *path))
*path = '_';
}
}
/**
* mutt_file_sanitize_regex - Escape any regex-magic characters in a string
* @param dest Buffer for result
* @param src String to transform
* @retval 0 Success
* @retval -1 Error
*/
int mutt_file_sanitize_regex(struct Buffer *dest, const char *src)
{
if (!dest || !src)
return -1;
mutt_buffer_reset(dest);
while (*src != '\0')
{
if (strchr(rx_special_chars, *src))
mutt_buffer_addch(dest, '\\');
mutt_buffer_addch(dest, *src++);
}
return 0;
}
/**
* mutt_file_seek - Wrapper for fseeko with error handling
* @param[in] fp File to seek
* @param[in] offset Offset
* @param[in] whence Seek mode
* @retval true Seek was successful
* @retval false Seek failed
*/
bool mutt_file_seek(FILE *fp, LOFF_T offset, int whence)
{
if (!fp)
{
return false;
}
if (fseeko(fp, offset, whence) != 0)
{
mutt_perror(_("Failed to seek file: %s"), strerror(errno));
return false;
}
return true;
}
/**
* mutt_file_read_line - Read a line from a file
* @param[out] line Buffer allocated on the head (optional)
* @param[in] size Length of buffer
* @param[in] fp File to read
* @param[out] line_num Current line number (optional)
* @param[in] flags Flags, e.g. #MUTT_RL_CONT
* @retval ptr The allocated string
*
* Read a line from "fp" into the dynamically allocated "line", increasing
* "line" if necessary. The ending "\n" or "\r\n" is removed. If a line ends
* with "\", this char and the linefeed is removed, and the next line is read
* too.
*/
char *mutt_file_read_line(char *line, size_t *size, FILE *fp, int *line_num, ReadLineFlags flags)
{
if (!size || !fp)
return NULL;
size_t offset = 0;
char *ch = NULL;
if (!line)
{
*size = 256;
line = mutt_mem_malloc(*size);
}
while (true)
{
if (!fgets(line + offset, *size - offset, fp))
{
FREE(&line);
return NULL;
}
ch = strchr(line + offset, '\n');
if (ch)
{
if (line_num)
(*line_num)++;
if (flags & MUTT_RL_EOL)
return line;
*ch = '\0';
if ((ch > line) && (*(ch - 1) == '\r'))
*--ch = '\0';
if (!(flags & MUTT_RL_CONT) || (ch == line) || (*(ch - 1) != '\\'))
return line;
offset = ch - line - 1;
}
else
{
int c;
c = getc(fp); /* This is kind of a hack. We want to know if the
char at the current point in the input stream is EOF.
feof() will only tell us if we've already hit EOF, not
if the next character is EOF. So, we need to read in
the next character and manually check if it is EOF. */
if (c == EOF)
{
/* The last line of fp isn't \n terminated */
if (line_num)
(*line_num)++;
return line;
}
else
{
ungetc(c, fp); /* undo our damage */
/* There wasn't room for the line -- increase "line" */
offset = *size - 1; /* overwrite the terminating 0 */
*size += 256;
mutt_mem_realloc(&line, *size);
}
}
}
}
/**
* mutt_file_iter_line - Iterate over the lines from an open file pointer
* @param iter State of iteration including ptr to line
* @param fp File pointer to read from
* @param flags Same as mutt_file_read_line()
* @retval true Data read
* @retval false On eof
*
* This is a slightly cleaner interface for mutt_file_read_line() which avoids
* the eternal C loop initialization ugliness. Use like this:
*
* ```
* struct MuttFileIter iter = { 0 };
* while (mutt_file_iter_line(&iter, fp, flags))
* {
* do_stuff(iter.line, iter.line_num);
* }
* ```
*/
bool mutt_file_iter_line(struct MuttFileIter *iter, FILE *fp, ReadLineFlags flags)
{
if (!iter)
return false;
char *p = mutt_file_read_line(iter->line, &iter->size, fp, &iter->line_num, flags);
if (!p)
return false;
iter->line = p;
return true;
}
/**
* mutt_file_map_lines - Process lines of text read from a file pointer
* @param func Callback function to call for each line, see mutt_file_map_t
* @param user_data Arbitrary data passed to "func"
* @param fp File pointer to read from
* @param flags Same as mutt_file_read_line()
* @retval true All data mapped
* @retval false "func" returns false
*/
bool mutt_file_map_lines(mutt_file_map_t func, void *user_data, FILE *fp, ReadLineFlags flags)
{
if (!func || !fp)
return false;
struct MuttFileIter iter = { 0 };
while (mutt_file_iter_line(&iter, fp, flags))
{
if (!(*func)(iter.line, iter.line_num, user_data))
{
FREE(&iter.line);
return false;
}
}
return true;
}
/**
* mutt_file_quote_filename - Quote a filename to survive the shell's quoting rules
* @param filename String to convert
* @param buf Buffer for the result
* @param buflen Length of buffer
* @retval num Bytes written to the buffer
*
* From the Unix programming FAQ by way of Liviu.
*/
size_t mutt_file_quote_filename(const char *filename, char *buf, size_t buflen)
{
if (!buf)
return 0;
if (!filename)
{
*buf = '\0';
return 0;
}
size_t j = 0;
/* leave some space for the trailing characters. */
buflen -= 6;
buf[j++] = '\'';
for (size_t i = 0; (j < buflen) && filename[i]; i++)
{
if ((filename[i] == '\'') || (filename[i] == '`'))
{
buf[j++] = '\'';
buf[j++] = '\\';
buf[j++] = filename[i];
buf[j++] = '\'';
}
else
buf[j++] = filename[i];
}
buf[j++] = '\'';
buf[j] = '\0';
return j;
}
/**
* mutt_buffer_quote_filename - Quote a filename to survive the shell's quoting rules
* @param buf Buffer for the result
* @param filename String to convert
* @param add_outer If true, add 'single quotes' around the result
*/
void mutt_buffer_quote_filename(struct Buffer *buf, const char *filename, bool add_outer)
{
if (!buf || !filename)
return;
mutt_buffer_reset(buf);
if (add_outer)
mutt_buffer_addch(buf, '\'');
for (; *filename != '\0'; filename++)
{
if ((*filename == '\'') || (*filename == '`'))
{
mutt_buffer_addch(buf, '\'');
mutt_buffer_addch(buf, '\\');
mutt_buffer_addch(buf, *filename);
mutt_buffer_addch(buf, '\'');
}
else
mutt_buffer_addch(buf, *filename);
}
if (add_outer)
mutt_buffer_addch(buf, '\'');
}
/**
* mutt_file_mkdir - Recursively create directories
* @param path Directories to create
* @param mode Permissions for final directory
* @retval 0 Success
* @retval -1 Error (errno set)
*
* Create a directory, creating the parents if necessary. (like mkdir -p)
*
* @note The permissions are only set on the final directory.
* The permissions of any parent directories are determined by the umask.
* (This is how "mkdir -p" behaves)
*/
int mutt_file_mkdir(const char *path, mode_t mode)
{
if (!path || (*path == '\0'))
{
errno = EINVAL;
return -1;
}
errno = 0;
char tmp_path[PATH_MAX] = { 0 };
const size_t len = strlen(path);
if (len >= sizeof(tmp_path))
{
errno = ENAMETOOLONG;
return -1;
}
struct stat st = { 0 };
if ((stat(path, &st) == 0) && S_ISDIR(st.st_mode))
return 0;
/* Create a mutable copy */
mutt_str_copy(tmp_path, path, sizeof(tmp_path));
for (char *p = tmp_path + 1; *p; p++)
{
if (*p != '/')
continue;
/* Temporarily truncate the path */
*p = '\0';
if ((mkdir(tmp_path, S_IRWXU | S_IRWXG | S_IRWXO) != 0) && (errno != EEXIST))
return -1;
*p = '/';
}
if ((mkdir(tmp_path, mode) != 0) && (errno != EEXIST))
return -1;
return 0;
}
/**
* mutt_file_mkstemp_full - Create temporary file safely
* @param file Source file of caller
* @param line Source line number of caller
* @param func Function name of caller
* @retval ptr FILE handle
* @retval NULL Error, see errno
*
* Create and immediately unlink a temp file using mkstemp().
*/
FILE *mutt_file_mkstemp_full(const char *file, int line, const char *func)
{
char name[PATH_MAX] = { 0 };
const char *const c_tmpdir = cs_subset_path(NeoMutt->sub, "tmpdir");
int n = snprintf(name, sizeof(name), "%s/neomutt-XXXXXX", NONULL(c_tmpdir));
if (n < 0)
return NULL;
int fd = mkstemp(name);
if (fd == -1)
return NULL;
FILE *fp = fdopen(fd, "w+");
if ((unlink(name) != 0) && (errno != ENOENT))