main.c 12 KB

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