[BACK]Return to fileio.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / mg

Annotation of src/usr.bin/mg/fileio.c, Revision 1.55

1.55    ! kjell       1: /*     $OpenBSD: fileio.c,v 1.54 2005/10/13 20:23:01 kjell Exp $       */
1.50      kjell       2:
                      3: /* This file is in the public domain. */
1.10      niklas      4:
1.1       deraadt     5: /*
1.7       millert     6:  *     POSIX fileio.c
1.1       deraadt     7:  */
1.49      db          8: #include "def.h"
1.1       deraadt     9:
1.53      kjell      10: #ifndef NO_DIRED
                     11: #include <sys/wait.h>
                     12: #include "kbd.h"
                     13: #endif /* !NO_DIRED */
                     14:
1.1       deraadt    15: #include <sys/types.h>
1.33      vincent    16: #include <limits.h>
1.1       deraadt    17: #include <sys/stat.h>
                     18: #include <sys/dir.h>
1.21      vincent    19: #include <string.h>
1.9       millert    20: #include <fcntl.h>
                     21: #include <unistd.h>
1.1       deraadt    22:
1.49      db         23: static FILE    *ffp;
                     24:
1.1       deraadt    25: /*
                     26:  * Open a file for reading.
                     27:  */
1.7       millert    28: int
1.25      vincent    29: ffropen(const char *fn, BUFFER *bp)
1.7       millert    30: {
1.16      mickey     31:        struct stat     statbuf;
1.7       millert    32:
1.46      jfb        33:        if ((ffp = fopen(fn, "r")) == NULL) {
                     34:                if (errno == ENOENT)
                     35:                        return (FIOFNF);
                     36:                return (FIOERR);
                     37:        }
1.53      kjell      38:
                     39:        /* If 'fn' is a directory open it with dired. */
1.54      kjell      40:        if (fisdir(fn) == TRUE)
1.53      kjell      41: #ifdef NO_DIRED
                     42:                return (FIOERR);
                     43: #else
                     44:                return (FIODIR);
                     45: #endif /* NO_DIRED */
                     46:
1.1       deraadt    47:        if (bp && fstat(fileno(ffp), &statbuf) == 0) {
1.7       millert    48:                /* set highorder bit to make sure this isn't all zero */
1.1       deraadt    49:                bp->b_fi.fi_mode = statbuf.st_mode | 0x8000;
                     50:                bp->b_fi.fi_uid = statbuf.st_uid;
                     51:                bp->b_fi.fi_gid = statbuf.st_gid;
                     52:        }
1.53      kjell      53:
1.1       deraadt    54:        return (FIOSUC);
                     55: }
                     56:
                     57: /*
                     58:  * Open a file for writing.
                     59:  */
1.7       millert    60: int
1.25      vincent    61: ffwopen(const char *fn, BUFFER *bp)
1.7       millert    62: {
1.49      db         63:        int     fd;
                     64:        mode_t  mode = DEFFILEMODE;
1.7       millert    65:
1.24      deraadt    66:        if (bp && bp->b_fi.fi_mode)
                     67:                mode = bp->b_fi.fi_mode & 07777;
                     68:
                     69:        fd = open(fn, O_RDWR | O_CREAT | O_TRUNC, mode);
                     70:        if (fd == -1) {
                     71:                ffp = NULL;
1.21      vincent    72:                ewprintf("Cannot open file for writing : %s", strerror(errno));
1.1       deraadt    73:                return (FIOERR);
1.34      deraadt    74:        }
1.24      deraadt    75:
                     76:        if ((ffp = fdopen(fd, "w")) == NULL) {
                     77:                ewprintf("Cannot open file for writing : %s", strerror(errno));
                     78:                close(fd);
1.34      deraadt    79:                return (FIOERR);
1.1       deraadt    80:        }
1.7       millert    81:
                     82:        /*
                     83:         * If we have file information, use it.  We don't bother to check for
                     84:         * errors, because there's no a lot we can do about it.  Certainly
1.24      deraadt    85:         * trying to change ownership will fail if we aren't root.  That's
1.7       millert    86:         * probably OK.  If we don't have info, no need to get it, since any
                     87:         * future writes will do the same thing.
1.1       deraadt    88:         */
                     89:        if (bp && bp->b_fi.fi_mode) {
1.28      deraadt    90:                fchmod(fd, bp->b_fi.fi_mode & 07777);
                     91:                fchown(fd, bp->b_fi.fi_uid, bp->b_fi.fi_gid);
1.1       deraadt    92:        }
                     93:        return (FIOSUC);
                     94: }
                     95:
                     96: /*
                     97:  * Close a file.
1.7       millert    98:  * XXX - Should look at the status.
1.1       deraadt    99:  */
1.7       millert   100: /* ARGSUSED */
                    101: int
1.25      vincent   102: ffclose(BUFFER *bp)
1.7       millert   103: {
1.13      art       104:        (void) fclose(ffp);
1.1       deraadt   105:        return (FIOSUC);
                    106: }
                    107:
                    108: /*
1.41      vincent   109:  * Write a buffer to the already opened file. bp points to the
1.1       deraadt   110:  * buffer. Return the status.
                    111:  */
1.7       millert   112: int
1.25      vincent   113: ffputbuf(BUFFER *bp)
1.1       deraadt   114: {
1.41      vincent   115:        LINE   *lp, *lpend;
1.7       millert   116:
                    117:        lpend = bp->b_linep;
1.41      vincent   118:        for (lp = lforw(lpend); lp != lpend; lp = lforw(lp)) {
                    119:                if (fwrite(ltext(lp), 1, llength(lp), ffp) != llength(lp)) {
                    120:                        ewprintf("Write I/O error");
1.49      db        121:                        return (FIOERR);
1.7       millert   122:                }
1.41      vincent   123:                if (lforw(lp) != lpend)         /* no implied \n on last line */
                    124:                        putc('\n', ffp);
1.48      deraadt   125:        }
1.42      vincent   126:        /*
                    127:         * XXX should be variable controlled (once we have variables)
                    128:         */
                    129:        if (llength(lback(lpend)) != 0) {
                    130:                if (eyorn("No newline at end of file, add one") == TRUE) {
                    131:                        lnewline_at(lback(lpend), llength(lback(lpend)));
                    132:                        putc('\n', ffp);
                    133:                }
                    134:        }
1.7       millert   135:        return (FIOSUC);
1.1       deraadt   136: }
                    137:
                    138: /*
                    139:  * Read a line from a file, and store the bytes
                    140:  * in the supplied buffer. Stop on end of file or end of
                    141:  * line.  When FIOEOF is returned, there is a valid line
                    142:  * of data without the normally implied \n.
                    143:  */
1.7       millert   144: int
1.25      vincent   145: ffgetline(char *buf, int nbuf, int *nbytes)
1.1       deraadt   146: {
1.16      mickey    147:        int     c, i;
1.1       deraadt   148:
                    149:        i = 0;
1.7       millert   150:        while ((c = getc(ffp)) != EOF && c != '\n') {
1.1       deraadt   151:                buf[i++] = c;
1.7       millert   152:                if (i >= nbuf)
1.49      db        153:                        return (FIOLONG);
1.1       deraadt   154:        }
1.7       millert   155:        if (c == EOF && ferror(ffp) != FALSE) {
1.1       deraadt   156:                ewprintf("File read error");
1.49      db        157:                return (FIOERR);
1.1       deraadt   158:        }
                    159:        *nbytes = i;
1.49      db        160:        return (c == EOF ? FIOEOF : FIOSUC);
1.1       deraadt   161: }
                    162:
                    163: #ifndef NO_BACKUP
                    164: /*
1.9       millert   165:  * Make a backup copy of "fname".  On Unix the backup has the same
                    166:  * name as the original file, with a "~" on the end; this seems to
                    167:  * be newest of the new-speak. The error handling is all in "file.c".
                    168:  * We do a copy instead of a rename since otherwise another process
                    169:  * with an open fd will get the backup, not the new file.  This is
                    170:  * a problem when using mg with things like crontab and vipw.
1.1       deraadt   171:  */
1.7       millert   172: int
1.25      vincent   173: fbackupfile(const char *fn)
1.7       millert   174: {
1.49      db        175:        struct stat      sb;
                    176:        int              from, to, serrno;
                    177:        ssize_t          nread;
                    178:        char             buf[BUFSIZ];
1.44      millert   179:        char            *nname, *tname;
1.1       deraadt   180:
1.35      vincent   181:        if (stat(fn, &sb) == -1) {
                    182:                ewprintf("Can't stat %s : %s", fn, strerror(errno));
                    183:                return (FALSE);
                    184:        }
                    185:
1.21      vincent   186:        if (asprintf(&nname, "%s~", fn) == -1) {
1.44      millert   187:                ewprintf("Can't allocate temp file name : %s", strerror(errno));
                    188:                return (ABORT);
                    189:        }
                    190:
                    191:        if (asprintf(&tname, "%s.XXXXXXXXXX", fn) == -1) {
                    192:                ewprintf("Can't allocate temp file name : %s", strerror(errno));
                    193:                free(nname);
1.1       deraadt   194:                return (ABORT);
1.9       millert   195:        }
                    196:
1.21      vincent   197:        if ((from = open(fn, O_RDONLY)) == -1) {
                    198:                free(nname);
1.44      millert   199:                free(tname);
1.1       deraadt   200:                return (FALSE);
1.21      vincent   201:        }
1.44      millert   202:        to = mkstemp(tname);
1.9       millert   203:        if (to == -1) {
                    204:                serrno = errno;
                    205:                close(from);
1.21      vincent   206:                free(nname);
1.44      millert   207:                free(tname);
1.9       millert   208:                errno = serrno;
                    209:                return (FALSE);
                    210:        }
                    211:        while ((nread = read(from, buf, sizeof(buf))) > 0) {
                    212:                if (write(to, buf, nread) != nread) {
1.40      vincent   213:                        nread = -1;
                    214:                        break;
1.9       millert   215:                }
1.1       deraadt   216:        }
1.9       millert   217:        serrno = errno;
1.44      millert   218:        (void) fchmod(to, (sb.st_mode & 0777));
1.9       millert   219:        close(from);
                    220:        close(to);
1.21      vincent   221:        if (nread == -1) {
1.44      millert   222:                if (unlink(tname) == -1)
1.21      vincent   223:                        ewprintf("Can't unlink temp : %s", strerror(errno));
1.44      millert   224:        } else {
                    225:                if (rename(tname, nname) == -1) {
                    226:                        ewprintf("Can't rename temp : %s", strerror(errno));
                    227:                        (void) unlink(tname);
1.45      henning   228:                        nread = -1;
1.44      millert   229:                }
1.21      vincent   230:        }
1.1       deraadt   231:        free(nname);
1.44      millert   232:        free(tname);
1.9       millert   233:        errno = serrno;
1.22      deraadt   234:
1.9       millert   235:        return (nread == -1 ? FALSE : TRUE);
1.1       deraadt   236: }
                    237: #endif
                    238:
                    239: /*
                    240:  * The string "fn" is a file name.
                    241:  * Perform any required appending of directory name or case adjustments.
1.39      jmc       242:  * If NO_DIR is not defined, the same file should be referred to even if the
1.1       deraadt   243:  * working directory changes.
                    244:  */
                    245: #ifdef SYMBLINK
                    246: #include <sys/types.h>
                    247: #include <sys/stat.h>
                    248: #ifndef MAXLINK
                    249: #define MAXLINK 8              /* maximum symbolic links to follow */
                    250: #endif
                    251: #endif
                    252: #include <pwd.h>
                    253: #ifndef NO_DIR
1.16      mickey    254: extern char    *wdir;
1.1       deraadt   255: #endif
                    256:
1.7       millert   257: char *
1.25      vincent   258: adjustname(const char *fn)
1.1       deraadt   259: {
1.49      db        260:        static char      fnb[MAXPATHLEN];
                    261:        const char      *cp;
                    262:        char             user[LOGIN_NAME_MAX + 1], path[MAXPATHLEN];
                    263:        int              len;
1.33      vincent   264:
                    265:        path[0] = '\0';
                    266:        /* first handle tilde expansion */
                    267:        if (fn[0] == '~') {
                    268:                struct passwd *pw;
                    269:
                    270:                cp = strchr(fn, '/');
                    271:                if (cp == NULL)
                    272:                        cp = fn + strlen(fn); /* point to the NUL byte */
1.1       deraadt   273:
1.33      vincent   274:                if ((cp - &fn[1]) > LOGIN_NAME_MAX) {
                    275:                        ewprintf("login name too long");
                    276:                        return (NULL);
                    277:                }
                    278:                if (cp == &fn[1]) /* ~/ */
1.49      db        279:                        strlcpy(user, getlogin(), sizeof(user));
1.33      vincent   280:                else
                    281:                        strlcpy(user, &fn[1], cp - &fn[1] + 1);
                    282:                pw = getpwnam(user);
                    283:                if (pw == NULL) {
                    284:                        ewprintf("unknown user %s", user);
                    285:                        return (NULL);
                    286:                }
1.49      db        287:                strlcpy(path, pw->pw_dir, sizeof(path) - 1);
1.33      vincent   288:                len = strlen(path);
                    289:                if (path[len] != '/') {
                    290:                        path[len] = '/';
                    291:                        path[len + 1] = '\0';
1.1       deraadt   292:                }
1.33      vincent   293:                fn = cp;
                    294:                if (*fn == '/')
1.7       millert   295:                        fn++;
                    296:        }
1.49      db        297:        strlcat(path, fn, sizeof(path));
1.33      vincent   298:
1.47      henning   299:        if (realpath(path, fnb) == NULL)
                    300:                strlcpy(fnb, path, sizeof(fnb));
                    301:
                    302:        return (fnb);
1.1       deraadt   303: }
                    304:
                    305: #ifndef NO_STARTUP
                    306: /*
                    307:  * Find a startup file for the user and return its name. As a service
                    308:  * to other pieces of code that may want to find a startup file (like
                    309:  * the terminal driver in particular), accepts a suffix to be appended
                    310:  * to the startup file name.
                    311:  */
                    312: char *
1.27      millert   313: startupfile(char *suffix)
1.1       deraadt   314: {
1.49      db        315:        static char      file[NFILEN];
1.16      mickey    316:        char            *home;
1.12      art       317:
                    318:        if ((home = getenv("HOME")) == NULL || *home == '\0')
                    319:                goto nohome;
1.1       deraadt   320:
1.12      art       321:        if (suffix == NULL) {
                    322:                if (snprintf(file, sizeof(file), "%s/.mg", home)
1.32      vincent   323:                    >= sizeof(file))
                    324:                        return (NULL);
1.12      art       325:        } else {
                    326:                if (snprintf(file, sizeof(file), "%s/.mg-%s", home, suffix)
1.32      vincent   327:                    >= sizeof(file))
                    328:                        return (NULL);
1.1       deraadt   329:        }
1.12      art       330:
                    331:        if (access(file, R_OK) == 0)
1.32      vincent   332:                return (file);
1.12      art       333: nohome:
                    334: #ifdef STARTUPFILE
1.27      millert   335:        if (suffix == NULL) {
1.12      art       336:                if (snprintf(file, sizeof(file), "%s", STARTUPFILE)
1.32      vincent   337:                    >= sizeof(file))
                    338:                        return (NULL);
1.12      art       339:        } else {
                    340:                if (snprintf(file, sizeof(file), "%s%s", STARTUPFILE, suffix)
1.32      vincent   341:                    >= sizeof(file))
                    342:                        return (NULL);
1.12      art       343:        }
                    344:
                    345:        if (access(file, R_OK) == 0)
1.32      vincent   346:                return (file);
1.1       deraadt   347: #endif
1.32      vincent   348:        return (NULL);
1.1       deraadt   349: }
                    350: #endif
                    351:
                    352: #ifndef NO_DIRED
                    353:
1.7       millert   354: int
1.27      millert   355: copy(char *frname, char *toname)
1.1       deraadt   356: {
1.49      db        357:        int     ifd, ofd, n;
                    358:        char    buf[BUFSIZ];
                    359:        mode_t  mode = DEFFILEMODE;     /* XXX?? */
                    360:        struct  stat orig;
1.30      vincent   361:
                    362:        if ((ifd = open(frname, O_RDONLY)) == -1)
                    363:                return (FALSE);
                    364:        if (fstat(ifd, &orig) == -1) {
                    365:                ewprintf("fstat: %s", strerror(errno));
                    366:                close(ifd);
                    367:                return (FALSE);
                    368:        }
                    369:
                    370:        if ((ofd = open(toname, O_WRONLY|O_CREAT|O_TRUNC, mode)) == -1) {
                    371:                close(ifd);
                    372:                return (FALSE);
                    373:        }
1.49      db        374:        while ((n = read(ifd, buf, sizeof(buf))) > 0) {
1.30      vincent   375:                if (write(ofd, buf, n) != n) {
                    376:                        ewprintf("write error : %s", strerror(errno));
                    377:                        break;
                    378:                }
                    379:        }
                    380:        if (fchmod(ofd, orig.st_mode) == -1)
                    381:                ewprintf("Cannot set original mode : %s", strerror(errno));
1.1       deraadt   382:
1.30      vincent   383:        if (n == -1) {
                    384:                ewprintf("Read error : %s", strerror(errno));
                    385:                close(ifd);
                    386:                close(ofd);
                    387:                return (FALSE);
1.7       millert   388:        }
1.30      vincent   389:        /*
1.32      vincent   390:         * It is "normal" for this to fail since we can't guarantee that
1.49      db        391:         * we will be running as root.
1.30      vincent   392:         */
                    393:        if (fchown(ofd, orig.st_uid, orig.st_gid) && errno != EPERM)
                    394:                ewprintf("Cannot set owner : %s", strerror(errno));
                    395:
                    396:        (void) close(ifd);
                    397:        (void) close(ofd);
                    398:
                    399:        return (TRUE);
1.7       millert   400: }
                    401:
                    402: #endif                         /* NO_DIRED */
1.1       deraadt   403:
                    404: struct filelist {
1.16      mickey    405:        LIST    fl_l;
                    406:        char    fl_name[NFILEN + 2];
1.1       deraadt   407: };
                    408:
1.7       millert   409: /*
1.1       deraadt   410:  * return list of file names that match the name in buf.
                    411:  */
1.7       millert   412: LIST *
1.25      vincent   413: make_file_list(char *buf)
1.7       millert   414: {
1.16      mickey    415:        char            *dir, *file, *cp;
1.49      db        416:        int              len, preflen;
1.16      mickey    417:        DIR             *dirp;
                    418:        struct dirent   *dent;
                    419:        LIST            *last;
1.7       millert   420:        struct filelist *current;
1.49      db        421:        char             prefixx[NFILEN + 1];
1.7       millert   422:
                    423:        /*
                    424:         * We need three different strings: dir - the name of the directory
                    425:         * containing what the user typed. Must be a real unix file name,
                    426:         * e.g. no ~user, etc..  Must not end in /. prefix - the portion of
                    427:         * what the user typed that is before the names we are going to find
                    428:         * in the directory.  Must have a trailing / if the user typed it.
1.49      db        429:         * names from the directory. We open dir, and return prefix
1.7       millert   430:         * concatenated with names.
                    431:         */
                    432:
                    433:        /* first we get a directory name we can look up */
                    434:        /*
                    435:         * Names ending in . are potentially odd, because adjustname will
                    436:         * treat foo/.. as a reference to another directory, whereas we are
                    437:         * interested in names starting with ..
                    438:         */
                    439:        len = strlen(buf);
                    440:        if (buf[len - 1] == '.') {
                    441:                buf[len - 1] = 'x';
                    442:                dir = adjustname(buf);
                    443:                buf[len - 1] = '.';
                    444:        } else
                    445:                dir = adjustname(buf);
1.33      vincent   446:        if (dir == NULL)
1.36      vincent   447:                return (NULL);
1.7       millert   448:        /*
                    449:         * If the user typed a trailing / or the empty string
                    450:         * he wants us to use his file spec as a directory name.
                    451:         */
                    452:        if (buf[0] && buf[strlen(buf) - 1] != '/') {
                    453:                file = strrchr(dir, '/');
                    454:                if (file) {
                    455:                        *file = 0;
                    456:                        if (*dir == 0)
                    457:                                dir = "/";
1.49      db        458:                } else
1.7       millert   459:                        return (NULL);
1.1       deraadt   460:        }
1.7       millert   461:        /* Now we get the prefix of the name the user typed. */
1.49      db        462:        strlcpy(prefixx, buf, sizeof(prefixx));
1.7       millert   463:        cp = strrchr(prefixx, '/');
                    464:        if (cp == NULL)
                    465:                prefixx[0] = 0;
                    466:        else
                    467:                cp[1] = 0;
                    468:
                    469:        preflen = strlen(prefixx);
1.49      db        470:        /* cp is the tail of buf that really needs to be compared. */
1.7       millert   471:        cp = buf + preflen;
                    472:        len = strlen(cp);
                    473:
                    474:        /*
                    475:         * Now make sure that file names will fit in the buffers allocated.
                    476:         * SV files are fairly short.  For BSD, something more general would
                    477:         * be required.
                    478:         */
                    479:        if ((preflen + MAXNAMLEN) > NFILEN)
                    480:                return (NULL);
                    481:
                    482:        /* loop over the specified directory, making up the list of files */
                    483:
                    484:        /*
                    485:         * Note that it is worth our time to filter out names that don't
                    486:         * match, even though our caller is going to do so again, and to
                    487:         * avoid doing the stat if completion is being done, because stat'ing
                    488:         * every file in the directory is relatively expensive.
                    489:         */
1.1       deraadt   490:
1.11      art       491:        dirp = opendir(dir);
                    492:        if (dirp == NULL)
1.7       millert   493:                return (NULL);
                    494:        last = NULL;
1.11      art       495:
                    496:        while ((dent = readdir(dirp)) != NULL) {
1.18      art       497:                int isdir;
                    498:
1.11      art       499:                if (dent->d_namlen < len || memcmp(cp, dent->d_name, len) != 0)
                    500:                        continue;
                    501:
1.18      art       502:                isdir = 0;
                    503:                if (dent->d_type == DT_DIR) {
                    504:                        isdir = 1;
                    505:                } else if (dent->d_type == DT_LNK ||
                    506:                            dent->d_type == DT_UNKNOWN) {
                    507:                        struct stat     statbuf;
                    508:                        char            statname[NFILEN + 2];
                    509:
                    510:                        statbuf.st_mode = 0;
                    511:                        if (snprintf(statname, sizeof(statname), "%s/%s",
                    512:                            dir, dent->d_name) > sizeof(statname) - 1) {
                    513:                                continue;
                    514:                        }
                    515:                        if (stat(statname, &statbuf) < 0)
                    516:                                continue;
                    517:                        if (statbuf.st_mode & S_IFDIR)
                    518:                                isdir = 1;
                    519:                }
                    520:
                    521:                current = malloc(sizeof(struct filelist));
1.12      art       522:                if (current == NULL)
                    523:                        break;
1.18      art       524:
1.11      art       525:                if (snprintf(current->fl_name, sizeof(current->fl_name),
1.18      art       526:                    "%s%s%s", prefixx, dent->d_name, isdir ? "/" : "")
                    527:                    >= sizeof(current->fl_name)) {
1.11      art       528:                        free(current);
1.7       millert   529:                        continue;
                    530:                }
                    531:                current->fl_l.l_next = last;
                    532:                current->fl_l.l_name = current->fl_name;
                    533:                last = (LIST *) current;
1.1       deraadt   534:        }
1.11      art       535:        closedir(dirp);
1.1       deraadt   536:
1.7       millert   537:        return (last);
1.54      kjell     538: }
                    539:
                    540: /*
                    541:  * Test if a supplied filename refers to a directory
                    542:  * Returns ABORT on error, TRUE if directory. FALSE otherwise
                    543:  */
                    544: int
                    545: fisdir(const char *fname)
                    546: {
                    547:        struct stat     statbuf;
                    548:
                    549:        if (stat(fname, &statbuf) != 0)
                    550:                return (ABORT);
                    551:
                    552:        if (S_ISDIR(statbuf.st_mode))
                    553:                return (TRUE);
                    554:
                    555:        return (FALSE);
1.1       deraadt   556: }