1 /* $OpenBSD: fileio.c,v 1.94 2012/07/10 06:28:12 lum Exp $ */
3 /* This file is in the public domain. */
10 #include <sys/types.h>
13 #include <sys/resource.h>
24 #include "pathnames.h"
26 static char *bkuplocation(const char *);
27 static int bkupleavetmp(const char *);
28 char *expandtilde(const char *);
31 static int leavetmp = 0; /* 1 = leave any '~' files in tmp dir */
34 * Open a file for reading.
37 ffropen(FILE ** ffp, const char *fn, struct buffer *bp)
39 if ((*ffp = fopen(fn, "r")) == NULL) {
45 /* If 'fn' is a directory open it with dired. */
46 if (fisdir(fn) == TRUE)
55 * Update stat/dirty info
58 ffstat(FILE *ffp, struct buffer *bp)
62 if (bp && fstat(fileno(ffp), &sb) == 0) {
63 /* set highorder bit to make sure this isn't all zero */
64 bp->b_fi.fi_mode = sb.st_mode | 0x8000;
65 bp->b_fi.fi_uid = sb.st_uid;
66 bp->b_fi.fi_gid = sb.st_gid;
67 bp->b_fi.fi_mtime = sb.st_mtimespec;
68 /* Clear the ignore flag */
69 bp->b_flag &= ~(BFIGNDIRTY | BFDIRTY);
74 * Update the status/dirty info. If there is an error,
75 * there's not a lot we can do.
78 fupdstat(struct buffer *bp)
82 if ((ffp = fopen(bp->b_fname, "r")) == NULL) {
88 (void)ffclose(ffp, bp);
93 * Open a file for writing.
96 ffwopen(FILE ** ffp, const char *fn, struct buffer *bp)
99 mode_t fmode = DEFFILEMODE;
101 if (bp && bp->b_fi.fi_mode)
102 fmode = bp->b_fi.fi_mode & 07777;
104 fd = open(fn, O_RDWR | O_CREAT | O_TRUNC, fmode);
107 ewprintf("Cannot open file for writing : %s", strerror(errno));
111 if ((*ffp = fdopen(fd, "w")) == NULL) {
112 ewprintf("Cannot open file for writing : %s", strerror(errno));
118 * If we have file information, use it. We don't bother to check for
119 * errors, because there's no a lot we can do about it. Certainly
120 * trying to change ownership will fail if we aren't root. That's
121 * probably OK. If we don't have info, no need to get it, since any
122 * future writes will do the same thing.
124 if (bp && bp->b_fi.fi_mode) {
125 fchmod(fd, bp->b_fi.fi_mode & 07777);
126 fchown(fd, bp->b_fi.fi_uid, bp->b_fi.fi_gid);
136 ffclose(FILE *ffp, struct buffer *bp)
138 if (fclose(ffp) == 0)
144 * Write a buffer to the already opened file. bp points to the
145 * buffer. Return the status.
148 ffputbuf(FILE *ffp, struct buffer *bp)
150 struct line *lp, *lpend;
153 for (lp = lforw(lpend); lp != lpend; lp = lforw(lp)) {
154 if (fwrite(ltext(lp), 1, llength(lp), ffp) != llength(lp)) {
155 ewprintf("Write I/O error");
158 if (lforw(lp) != lpend) /* no implied \n on last line */
162 * XXX should be variable controlled (once we have variables)
164 if (llength(lback(lpend)) != 0) {
165 if (eyorn("No newline at end of file, add one") == TRUE) {
166 lnewline_at(lback(lpend), llength(lback(lpend)));
174 * Read a line from a file, and store the bytes
175 * in the supplied buffer. Stop on end of file or end of
176 * line. When FIOEOF is returned, there is a valid line
177 * of data without the normally implied \n.
178 * If the line length exceeds nbuf, FIOLONG is returned.
181 ffgetline(FILE *ffp, char *buf, int nbuf, int *nbytes)
186 while ((c = getc(ffp)) != EOF && c != '\n') {
191 if (c == EOF && ferror(ffp) != FALSE) {
192 ewprintf("File read error");
196 return (c == EOF ? FIOEOF : FIOSUC);
200 * Make a backup copy of "fname". On Unix the backup has the same
201 * name as the original file, with a "~" on the end; this seems to
202 * be newest of the new-speak. The error handling is all in "file.c".
203 * We do a copy instead of a rename since otherwise another process
204 * with an open fd will get the backup, not the new file. This is
205 * a problem when using mg with things like crontab and vipw.
208 fbackupfile(const char *fn)
211 int from, to, serrno;
214 char *nname, *tname, *bkpth;
216 if (stat(fn, &sb) == -1) {
217 ewprintf("Can't stat %s : %s", fn, strerror(errno));
221 if ((bkpth = bkuplocation(fn)) == NULL)
224 if (asprintf(&nname, "%s~", bkpth) == -1) {
225 ewprintf("Can't allocate backup file name : %s", strerror(errno));
229 if (asprintf(&tname, "%s.XXXXXXXXXX", bkpth) == -1) {
230 ewprintf("Can't allocate temp file name : %s", strerror(errno));
237 if ((from = open(fn, O_RDONLY)) == -1) {
251 while ((nread = read(from, buf, sizeof(buf))) > 0) {
252 if (write(to, buf, (size_t)nread) != nread) {
258 (void) fchmod(to, (sb.st_mode & 0777));
262 if (unlink(tname) == -1)
263 ewprintf("Can't unlink temp : %s", strerror(errno));
265 if (rename(tname, nname) == -1) {
266 ewprintf("Can't rename temp : %s", strerror(errno));
267 (void) unlink(tname);
275 return (nread == -1 ? FALSE : TRUE);
279 * Convert "fn" to a canonicalized absolute filename, replacing
280 * a leading ~/ with the user's home dir, following symlinks, and
281 * and remove all occurrences of /./ and /../
284 adjustname(const char *fn, int slashslash)
286 static char fnb[MAXPATHLEN];
287 const char *cp, *ep = NULL;
290 if (slashslash == TRUE) {
291 cp = fn + strlen(fn) - 1;
292 for (; cp >= fn; cp--) {
293 if (ep && (*cp == '/')) {
297 if (*cp == '/' || *cp == '~')
303 if ((path = expandtilde(fn)) == NULL)
306 if (realpath(path, fnb) == NULL)
307 (void)strlcpy(fnb, path, sizeof(fnb));
314 * Find a startup file for the user and return its name. As a service
315 * to other pieces of code that may want to find a startup file (like
316 * the terminal driver in particular), accepts a suffix to be appended
317 * to the startup file name.
320 startupfile(char *suffix)
322 static char file[NFILEN];
326 if ((home = getenv("HOME")) == NULL || *home == '\0')
329 if (suffix == NULL) {
330 ret = snprintf(file, sizeof(file), _PATH_MG_STARTUP, home);
331 if (ret < 0 || ret >= sizeof(file))
334 ret = snprintf(file, sizeof(file), _PATH_MG_TERM, home, suffix);
335 if (ret < 0 || ret >= sizeof(file))
339 if (access(file, R_OK) == 0)
343 if (suffix == NULL) {
344 ret = snprintf(file, sizeof(file), "%s", STARTUPFILE);
345 if (ret < 0 || ret >= sizeof(file))
348 ret = snprintf(file, sizeof(file), "%s%s", STARTUPFILE,
350 if (ret < 0 || ret >= sizeof(file))
354 if (access(file, R_OK) == 0)
356 #endif /* STARTUPFILE */
361 copy(char *frname, char *toname)
365 mode_t fmode = DEFFILEMODE; /* XXX?? */
369 if ((ifd = open(frname, O_RDONLY)) == -1)
371 if (fstat(ifd, &orig) == -1) {
372 ewprintf("fstat: %s", strerror(errno));
377 if ((ofd = open(toname, O_WRONLY|O_CREAT|O_TRUNC, fmode)) == -1) {
381 while ((sr = read(ifd, buf, sizeof(buf))) > 0) {
382 if (write(ofd, buf, (size_t)sr) != sr) {
383 ewprintf("write error : %s", strerror(errno));
387 if (fchmod(ofd, orig.st_mode) == -1)
388 ewprintf("Cannot set original mode : %s", strerror(errno));
391 ewprintf("Read error : %s", strerror(errno));
397 * It is "normal" for this to fail since we can't guarantee that
398 * we will be running as root.
400 if (fchown(ofd, orig.st_uid, orig.st_gid) && errno != EPERM)
401 ewprintf("Cannot set owner : %s", strerror(errno));
410 * return list of file names that match the name in buf.
413 make_file_list(char *buf)
415 char *dir, *file, *cp;
420 struct list *last, *current;
421 char fl_name[NFILEN + 2];
422 char prefixx[NFILEN + 1];
425 * We need three different strings:
427 * dir - the name of the directory containing what the user typed.
428 * Must be a real unix file name, e.g. no ~user, etc..
430 * prefix - the portion of what the user typed that is before the
431 * names we are going to find in the directory. Must have a
432 * trailing / if the user typed it.
433 * names from the directory - We open dir, and return prefix
434 * concatenated with names.
437 /* first we get a directory name we can look up */
439 * Names ending in . are potentially odd, because adjustname will
440 * treat foo/bar/.. as a foo/, whereas we are
441 * interested in names starting with ..
444 if (len && buf[len - 1] == '.') {
446 dir = adjustname(buf, TRUE);
449 dir = adjustname(buf, TRUE);
453 * If the user typed a trailing / or the empty string
454 * he wants us to use his file spec as a directory name.
456 if (len && buf[len - 1] != '/') {
457 file = strrchr(dir, '/');
465 /* Now we get the prefix of the name the user typed. */
466 if (strlcpy(prefixx, buf, sizeof(prefixx)) >= sizeof(prefixx))
468 cp = strrchr(prefixx, '/');
474 preflen = strlen(prefixx);
475 /* cp is the tail of buf that really needs to be compared. */
480 * Now make sure that file names will fit in the buffers allocated.
481 * SV files are fairly short. For BSD, something more general would
484 if (preflen > NFILEN - MAXNAMLEN)
487 /* loop over the specified directory, making up the list of files */
490 * Note that it is worth our time to filter out names that don't
491 * match, even though our caller is going to do so again, and to
492 * avoid doing the stat if completion is being done, because stat'ing
493 * every file in the directory is relatively expensive.
501 while ((dent = readdir(dirp)) != NULL) {
503 if (strncmp(cp, dent->d_name, len) != 0)
506 if (dent->d_type == DT_DIR) {
508 } else if (dent->d_type == DT_LNK ||
509 dent->d_type == DT_UNKNOWN) {
511 char statname[NFILEN + 2];
514 ret = snprintf(statname, sizeof(statname), "%s/%s",
516 if (ret < 0 || ret > sizeof(statname) - 1)
518 if (stat(statname, &statbuf) < 0)
520 if (S_ISDIR(statbuf.st_mode))
524 if ((current = malloc(sizeof(struct list))) == NULL) {
525 free_file_list(last);
529 ret = snprintf(fl_name, sizeof(fl_name),
530 "%s%s%s", prefixx, dent->d_name, isdir ? "/" : "");
531 if (ret < 0 || ret >= sizeof(fl_name)) {
535 current->l_next = last;
536 current->l_name = strdup(fl_name);
545 * Test if a supplied filename refers to a directory
546 * Returns ABORT on error, TRUE if directory. FALSE otherwise
549 fisdir(const char *fname)
553 if (stat(fname, &statbuf) != 0)
556 if (S_ISDIR(statbuf.st_mode))
563 * Check the mtime of the supplied filename.
564 * Return TRUE if last mtime matches, FALSE if not,
565 * If the stat fails, return TRUE and try the save anyway
568 fchecktime(struct buffer *bp)
572 if (stat(bp->b_fname, &sb) == -1)
575 if (bp->b_fi.fi_mtime.tv_sec != sb.st_mtimespec.tv_sec ||
576 bp->b_fi.fi_mtime.tv_nsec != sb.st_mtimespec.tv_nsec)
584 * Location of backup file. This function creates the correct path.
587 bkuplocation(const char *fn)
592 if (bkupdir != NULL && (stat(bkupdir, &sb) == 0) &&
593 S_ISDIR(sb.st_mode) && !bkupleavetmp(fn)) {
599 len = strlen(bkupdir);
602 /* Make sure we don't go over combined:
603 * strlen(bkupdir + '/' + fname + '\0')
605 if (i >= NFILEN - len - 1)
609 } else if (*c == '!') {
610 if (i >= NFILEN - len - 2)
620 if (asprintf(&ret, "%s/%s", bkupdir, fname) == -1)
623 } else if ((ret = strndup(fn, NFILEN)) == NULL)
630 backuptohomedir(int f, int n)
632 const char *c = _PATH_MG_DIR;
635 if (bkupdir == NULL) {
636 p = adjustname(c, TRUE);
637 bkupdir = strndup(p, NFILEN);
641 if (mkdir(bkupdir, 0700) == -1 && errno != EEXIST) {
654 * For applications that use mg as the editor and have a desire to keep
655 * '~' files in the TMPDIR, toggle the location: /tmp | ~/.mg.d
658 toggleleavetmp(int f, int n)
660 leavetmp = !leavetmp;
666 * Returns TRUE if fn is located in the temp directory and we want to save
667 * those backups there.
670 bkupleavetmp(const char *fn)
672 char *tmpdir, *tmp = NULL;
677 if((tmpdir = getenv("TMPDIR")) != NULL && *tmpdir != '\0') {
678 tmp = strstr(fn, tmpdir);
685 tmp = strstr(fn, "/tmp");
693 * Expand file names beginning with '~' if appropriate:
694 * 1, if ./~fn exists, continue without expanding tilde.
695 * 2, else, if username 'fn' exists, expand tilde with home directory path.
696 * 3, otherwise, continue and create new buffer called ~fn.
699 expandtilde(const char *fn)
704 char user[LOGIN_NAME_MAX], path[NFILEN];
710 if (fn[0] != '~' || stat(fn, &statbuf) == 0) {
711 if ((ret = strndup(fn, NFILEN)) == NULL)
715 cp = strchr(fn, '/');
717 cp = fn + strlen(fn); /* point to the NUL byte */
719 if (ulen >= sizeof(user)) {
720 if ((ret = strndup(fn, NFILEN)) == NULL)
724 if (ulen == 0) { /* ~/ or ~ */
725 if ((un = getlogin()) != NULL)
726 (void)strlcpy(user, un, sizeof(user));
729 } else { /* ~user/ or ~user */
730 memcpy(user, &fn[1], ulen);
735 plen = strlcpy(path, pw->pw_dir, sizeof(path));
736 if (plen == 0 || path[plen - 1] != '/') {
737 if (strlcat(path, "/", sizeof(path)) >= sizeof(path)) {
738 ewprintf("Path too long");
746 if (strlcat(path, fn, sizeof(path)) >= sizeof(path)) {
747 ewprintf("Path too long");
750 if ((ret = strndup(path, NFILEN)) == NULL)