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