Home | History | Annotate | Line # | Download | only in sort
sort.c revision 1.54
      1 /*	$NetBSD: sort.c,v 1.54 2009/09/05 09:16:18 dsl Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2000-2003 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Ben Harris and Jaromir Dolecek.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*-
     33  * Copyright (c) 1993
     34  *	The Regents of the University of California.  All rights reserved.
     35  *
     36  * This code is derived from software contributed to Berkeley by
     37  * Peter McIlroy.
     38  *
     39  * Redistribution and use in source and binary forms, with or without
     40  * modification, are permitted provided that the following conditions
     41  * are met:
     42  * 1. Redistributions of source code must retain the above copyright
     43  *    notice, this list of conditions and the following disclaimer.
     44  * 2. Redistributions in binary form must reproduce the above copyright
     45  *    notice, this list of conditions and the following disclaimer in the
     46  *    documentation and/or other materials provided with the distribution.
     47  * 3. Neither the name of the University nor the names of its contributors
     48  *    may be used to endorse or promote products derived from this software
     49  *    without specific prior written permission.
     50  *
     51  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     52  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     53  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     54  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     55  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     56  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     57  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     58  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     59  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     60  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     61  * SUCH DAMAGE.
     62  */
     63 
     64 /* Sort sorts a file using an optional user-defined key.
     65  * Sort uses radix sort for internal sorting, and allows
     66  * a choice of merge sort and radix sort for external sorting.
     67  */
     68 
     69 #include "sort.h"
     70 #include "fsort.h"
     71 #include "pathnames.h"
     72 
     73 #ifndef lint
     74 __COPYRIGHT("@(#) Copyright (c) 1993\
     75  The Regents of the University of California.  All rights reserved.");
     76 #endif /* not lint */
     77 
     78 #ifndef lint
     79 __RCSID("$NetBSD: sort.c,v 1.54 2009/09/05 09:16:18 dsl Exp $");
     80 __SCCSID("@(#)sort.c	8.1 (Berkeley) 6/6/93");
     81 #endif /* not lint */
     82 
     83 #include <sys/types.h>
     84 #include <sys/time.h>
     85 #include <sys/resource.h>
     86 
     87 #include <paths.h>
     88 #include <signal.h>
     89 #include <stdlib.h>
     90 #include <string.h>
     91 #include <unistd.h>
     92 #include <locale.h>
     93 
     94 int REC_D = '\n';
     95 u_char d_mask[NBINS];		/* flags for rec_d, field_d, <blank> */
     96 
     97 /*
     98  * weight tables.  Gweights is one of ascii, Rascii..
     99  * modified to weight rec_d = 0 (or 255)
    100  */
    101 u_char *const weight_tables[4] = { ascii, Rascii, Ftable, RFtable };
    102 u_char ascii[NBINS], Rascii[NBINS], RFtable[NBINS], Ftable[NBINS];
    103 u_char unweighted[NBINS];
    104 int SINGL_FLD = 0, SEP_FLAG = 0, UNIQUE = 0;
    105 
    106 unsigned int debug_flags = 0;
    107 
    108 static char toutpath[MAXPATHLEN];
    109 
    110 const char *tmpdir;	/* where temporary files should be put */
    111 
    112 static void cleanup(void);
    113 static void onsignal(int);
    114 static void usage(const char *);
    115 
    116 int main(int argc, char **argv);
    117 
    118 int
    119 main(int argc, char *argv[])
    120 {
    121 	get_func_t get;
    122 	int ch, i, stdinflag = 0;
    123 	char cflag = 0, mflag = 0;
    124 	char *outfile, *outpath = 0;
    125 	struct field *fldtab, *p;
    126 	size_t fldtab_sz, fld_cnt;
    127 	struct filelist filelist;
    128 	int num_input_files;
    129 	FILE *outfp = NULL;
    130 	struct rlimit rl;
    131 	struct stat st;
    132 
    133 	setlocale(LC_ALL, "");
    134 
    135 	/* bump RLIMIT_NOFILE to maximum our hard limit allows */
    136 	if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
    137 		err(2, "getrlimit");
    138 	rl.rlim_cur = rl.rlim_max;
    139 	if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
    140 		err(2, "setrlimit");
    141 
    142 	d_mask[REC_D = '\n'] = REC_D_F;
    143 	d_mask['\t'] = d_mask[' '] = BLANK | FLD_D;
    144 
    145 	/* fldtab[0] is the global options. */
    146 	fldtab_sz = 3;
    147 	fld_cnt = 0;
    148 	fldtab = malloc(fldtab_sz * sizeof(*fldtab));
    149 	memset(fldtab, 0, fldtab_sz * sizeof(*fldtab));
    150 
    151 	/* Convert "+field" args to -f format */
    152 	fixit(&argc, argv);
    153 
    154 	if (!(tmpdir = getenv("TMPDIR")))
    155 		tmpdir = _PATH_TMP;
    156 
    157 	while ((ch = getopt(argc, argv, "bcdD:fik:mHno:rR:sSt:T:ux")) != -1) {
    158 		switch (ch) {
    159 		case 'b':
    160 			fldtab[0].flags |= BI | BT;
    161 			break;
    162 		case 'c':
    163 			cflag = 1;
    164 			break;
    165 		case 'D': /* Debug flags */
    166 			for (i = 0; optarg[i]; i++)
    167 			    debug_flags |= 1 << (optarg[i] & 31);
    168 			break;
    169 		case 'd': case 'f': case 'i': case 'n': case 'r':
    170 			fldtab[0].flags |= optval(ch, 0);
    171 			break;
    172 		case 'H':
    173 			/* -H was ; use merge sort for blocks of large files' */
    174 			/* That is now the default. */
    175 			break;
    176 		case 'k':
    177 			p = realloc(fldtab, (fldtab_sz + 1) * sizeof(*fldtab));
    178 			if (!p)
    179 				err(1, "realloc");
    180 			fldtab = p;
    181 			memset(&fldtab[fldtab_sz], 0, sizeof(fldtab[0]));
    182 			fldtab_sz++;
    183 
    184 			setfield(optarg, &fldtab[++fld_cnt], fldtab[0].flags);
    185 			break;
    186 		case 'm':
    187 			mflag = 1;
    188 			break;
    189 		case 'o':
    190 			outpath = optarg;
    191 			break;
    192 		case 's':
    193 			/*
    194 			 * Nominally 'stable sort', keep lines with equal keys
    195 			 * in input file order. (Default for NetBSD)
    196 			 * (-s for GNU sort compatibility.)
    197 			 */
    198 			break;
    199 		case 'S':
    200 			/*
    201 			 * Reverse of -s!
    202 			 * This needs to enforce a POSIX sort where records
    203 			 * with equal keys are then sorted by the raw data.
    204 			 * Currently not implemented!
    205 			 * (using libc radixsort() v sradixsort() doesn't
    206 			 * have the desired effect.)
    207 			 */
    208 			break;
    209 		case 't':
    210 			if (SEP_FLAG)
    211 				usage("multiple field delimiters");
    212 			SEP_FLAG = 1;
    213 			d_mask[' '] &= ~FLD_D;
    214 			d_mask['\t'] &= ~FLD_D;
    215 			d_mask[(u_char)*optarg] |= FLD_D;
    216 			if (d_mask[(u_char)*optarg] & REC_D_F)
    217 				errx(2, "record/field delimiter clash");
    218 			break;
    219 		case 'R':
    220 			if (REC_D != '\n')
    221 				usage("multiple record delimiters");
    222 			REC_D = *optarg;
    223 			if (REC_D == '\n')
    224 				break;
    225 			if (optarg[1] != '\0') {
    226 				char *ep;
    227 				int t = 0;
    228 				if (optarg[0] == '\\')
    229 					optarg++, t = 8;
    230 				REC_D = (int)strtol(optarg, &ep, t);
    231 				if (*ep != '\0' || REC_D < 0 ||
    232 				    REC_D >= (int)__arraycount(d_mask))
    233 					errx(2, "invalid record delimiter %s",
    234 					    optarg);
    235 			}
    236 			d_mask['\n'] = d_mask[' '];
    237 			d_mask[REC_D] = REC_D_F;
    238 			break;
    239 		case 'T':
    240 			/* -T tmpdir */
    241 			tmpdir = optarg;
    242 			break;
    243 		case 'u':
    244 			UNIQUE = 1;
    245 			break;
    246 		case '?':
    247 		default:
    248 			usage(NULL);
    249 		}
    250 	}
    251 
    252 	if (cflag && argc > optind+1)
    253 		errx(2, "too many input files for -c option");
    254 	if (argc - 2 > optind && !strcmp(argv[argc-2], "-o")) {
    255 		outpath = argv[argc-1];
    256 		argc -= 2;
    257 	}
    258 	if (mflag && argc - optind > (MAXFCT - (16+1))*16)
    259 		errx(2, "too many input files for -m option");
    260 
    261 	for (i = optind; i < argc; i++) {
    262 		/* allow one occurrence of /dev/stdin */
    263 		if (!strcmp(argv[i], "-") || !strcmp(argv[i], _PATH_STDIN)) {
    264 			if (stdinflag)
    265 				warnx("ignoring extra \"%s\" in file list",
    266 				    argv[i]);
    267 			else
    268 				stdinflag = 1;
    269 
    270 			/* change to /dev/stdin if '-' */
    271 			if (argv[i][0] == '-') {
    272 				static char path_stdin[] = _PATH_STDIN;
    273 				argv[i] = path_stdin;
    274 			}
    275 
    276 		} else if ((ch = access(argv[i], R_OK)))
    277 			err(2, "%s", argv[i]);
    278 	}
    279 
    280 	if (!(fldtab[0].flags & (I|D|N) || fldtab[1].icol.num)) {
    281 		SINGL_FLD = 1;
    282 		fldtab[0].icol.num = 1;
    283 		fldtab[0].weights = weight_tables[fldtab->flags & (R | F)];
    284 	} else {
    285 		if (!fldtab[1].icol.num) {
    286 			fldtab[0].flags &= ~(BI|BT);
    287 			setfield("1", &fldtab[++fld_cnt], fldtab->flags);
    288 		}
    289 		fldreset(fldtab);
    290 	}
    291 	settables();
    292 
    293 	if (optind == argc) {
    294 		static const char * const names[] = { _PATH_STDIN, NULL };
    295 		filelist.names = names;
    296 		num_input_files = 1;
    297 	} else {
    298 		filelist.names = (const char * const *) &argv[optind];
    299 		num_input_files = argc - optind;
    300 	}
    301 
    302 	if (SINGL_FLD)
    303 		get = makeline;
    304 	else
    305 		get = makekey;
    306 
    307 	if (cflag) {
    308 		order(&filelist, get, fldtab);
    309 		/* NOT REACHED */
    310 	}
    311 	if (!outpath) {
    312 		toutpath[0] = '\0';	/* path not used in this case */
    313 		outfile = outpath = toutpath;
    314 		outfp = stdout;
    315 	} else if (lstat(outpath, &st) == 0
    316 	    && !S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
    317 		/* output file exists and isn't character or block device */
    318 		struct sigaction act;
    319 		static const int sigtable[] = {SIGHUP, SIGINT, SIGPIPE,
    320 		    SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, 0};
    321 		int outfd;
    322 		errno = 0;
    323 		if (access(outpath, W_OK))
    324 			err(2, "%s", outpath);
    325 		(void)snprintf(toutpath, sizeof(toutpath), "%sXXXXXX",
    326 		    outpath);
    327 		if ((outfd = mkstemp(toutpath)) == -1)
    328 			err(2, "Cannot create temporary file `%s'", toutpath);
    329 		(void)atexit(cleanup);
    330 		act.sa_handler = onsignal;
    331 		(void) sigemptyset(&act.sa_mask);
    332 		act.sa_flags = SA_RESTART | SA_RESETHAND;
    333 		for (i = 0; sigtable[i]; ++i)	/* always unlink toutpath */
    334 			sigaction(sigtable[i], &act, 0);
    335 		outfile = toutpath;
    336 		if ((outfp = fdopen(outfd, "w")) == NULL)
    337 			err(2, "Cannot open temporary file `%s'", toutpath);
    338 	} else {
    339 		outfile = outpath;
    340 
    341 		if ((outfp = fopen(outfile, "w")) == NULL)
    342 			err(2, "output file %s", outfile);
    343 	}
    344 
    345 	if (mflag) {
    346 		fmerge(-1, &filelist, num_input_files, get, outfp, putline,
    347 			fldtab);
    348 	} else
    349 		fsort(&filelist, num_input_files, outfp, fldtab);
    350 
    351 	if (outfile != outpath) {
    352 		if (access(outfile, F_OK))
    353 			err(2, "%s", outfile);
    354 
    355 		/*
    356 		 * Copy file permissions bits of the original file.
    357 		 * st is initialized above, when we create the
    358 		 * temporary spool file.
    359 		 */
    360 		if (lchmod(outfile, st.st_mode & ALLPERMS) != 0) {
    361 			err(2, "cannot chmod %s: output left in %s",
    362 			    outpath, outfile);
    363 		}
    364 
    365 		(void)unlink(outpath);
    366 		if (link(outfile, outpath))
    367 			err(2, "cannot link %s: output left in %s",
    368 			    outpath, outfile);
    369 		(void)unlink(outfile);
    370 		toutpath[0] = 0;
    371 	}
    372 	exit(0);
    373 }
    374 
    375 static void
    376 onsignal(int sig)
    377 {
    378 	cleanup();
    379 }
    380 
    381 static void
    382 cleanup(void)
    383 {
    384 	if (toutpath[0])
    385 		(void)unlink(toutpath);
    386 }
    387 
    388 static void
    389 usage(const char *msg)
    390 {
    391 	if (msg != NULL)
    392 		(void)fprintf(stderr, "%s: %s\n", getprogname(), msg);
    393 	(void)fprintf(stderr,
    394 	    "usage: %s [-bcdfHimnrSsu] [-k field1[,field2]] [-o output]"
    395 	    " [-R char] [-T dir]", getprogname());
    396 	(void)fprintf(stderr,
    397 	    "             [-t char] [file ...]\n");
    398 	exit(2);
    399 }
    400