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

Annotation of src/usr.bin/sed/main.c, Revision 1.38

1.38    ! martijn     1: /*     $OpenBSD: main.c,v 1.37 2018/07/11 06:57:18 martijn Exp $       */
1.3       deraadt     2:
1.1       deraadt     3: /*-
                      4:  * Copyright (c) 1992 Diomidis Spinellis.
                      5:  * Copyright (c) 1992, 1993
                      6:  *     The Regents of the University of California.  All rights reserved.
                      7:  *
                      8:  * This code is derived from software contributed to Berkeley by
                      9:  * Diomidis Spinellis of Imperial College, University of London.
                     10:  *
                     11:  * Redistribution and use in source and binary forms, with or without
                     12:  * modification, are permitted provided that the following conditions
                     13:  * are met:
                     14:  * 1. Redistributions of source code must retain the above copyright
                     15:  *    notice, this list of conditions and the following disclaimer.
                     16:  * 2. Redistributions in binary form must reproduce the above copyright
                     17:  *    notice, this list of conditions and the following disclaimer in the
                     18:  *    documentation and/or other materials provided with the distribution.
1.8       millert    19:  * 3. Neither the name of the University nor the names of its contributors
1.1       deraadt    20:  *    may be used to endorse or promote products derived from this software
                     21:  *    without specific prior written permission.
                     22:  *
                     23:  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
                     24:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     25:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     26:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
                     27:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     28:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     29:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     30:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     31:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     32:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     33:  * SUCH DAMAGE.
                     34:  */
                     35:
                     36: #include <sys/types.h>
1.24      deraadt    37: #include <sys/ioctl.h>
1.19      jasper     38: #include <sys/stat.h>
1.1       deraadt    39:
                     40: #include <ctype.h>
                     41: #include <errno.h>
                     42: #include <fcntl.h>
1.15      millert    43: #include <limits.h>
1.1       deraadt    44: #include <regex.h>
                     45: #include <stddef.h>
                     46: #include <stdio.h>
                     47: #include <stdlib.h>
                     48: #include <string.h>
                     49: #include <unistd.h>
1.19      jasper     50: #include <libgen.h>
1.1       deraadt    51:
                     52: #include "defs.h"
                     53: #include "extern.h"
                     54:
                     55: /*
                     56:  * Linked list of units (strings and files) to be compiled
                     57:  */
                     58: struct s_compunit {
                     59:        struct s_compunit *next;
                     60:        enum e_cut {CU_FILE, CU_STRING} type;
                     61:        char *s;                        /* Pointer to string or fname */
                     62: };
                     63:
                     64: /*
                     65:  * Linked list pointer to compilation units and pointer to current
                     66:  * next pointer.
                     67:  */
                     68: static struct s_compunit *script, **cu_nextp = &script;
                     69:
                     70: /*
                     71:  * Linked list of files to be processed
                     72:  */
                     73: struct s_flist {
                     74:        char *fname;
                     75:        struct s_flist *next;
                     76: };
                     77:
                     78: /*
                     79:  * Linked list pointer to files and pointer to current
                     80:  * next pointer.
                     81:  */
                     82: static struct s_flist *files, **fl_nextp = &files;
                     83:
1.19      jasper     84: FILE *infile;                  /* Current input file */
                     85: FILE *outfile;                 /* Current output file */
                     86:
1.16      djm        87: int Eflag, aflag, eflag, nflag;
1.19      jasper     88: static int rval;       /* Exit status */
1.1       deraadt    89:
                     90: /*
                     91:  * Current file and line number; line numbers restart across compilation
1.19      jasper     92:  * units, but span across input files.  The latter is optional if editing
                     93:  * in place.
1.1       deraadt    94:  */
1.19      jasper     95: const char *fname;             /* File name. */
                     96: const char *outfname;          /* Output file name */
                     97: static char oldfname[PATH_MAX];        /* Old file name (for in-place editing) */
                     98: static char tmpfname[PATH_MAX];        /* Temporary file name (for in-place editing) */
                     99: char *inplace;                 /* Inplace edit file extension */
1.1       deraadt   100: u_long linenum;
                    101:
1.6       millert   102: static void add_compunit(enum e_cut, char *);
                    103: static void add_file(char *);
1.21      jasper    104: static int next_files_have_lines(void);
1.1       deraadt   105:
1.24      deraadt   106: int termwidth;
                    107:
1.35      martijn   108: int pledge_wpath, pledge_rpath;
                    109:
1.1       deraadt   110: int
1.9       deraadt   111: main(int argc, char *argv[])
1.1       deraadt   112: {
1.24      deraadt   113:        struct winsize win;
1.1       deraadt   114:        int c, fflag;
1.24      deraadt   115:        char *p;
1.1       deraadt   116:
                    117:        fflag = 0;
1.19      jasper    118:        inplace = NULL;
                    119:        while ((c = getopt(argc, argv, "Eae:f:i::nru")) != -1)
1.1       deraadt   120:                switch (c) {
1.16      djm       121:                case 'E':
                    122:                case 'r':
                    123:                        Eflag = 1;
                    124:                        break;
1.1       deraadt   125:                case 'a':
                    126:                        aflag = 1;
                    127:                        break;
                    128:                case 'e':
                    129:                        eflag = 1;
                    130:                        add_compunit(CU_STRING, optarg);
                    131:                        break;
                    132:                case 'f':
                    133:                        fflag = 1;
                    134:                        add_compunit(CU_FILE, optarg);
                    135:                        break;
1.19      jasper    136:                case 'i':
                    137:                        inplace = optarg ? optarg : "";
                    138:                        break;
1.1       deraadt   139:                case 'n':
                    140:                        nflag = 1;
                    141:                        break;
1.11      ray       142:                case 'u':
1.18      millert   143:                        setvbuf(stdout, NULL, _IOLBF, 0);
1.11      ray       144:                        break;
1.1       deraadt   145:                default:
                    146:                case '?':
                    147:                        (void)fprintf(stderr,
1.22      jmc       148:                            "usage: sed [-aEnru] [-i[extension]] command [file ...]\n"
                    149:                            "       sed [-aEnru] [-e command] [-f command_file] [-i[extension]] [file ...]\n");
1.1       deraadt   150:                        exit(1);
                    151:                }
                    152:        argc -= optind;
                    153:        argv += optind;
1.24      deraadt   154:
1.32      bentley   155:        termwidth = 0;
                    156:        if ((p = getenv("COLUMNS")) != NULL)
1.24      deraadt   157:                termwidth = strtonum(p, 0, INT_MAX, NULL);
1.32      bentley   158:        if (termwidth == 0 && ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
1.24      deraadt   159:            win.ws_col > 0)
                    160:                termwidth = win.ws_col;
                    161:        if (termwidth == 0)
1.32      bentley   162:                termwidth = 80;
1.37      martijn   163:        if (termwidth <= 8)
                    164:                termwidth = 1;
                    165:        else
                    166:                termwidth -= 8;
1.25      deraadt   167:
                    168:        if (inplace != NULL) {
1.33      semarie   169:                if (pledge("stdio rpath wpath cpath fattr chown", NULL) == -1)
1.30      jca       170:                        error(FATAL, "pledge: %s", strerror(errno));
1.25      deraadt   171:        } else {
1.27      deraadt   172:                if (pledge("stdio rpath wpath cpath", NULL) == -1)
1.30      jca       173:                        error(FATAL, "pledge: %s", strerror(errno));
1.25      deraadt   174:        }
1.1       deraadt   175:
                    176:        /* First usage case; script is the first arg */
                    177:        if (!eflag && !fflag && *argv) {
                    178:                add_compunit(CU_STRING, *argv);
                    179:                argv++;
                    180:        }
                    181:
                    182:        compile();
                    183:
                    184:        /* Continue with first and start second usage */
1.35      martijn   185:        if (*argv) {
                    186:                if (!pledge_wpath && inplace == NULL) {
                    187:                        if (pledge("stdio rpath", NULL) == -1)
                    188:                                error(FATAL, "pledge: %s", strerror(errno));
                    189:                }
1.1       deraadt   190:                for (; *argv; argv++)
                    191:                        add_file(*argv);
1.35      martijn   192:        } else {
                    193:                if (!pledge_wpath && !pledge_rpath) {
                    194:                        if (pledge("stdio", NULL) == -1)
                    195:                                error(FATAL, "pledge: %s", strerror(errno));
                    196:                } else if (pledge_rpath) {
                    197:                        if (pledge("stdio rpath", NULL) == -1)
                    198:                                error(FATAL, "pledge: %s", strerror(errno));
                    199:                } else if (pledge_wpath) {
                    200:                        if (pledge("stdio wpath cpath", NULL) == -1)
                    201:                                error(FATAL, "pledge: %s", strerror(errno));
                    202:                }
1.1       deraadt   203:                add_file(NULL);
1.35      martijn   204:        }
1.1       deraadt   205:        process();
                    206:        cfclose(prog, NULL);
                    207:        if (fclose(stdout))
1.29      mmcc      208:                error(FATAL, "stdout: %s", strerror(errno));
1.19      jasper    209:        exit (rval);
1.1       deraadt   210: }
                    211:
                    212: /*
                    213:  * Like fgets, but go through the chain of compilation units chaining them
                    214:  * together.  Empty strings and files are ignored.
                    215:  */
                    216: char *
1.15      millert   217: cu_fgets(char **outbuf, size_t *outsize)
1.1       deraadt   218: {
                    219:        static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF;
                    220:        static FILE *f;         /* Current open file */
                    221:        static char *s;         /* Current pointer inside string */
                    222:        static char string_ident[30];
1.13      millert   223:        size_t len;
1.1       deraadt   224:        char *p;
                    225:
1.15      millert   226:        if (*outbuf == NULL)
                    227:                *outsize = 0;
                    228:
1.1       deraadt   229: again:
                    230:        switch (state) {
                    231:        case ST_EOF:
                    232:                if (script == NULL)
                    233:                        return (NULL);
                    234:                linenum = 0;
                    235:                switch (script->type) {
                    236:                case CU_FILE:
                    237:                        if ((f = fopen(script->s, "r")) == NULL)
1.29      mmcc      238:                                error(FATAL,
1.1       deraadt   239:                                    "%s: %s", script->s, strerror(errno));
                    240:                        fname = script->s;
                    241:                        state = ST_FILE;
                    242:                        goto again;
                    243:                case CU_STRING:
1.36      millert   244:                        len = snprintf(string_ident, sizeof(string_ident),
                    245:                            "\"%s\"", script->s);
                    246:                        if (len >= sizeof(string_ident))
1.7       deraadt   247:                                strlcpy(string_ident +
                    248:                                    sizeof(string_ident) - 6, " ...\"", 5);
1.1       deraadt   249:                        fname = string_ident;
                    250:                        s = script->s;
                    251:                        state = ST_STRING;
                    252:                        goto again;
                    253:                }
                    254:        case ST_FILE:
1.13      millert   255:                if ((p = fgetln(f, &len)) != NULL) {
1.1       deraadt   256:                        linenum++;
1.15      millert   257:                        if (len >= *outsize) {
1.13      millert   258:                                free(*outbuf);
1.15      millert   259:                                *outsize = ROUNDLEN(len + 1);
                    260:                                *outbuf = xmalloc(*outsize);
1.13      millert   261:                        }
                    262:                        memcpy(*outbuf, p, len);
                    263:                        (*outbuf)[len] = '\0';
                    264:                        if (linenum == 1 && p[0] == '#' && p[1] == 'n')
1.1       deraadt   265:                                nflag = 1;
1.13      millert   266:                        return (*outbuf);
1.1       deraadt   267:                }
                    268:                script = script->next;
                    269:                (void)fclose(f);
                    270:                state = ST_EOF;
                    271:                goto again;
                    272:        case ST_STRING:
                    273:                if (linenum == 0 && s[0] == '#' && s[1] == 'n')
                    274:                        nflag = 1;
1.13      millert   275:                p = *outbuf;
1.15      millert   276:                len = *outsize;
1.1       deraadt   277:                for (;;) {
1.15      millert   278:                        if (len <= 1) {
                    279:                                *outbuf = xrealloc(*outbuf,
                    280:                                    *outsize + _POSIX2_LINE_MAX);
                    281:                                p = *outbuf + *outsize - len;
                    282:                                len += _POSIX2_LINE_MAX;
                    283:                                *outsize += _POSIX2_LINE_MAX;
1.1       deraadt   284:                        }
                    285:                        switch (*s) {
                    286:                        case '\0':
                    287:                                state = ST_EOF;
                    288:                                if (s == script->s) {
                    289:                                        script = script->next;
                    290:                                        goto again;
                    291:                                } else {
                    292:                                        script = script->next;
                    293:                                        *p = '\0';
                    294:                                        linenum++;
1.13      millert   295:                                        return (*outbuf);
1.1       deraadt   296:                                }
                    297:                        case '\n':
                    298:                                *p++ = '\n';
                    299:                                *p = '\0';
                    300:                                s++;
                    301:                                linenum++;
1.13      millert   302:                                return (*outbuf);
1.1       deraadt   303:                        default:
                    304:                                *p++ = *s++;
1.15      millert   305:                                len--;
1.1       deraadt   306:                        }
                    307:                }
                    308:        }
1.34      krw       309:
                    310:        return (NULL);
1.1       deraadt   311: }
                    312:
1.38    ! martijn   313: void
        !           314: finish_file(void)
        !           315: {
        !           316:        if (infile != NULL) {
        !           317:                fclose(infile);
        !           318:                if (*oldfname != '\0') {
        !           319:                        if (rename(fname, oldfname) != 0) {
        !           320:                                warning("rename()");
        !           321:                                unlink(tmpfname);
        !           322:                                exit(1);
        !           323:                        }
        !           324:                        *oldfname = '\0';
        !           325:                }
        !           326:                if (*tmpfname != '\0') {
        !           327:                        if (outfile != NULL && outfile != stdout)
        !           328:                                fclose(outfile);
        !           329:                        outfile = NULL;
        !           330:                        rename(tmpfname, fname);
        !           331:                        *tmpfname = '\0';
        !           332:                }
        !           333:                outfname = NULL;
        !           334:        }
        !           335: }
        !           336:
1.1       deraadt   337: /*
                    338:  * Like fgets, but go through the list of files chaining them together.
                    339:  * Set len to the length of the line.
                    340:  */
                    341: int
1.9       deraadt   342: mf_fgets(SPACE *sp, enum e_spflag spflag)
1.1       deraadt   343: {
1.19      jasper    344:        struct stat sb;
1.1       deraadt   345:        size_t len;
1.2       deraadt   346:        char *p;
1.19      jasper    347:        int c, fd;
                    348:        static int firstfile;
                    349:
                    350:        if (infile == NULL) {
                    351:                /* stdin? */
                    352:                if (files->fname == NULL) {
                    353:                        if (inplace != NULL)
1.29      mmcc      354:                                error(FATAL, "-i may not be used with stdin");
1.19      jasper    355:                        infile = stdin;
                    356:                        fname = "stdin";
                    357:                        outfile = stdout;
                    358:                        outfname = "stdout";
                    359:                }
                    360:
                    361:                firstfile = 1;
                    362:        }
1.1       deraadt   363:
1.19      jasper    364:        for (;;) {
                    365:                if (infile != NULL && (c = getc(infile)) != EOF) {
                    366:                        (void)ungetc(c, infile);
                    367:                        break;
                    368:                }
                    369:                /* If we are here then either eof or no files are open yet */
                    370:                if (infile == stdin) {
                    371:                        sp->len = 0;
                    372:                        return (0);
                    373:                }
1.38    ! martijn   374:                finish_file();
1.19      jasper    375:                if (firstfile == 0)
                    376:                        files = files->next;
                    377:                else
                    378:                        firstfile = 0;
                    379:                if (files == NULL) {
                    380:                        sp->len = 0;
                    381:                        return (0);
                    382:                }
                    383:                fname = files->fname;
                    384:                if (inplace != NULL) {
                    385:                        if (lstat(fname, &sb) != 0)
1.30      jca       386:                                error(FATAL, "%s: %s", fname,
1.23      sthen     387:                                    strerror(errno ? errno : EIO));
1.19      jasper    388:                        if (!S_ISREG(sb.st_mode))
1.29      mmcc      389:                                error(FATAL, "%s: %s %s", fname,
1.19      jasper    390:                                    "in-place editing only",
                    391:                                    "works for regular files");
                    392:                        if (*inplace != '\0') {
                    393:                                strlcpy(oldfname, fname,
                    394:                                    sizeof(oldfname));
                    395:                                len = strlcat(oldfname, inplace,
                    396:                                    sizeof(oldfname));
                    397:                                if (len > sizeof(oldfname))
1.29      mmcc      398:                                        error(FATAL, "%s: name too long", fname);
1.1       deraadt   399:                        }
1.19      jasper    400:                        len = snprintf(tmpfname, sizeof(tmpfname), "%s/sedXXXXXXXXXX",
                    401:                            dirname(fname));
                    402:                        if (len >= sizeof(tmpfname))
1.29      mmcc      403:                                error(FATAL, "%s: name too long", fname);
1.19      jasper    404:                        if ((fd = mkstemp(tmpfname)) == -1)
1.31      tb        405:                                error(FATAL, "%s: %s", fname, strerror(errno));
1.19      jasper    406:                        if ((outfile = fdopen(fd, "w")) == NULL) {
                    407:                                unlink(tmpfname);
1.29      mmcc      408:                                error(FATAL, "%s", fname);
1.19      jasper    409:                        }
                    410:                        fchown(fileno(outfile), sb.st_uid, sb.st_gid);
                    411:                        fchmod(fileno(outfile), sb.st_mode & ALLPERMS);
                    412:                        outfname = tmpfname;
                    413:                        linenum = 0;
1.38    ! martijn   414:                        resetstate();
1.19      jasper    415:                } else {
                    416:                        outfile = stdout;
                    417:                        outfname = "stdout";
                    418:                }
                    419:                if ((infile = fopen(fname, "r")) == NULL) {
1.34      krw       420:                        warning("%s", strerror(errno));
1.19      jasper    421:                        rval = 1;
                    422:                        continue;
1.1       deraadt   423:                }
                    424:        }
                    425:
                    426:        /*
1.19      jasper    427:         * We are here only when infile is open and we still have something
                    428:         * to read from it.
                    429:         *
1.1       deraadt   430:         * Use fgetln so that we can handle essentially infinite input data.
                    431:         * Can't use the pointer into the stdio buffer as the process space
                    432:         * because the ungetc() can cause it to move.
                    433:         */
1.19      jasper    434:        p = fgetln(infile, &len);
                    435:        if (ferror(infile))
1.29      mmcc      436:                error(FATAL, "%s: %s", fname, strerror(errno ? errno : EIO));
1.19      jasper    437:        if (len != 0 && p[len - 1] == '\n') {
                    438:                sp->append_newline = 1;
                    439:                len--;
                    440:        } else if (!lastline()) {
                    441:                sp->append_newline = 1;
                    442:        } else {
                    443:                sp->append_newline = 0;
                    444:        }
1.1       deraadt   445:        cspace(sp, p, len, spflag);
                    446:
                    447:        linenum++;
1.19      jasper    448:
1.1       deraadt   449:        return (1);
                    450: }
                    451:
                    452: /*
                    453:  * Add a compilation unit to the linked list
                    454:  */
                    455: static void
1.9       deraadt   456: add_compunit(enum e_cut type, char *s)
1.1       deraadt   457: {
                    458:        struct s_compunit *cu;
                    459:
                    460:        cu = xmalloc(sizeof(struct s_compunit));
                    461:        cu->type = type;
                    462:        cu->s = s;
                    463:        cu->next = NULL;
                    464:        *cu_nextp = cu;
                    465:        cu_nextp = &cu->next;
                    466: }
                    467:
                    468: /*
                    469:  * Add a file to the linked list
                    470:  */
                    471: static void
1.9       deraadt   472: add_file(char *s)
1.1       deraadt   473: {
                    474:        struct s_flist *fp;
                    475:
                    476:        fp = xmalloc(sizeof(struct s_flist));
                    477:        fp->next = NULL;
                    478:        *fl_nextp = fp;
                    479:        fp->fname = s;
                    480:        fl_nextp = &fp->next;
1.19      jasper    481: }
                    482:
                    483:
                    484: static int
                    485: next_files_have_lines()
                    486: {
1.20      deraadt   487:        struct s_flist *file;
                    488:        FILE *file_fd;
                    489:        int ch;
                    490:
                    491:        file = files;
                    492:        while ((file = file->next) != NULL) {
                    493:                if ((file_fd = fopen(file->fname, "r")) == NULL)
                    494:                        continue;
1.19      jasper    495:
1.20      deraadt   496:                if ((ch = getc(file_fd)) != EOF) {
                    497:                        /*
                    498:                         * This next file has content, therefore current
                    499:                         * file doesn't contains the last line.
                    500:                         */
                    501:                        ungetc(ch, file_fd);
                    502:                        fclose(file_fd);
                    503:                        return (1);
                    504:                }
                    505:                fclose(file_fd);
                    506:        }
                    507:        return (0);
1.19      jasper    508: }
                    509:
                    510: int
                    511: lastline(void)
                    512: {
                    513:        int ch;
                    514:
                    515:        if (feof(infile)) {
                    516:                return !(
                    517:                    (inplace == NULL) &&
                    518:                    next_files_have_lines());
                    519:        }
                    520:        if ((ch = getc(infile)) == EOF) {
                    521:                return !(
                    522:                    (inplace == NULL) &&
                    523:                    next_files_have_lines());
                    524:        }
                    525:        ungetc(ch, infile);
                    526:        return (0);
1.1       deraadt   527: }