Home | History | Annotate | Line # | Download | only in sort
sort.c revision 1.49
      1 /*	$NetBSD: sort.c,v 1.49 2009/08/15 09:48:46 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.49 2009/08/15 09:48:46 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 ascii[NBINS], Rascii[NBINS], RFtable[NBINS], Ftable[NBINS];
    102 int SINGL_FLD = 0, SEP_FLAG = 0, UNIQUE = 0;
    103 
    104 /*
    105  * Default to stable sort.
    106  */
    107 int stable_sort = 1;
    108 
    109 static char toutpath[MAXPATHLEN];
    110 
    111 const char *tmpdir;	/* where temporary files should be put */
    112 
    113 static void cleanup(void);
    114 static void onsignal(int);
    115 static void usage(const char *);
    116 
    117 int main(int argc, char **argv);
    118 
    119 int
    120 main(int argc, char *argv[])
    121 {
    122 	get_func_t get;
    123 	int ch, i, stdinflag = 0, tmp = 0;
    124 	char cflag = 0, mflag = 0;
    125 	char *outfile, *outpath = 0;
    126 	struct field *fldtab, *p;
    127 	size_t fldtab_sz = 3, fidx = 0;
    128 	struct filelist filelist;
    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 = malloc(fldtab_sz * sizeof(*fldtab));
    146 	memset(fldtab, 0, fldtab_sz * sizeof(*fldtab));
    147 
    148 	fixit(&argc, argv);
    149 
    150 	if (!(tmpdir = getenv("TMPDIR")))
    151 		tmpdir = _PATH_TMP;
    152 
    153 	while ((ch = getopt(argc, argv, "bcdfik:mHno:rR:sSt:T:ux")) != -1) {
    154 		switch (ch) {
    155 		case 'b':
    156 			fldtab->flags |= BI | BT;
    157 			break;
    158 		case 'c':
    159 			cflag = 1;
    160 			break;
    161 		case 'd': case 'f': case 'i': case 'n': case 'r':
    162 			tmp |= optval(ch, 0);
    163 			if ((tmp & R) && (tmp & F))
    164 				fldtab->weights = RFtable;
    165 			else if (tmp & F)
    166 				fldtab->weights = Ftable;
    167 			else if (tmp & R)
    168 				fldtab->weights = Rascii;
    169 			fldtab->flags |= tmp;
    170 			break;
    171 		case 'H':
    172 			PANIC = 0;
    173 			break;
    174 		case 'k':
    175 			p = realloc(fldtab, (fldtab_sz + 1) * sizeof(*fldtab));
    176 			if (!p)
    177 				err(1, "realloc");
    178 			fldtab = p;
    179 			memset(&fldtab[fldtab_sz], 0,
    180 			    sizeof(fldtab[fldtab_sz]));
    181 			fldtab_sz++;
    182 
    183 			setfield(optarg, &fldtab[++fidx], fldtab->flags);
    184 			break;
    185 		case 'm':
    186 			mflag = 1;
    187 			break;
    188 		case 'o':
    189 			outpath = optarg;
    190 			break;
    191 		case 's':
    192 			/* for GNU sort compatibility (this is our default) */
    193 			stable_sort = 1;
    194 			break;
    195 		case 'S':
    196 			stable_sort = 0;
    197 			break;
    198 		case 't':
    199 			if (SEP_FLAG)
    200 				usage("multiple field delimiters");
    201 			SEP_FLAG = 1;
    202 			d_mask[' '] &= ~FLD_D;
    203 			d_mask['\t'] &= ~FLD_D;
    204 			d_mask[(u_char)*optarg] |= FLD_D;
    205 			if (d_mask[(u_char)*optarg] & REC_D_F)
    206 				errx(2, "record/field delimiter clash");
    207 			break;
    208 		case 'R':
    209 			if (REC_D != '\n')
    210 				usage("multiple record delimiters");
    211 			if ('\n' == (REC_D = *optarg))
    212 				break;
    213 			if (optarg[1] != '\0') {
    214 				char *ep;
    215 				int t = 0;
    216 				if (optarg[0] == '\\')
    217 					optarg++, t = 8;
    218 				REC_D = (int)strtol(optarg, &ep, t);
    219 				if (*ep != '\0' || REC_D < 0 ||
    220 				    REC_D >= (int)__arraycount(d_mask))
    221 					errx(2, "invalid record delimiter %s",
    222 					    optarg);
    223 			}
    224 			d_mask['\n'] = d_mask[' '];
    225 			d_mask[REC_D] = REC_D_F;
    226 			break;
    227 		case 'T':
    228 			/* -T tmpdir */
    229 			tmpdir = optarg;
    230 			break;
    231 		case 'u':
    232 			UNIQUE = 1;
    233 			break;
    234 		case '?':
    235 		default:
    236 			usage(NULL);
    237 		}
    238 	}
    239 	if (cflag && argc > optind+1)
    240 		errx(2, "too many input files for -c option");
    241 	if (argc - 2 > optind && !strcmp(argv[argc-2], "-o")) {
    242 		outpath = argv[argc-1];
    243 		argc -= 2;
    244 	}
    245 	if (mflag && argc - optind > (MAXFCT - (16+1))*16)
    246 		errx(2, "too many input files for -m option");
    247 	for (i = optind; i < argc; i++) {
    248 		/* allow one occurrence of /dev/stdin */
    249 		if (!strcmp(argv[i], "-") || !strcmp(argv[i], _PATH_STDIN)) {
    250 			if (stdinflag)
    251 				warnx("ignoring extra \"%s\" in file list",
    252 				    argv[i]);
    253 			else
    254 				stdinflag = 1;
    255 
    256 			/* change to /dev/stdin if '-' */
    257 			if (argv[i][0] == '-')
    258 				argv[i] = __UNCONST(_PATH_STDIN);
    259 
    260 		} else if ((ch = access(argv[i], R_OK)))
    261 			err(2, "%s", argv[i]);
    262 	}
    263 	if (!(fldtab->flags & (I|D|N) || fldtab[1].icol.num)) {
    264 		SINGL_FLD = 1;
    265 		fldtab[0].icol.num = 1;
    266 	} else {
    267 		if (!fldtab[1].icol.num) {
    268 			fldtab[0].flags &= ~(BI|BT);
    269 			setfield("1", &fldtab[++fidx], fldtab->flags);
    270 		}
    271 		fldreset(fldtab);
    272 		fldtab[0].flags &= ~F;
    273 	}
    274 	settables(fldtab[0].flags);
    275 	num_init();
    276 	fldtab->weights = gweights;
    277 	if (optind == argc) {
    278 		static const char * const names[] = { _PATH_STDIN, NULL };
    279 
    280 		filelist.names = names;
    281 		optind--;
    282 	} else
    283 		filelist.names = (const char * const *) &argv[optind];
    284 
    285 	if (SINGL_FLD)
    286 		get = makeline;
    287 	else
    288 		get = makekey;
    289 
    290 	if (cflag) {
    291 		order(&filelist, get, fldtab);
    292 		/* NOT REACHED */
    293 	}
    294 	if (!outpath) {
    295 		toutpath[0] = '\0';	/* path not used in this case */
    296 		outfile = outpath = toutpath;
    297 		outfp = stdout;
    298 	} else if (lstat(outpath, &st) == 0
    299 	    && !S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
    300 		/* output file exists and isn't character or block device */
    301 		struct sigaction act;
    302 		static const int sigtable[] = {SIGHUP, SIGINT, SIGPIPE,
    303 		    SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, 0};
    304 		int outfd;
    305 		errno = 0;
    306 		if (access(outpath, W_OK))
    307 			err(2, "%s", outpath);
    308 		(void)snprintf(toutpath, sizeof(toutpath), "%sXXXXXX",
    309 		    outpath);
    310 		if ((outfd = mkstemp(toutpath)) == -1)
    311 			err(2, "Cannot create temporary file `%s'", toutpath);
    312 		if ((outfp = fdopen(outfd, "w")) == NULL)
    313 			err(2, "Cannot open temporary file `%s'", toutpath);
    314 		outfile = toutpath;
    315 		(void)atexit(cleanup);
    316 		act.sa_handler = onsignal;
    317 		(void) sigemptyset(&act.sa_mask);
    318 		act.sa_flags = SA_RESTART | SA_RESETHAND;
    319 		for (i = 0; sigtable[i]; ++i)	/* always unlink toutpath */
    320 			sigaction(sigtable[i], &act, 0);
    321 	} else {
    322 		outfile = outpath;
    323 
    324 		if ((outfp = fopen(outfile, "w")) == NULL)
    325 			err(2, "output file %s", outfile);
    326 	}
    327 
    328 	if (mflag) {
    329 		fmerge(-1, 0, &filelist, argc-optind, get, outfp, putline,
    330 			fldtab);
    331 	} else
    332 		fsort(-1, 0, 0, &filelist, argc-optind, outfp, fldtab);
    333 
    334 	if (outfile != outpath) {
    335 		if (access(outfile, F_OK))
    336 			err(2, "%s", outfile);
    337 
    338 		/*
    339 		 * Copy file permissions bits of the original file.
    340 		 * st is initialized above, when we create the
    341 		 * temporary spool file.
    342 		 */
    343 		if (lchmod(outfile, st.st_mode & ALLPERMS) != 0) {
    344 			err(2, "cannot chmod %s: output left in %s",
    345 			    outpath, outfile);
    346 		}
    347 
    348 		(void)unlink(outpath);
    349 		if (link(outfile, outpath))
    350 			err(2, "cannot link %s: output left in %s",
    351 			    outpath, outfile);
    352 		(void)unlink(outfile);
    353 	}
    354 	exit(0);
    355 }
    356 
    357 static void
    358 onsignal(int sig)
    359 {
    360 	cleanup();
    361 }
    362 
    363 static void
    364 cleanup(void)
    365 {
    366 	if (toutpath[0])
    367 		(void)unlink(toutpath);
    368 }
    369 
    370 static void
    371 usage(const char *msg)
    372 {
    373 	if (msg != NULL)
    374 		(void)fprintf(stderr, "%s: %s\n", getprogname(), msg);
    375 	(void)fprintf(stderr,
    376 	    "usage: %s [-bcdfHimnrSsu] [-k field1[,field2]] [-o output]"
    377 	    " [-R char] [-T dir]", getprogname());
    378 	(void)fprintf(stderr,
    379 	    "             [-t char] [file ...]\n");
    380 	exit(2);
    381 }
    382