xref: /freebsd/usr.bin/sort/sort.c (revision 1aaed33edb24c98a09130cd66667d6a795b6b2a8)
1 /*-
2  * Copyright (C) 2009 Gabor Kovesdan <gabor@FreeBSD.org>
3  * Copyright (C) 2012 Oleg Moskalenko <oleg.moskalenko@citrix.com>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include <sys/stat.h>
32 #include <sys/sysctl.h>
33 #include <sys/types.h>
34 
35 #include <err.h>
36 #include <errno.h>
37 #include <getopt.h>
38 #include <limits.h>
39 #include <locale.h>
40 #include <md5.h>
41 #include <regex.h>
42 #include <signal.h>
43 #include <stdbool.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 #include <wchar.h>
49 #include <wctype.h>
50 
51 #include "coll.h"
52 #include "file.h"
53 #include "sort.h"
54 
55 #ifndef WITHOUT_NLS
56 #include <nl_types.h>
57 nl_catd catalog;
58 #endif
59 
60 #define	OPTIONS	"bcCdfghik:Mmno:RrsS:t:T:uVz"
61 
62 #define DEFAULT_RANDOM_SORT_SEED_FILE ("/dev/random")
63 #define MAX_DEFAULT_RANDOM_SEED_DATA_SIZE (1024)
64 
65 static bool need_random = false;
66 static const char* random_source = DEFAULT_RANDOM_SORT_SEED_FILE;
67 static const void* random_seed = NULL;
68 static size_t random_seed_size = 0;
69 
70 MD5_CTX md5_ctx;
71 
72 /*
73  * Default messages to use when NLS is disabled or no catalogue
74  * is found.
75  */
76 const char *nlsstr[] = { "",
77 /* 1*/"you cannot use -%c and -%c together",
78 /* 2*/"extra argument not allowed with -c",
79 /* 3*/"Unknown feature: %s",
80 /* 4*/"Wrong memory buffer specification",
81 /* 5*/"0 field in key specs",
82 /* 6*/"0 column in key specs",
83 /* 7*/"Wrong file mode",
84 /* 8*/"Cannot open file for reading",
85 /* 9*/"Radix sort cannot be used with these sort options",
86 /*10*/"The chosen sort method cannot be used with stable and/or unique sort",
87 /*11*/"Invalid key position",
88 /*12*/"Usage: %s [-bcCdfigMmnrsuz] [-kPOS1[,POS2] ... ] "
89       "[+POS1 [-POS2]] [-S memsize] [-T tmpdir] [-t separator] "
90       "[-o outfile] [--batch-size size] [--files0-from file] "
91       "[--heapsort] [--mergesort] [--radixsort] [--qsort] "
92 #if defined(SORT_THREADS)
93       "[--nthreads thread_no] "
94 #endif
95       "[--human-numeric-sort] "
96       "[--version-sort] [--random-sort [--random-source file]] "
97       "[--compress-program program] [file ...]\n" };
98 
99 struct sort_opts sort_opts_vals;
100 
101 bool debug_sort = false;
102 bool need_hint = false;
103 
104 #if defined(SORT_THREADS)
105 size_t ncpu = 1;
106 size_t nthreads = 1;
107 #endif
108 
109 static bool gnusort_numeric_compatibility = false;
110 
111 static struct sort_mods default_sort_mods_object;
112 struct sort_mods * const default_sort_mods = &default_sort_mods_object;
113 
114 static bool print_symbols_on_debug = false;
115 
116 /*
117  * Arguments from file (when file0-from option is used:
118  */
119 static int argc_from_file0 = -1;
120 static char **argv_from_file0 = NULL;
121 
122 /*
123  * Placeholder symbols for options which have no single-character equivalent
124  */
125 enum
126 {
127 	SORT_OPT = CHAR_MAX + 1,
128 	HELP_OPT,
129 	FF_OPT,
130 	BS_OPT,
131 	VERSION_OPT,
132 	DEBUG_OPT,
133 #if defined(SORT_THREADS)
134 	NTHREADS_OPT,
135 #endif
136 	RANDOMSOURCE_OPT,
137 	COMPRESSPROGRAM_OPT,
138 	QSORT_OPT,
139 	MERGESORT_OPT,
140 	HEAPSORT_OPT,
141 	RADIXSORT_OPT
142 };
143 
144 #define	NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS 6
145 static const char mutually_exclusive_flags[NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS] = { 'M', 'n', 'g', 'R', 'h', 'V' };
146 
147 struct option long_options[] = {
148 				{ "batch-size", required_argument, NULL, BS_OPT },
149 				{ "buffer-size", required_argument, NULL, 'S' },
150 				{ "check", optional_argument, NULL, 'c' },
151 				{ "check=silent|quiet", optional_argument, NULL, 'C' },
152 				{ "compress-program", required_argument, NULL, COMPRESSPROGRAM_OPT },
153 				{ "debug", no_argument, NULL, DEBUG_OPT },
154 				{ "dictionary-order", no_argument, NULL, 'd' },
155 				{ "field-separator", required_argument, NULL, 't' },
156 				{ "files0-from", required_argument, NULL, FF_OPT },
157 				{ "general-numeric-sort", no_argument, NULL, 'g' },
158 				{ "heapsort", no_argument, NULL, HEAPSORT_OPT },
159 				{ "help",no_argument, NULL, HELP_OPT },
160 				{ "human-numeric-sort", no_argument, NULL, 'h' },
161 				{ "ignore-leading-blanks", no_argument, NULL, 'b' },
162 				{ "ignore-case", no_argument, NULL, 'f' },
163 				{ "ignore-nonprinting", no_argument, NULL, 'i' },
164 				{ "key", required_argument, NULL, 'k' },
165 				{ "merge", no_argument, NULL, 'm' },
166 				{ "mergesort", no_argument, NULL, MERGESORT_OPT },
167 				{ "month-sort", no_argument, NULL, 'M' },
168 				{ "numeric-sort", no_argument, NULL, 'n' },
169 				{ "output", required_argument, NULL, 'o' },
170 #if defined(SORT_THREADS)
171 				{ "nthreads", required_argument, NULL, NTHREADS_OPT },
172 #endif
173 				{ "qsort", no_argument, NULL, QSORT_OPT },
174 				{ "radixsort", no_argument, NULL, RADIXSORT_OPT },
175 				{ "random-sort", no_argument, NULL, 'R' },
176 				{ "random-source", required_argument, NULL, RANDOMSOURCE_OPT },
177 				{ "reverse", no_argument, NULL, 'r' },
178 				{ "sort", required_argument, NULL, SORT_OPT },
179 				{ "stable", no_argument, NULL, 's' },
180 				{ "temporary-directory",required_argument, NULL, 'T' },
181 				{ "unique", no_argument, NULL, 'u' },
182 				{ "version", no_argument, NULL, VERSION_OPT },
183 				{ "version-sort",no_argument, NULL, 'V' },
184 				{ "zero-terminated", no_argument, NULL, 'z' },
185 				{ NULL, no_argument, NULL, 0 }
186 };
187 
188 void fix_obsolete_keys(int *argc, char **argv);
189 
190 /*
191  * Check where sort modifier is present
192  */
193 static bool
194 sort_modifier_empty(struct sort_mods *sm)
195 {
196 
197 	if (sm == NULL)
198 		return (true);
199 	return (!(sm->Mflag || sm->Vflag || sm->nflag || sm->gflag ||
200 	    sm->rflag || sm->Rflag || sm->hflag || sm->dflag || sm->fflag));
201 }
202 
203 /*
204  * Print out usage text.
205  */
206 static void
207 usage(bool opt_err)
208 {
209 	struct option *o;
210 	FILE *out;
211 
212 	out = stdout;
213 	o = &(long_options[0]);
214 
215 	if (opt_err)
216 		out = stderr;
217 	fprintf(out, getstr(12), getprogname());
218 	if (opt_err)
219 		exit(2);
220 	exit(0);
221 }
222 
223 /*
224  * Read input file names from a file (file0-from option).
225  */
226 static void
227 read_fns_from_file0(const char *fn)
228 {
229 	if (fn) {
230 		struct file0_reader f0r;
231 		FILE *f;
232 
233 		f = fopen(fn, "r");
234 		if (f == NULL)
235 			err(2, NULL);
236 
237 		memset(&f0r, 0, sizeof(f0r));
238 		f0r.f = f;
239 
240 		while (!feof(f)) {
241 			char *line = read_file0_line(&f0r);
242 
243 			if (line && *line) {
244 				++argc_from_file0;
245 				if (argc_from_file0 < 1)
246 					argc_from_file0 = 1;
247 				argv_from_file0 = sort_realloc(argv_from_file0,
248 				    argc_from_file0 * sizeof(char *));
249 				if (argv_from_file0 == NULL)
250 					err(2, NULL);
251 				argv_from_file0[argc_from_file0 - 1] =
252 				    sort_strdup(line);
253 			}
254 		}
255 		closefile(f, fn);
256 	}
257 }
258 
259 /*
260  * Check how much RAM is available for the sort.
261  */
262 static void
263 set_hw_params(void)
264 {
265 #if defined(SORT_THREADS)
266 	size_t ncpusz;
267 #endif
268 	size_t pages, psize, psz, pszsz;
269 
270 	pages = psize = 0;
271 #if defined(SORT_THREADS)
272 	ncpu = 1;
273 	ncpusz = sizeof(size_t);
274 #endif
275 	psz = pszsz = sizeof(size_t);
276 
277 	if (sysctlbyname("vm.stats.vm.v_free_count", &pages, &psz,
278 	    NULL, 0) < 0) {
279 		perror("vm.stats.vm.v_free_count");
280 		return;
281 	}
282 	if (sysctlbyname("vm.stats.vm.v_page_size", &psize, &pszsz,
283 	    NULL, 0) < 0) {
284 		perror("vm.stats.vm.v_page_size");
285 		return;
286 	}
287 #if defined(SORT_THREADS)
288 	if (sysctlbyname("hw.ncpu", &ncpu, &ncpusz,
289 	    NULL, 0) < 0)
290 		ncpu = 1;
291 	else if(ncpu > 32)
292 		ncpu = 32;
293 
294 	nthreads = ncpu;
295 #endif
296 
297 	free_memory = (unsigned long long) pages * (unsigned long long) psize;
298 	available_free_memory = (free_memory * 9) / 10;
299 }
300 
301 /*
302  * Convert "plain" symbol to wide symbol, with default value.
303  */
304 static void
305 conv_mbtowc(wchar_t *wc, const char *c, const wchar_t def)
306 {
307 
308 	if (wc && c) {
309 		int res;
310 
311 		res = mbtowc(wc, c, MB_CUR_MAX);
312 		if (res < 1)
313 			*wc = def;
314 	}
315 }
316 
317 /*
318  * Set current locale symbols.
319  */
320 static void
321 set_locale(void)
322 {
323 	struct lconv *lc;
324 	const char *locale;
325 
326 	setlocale(LC_ALL, "");
327 
328 	lc = localeconv();
329 
330 	if (lc) {
331 		/* obtain LC_NUMERIC info */
332 		/* Convert to wide char form */
333 		conv_mbtowc(&symbol_decimal_point, lc->decimal_point,
334 		    symbol_decimal_point);
335 		conv_mbtowc(&symbol_thousands_sep, lc->thousands_sep,
336 		    symbol_thousands_sep);
337 		conv_mbtowc(&symbol_positive_sign, lc->positive_sign,
338 		    symbol_positive_sign);
339 		conv_mbtowc(&symbol_negative_sign, lc->negative_sign,
340 		    symbol_negative_sign);
341 	}
342 
343 	if (getenv("GNUSORT_NUMERIC_COMPATIBILITY"))
344 		gnusort_numeric_compatibility = true;
345 
346 	locale = setlocale(LC_COLLATE, NULL);
347 
348 	if (locale) {
349 		char *tmpl;
350 		const char *cclocale;
351 
352 		tmpl = sort_strdup(locale);
353 		cclocale = setlocale(LC_COLLATE, "C");
354 		if (cclocale && !strcmp(cclocale, tmpl))
355 			byte_sort = true;
356 		else {
357 			const char *pclocale;
358 
359 			pclocale = setlocale(LC_COLLATE, "POSIX");
360 			if (pclocale && !strcmp(pclocale, tmpl))
361 				byte_sort = true;
362 		}
363 		setlocale(LC_COLLATE, tmpl);
364 		sort_free(tmpl);
365 	}
366 }
367 
368 /*
369  * Set directory temporary files.
370  */
371 static void
372 set_tmpdir(void)
373 {
374 	char *td;
375 
376 	td = getenv("TMPDIR");
377 	if (td != NULL)
378 		tmpdir = sort_strdup(td);
379 }
380 
381 /*
382  * Parse -S option.
383  */
384 static unsigned long long
385 parse_memory_buffer_value(const char *value)
386 {
387 
388 	if (value == NULL)
389 		return (available_free_memory);
390 	else {
391 		char *endptr;
392 		unsigned long long membuf;
393 
394 		endptr = NULL;
395 		errno = 0;
396 		membuf = strtoll(value, &endptr, 10);
397 
398 		if (errno != 0) {
399 			warn(getstr(4));
400 			membuf = available_free_memory;
401 		} else {
402 			switch (*endptr){
403 			case 'Y':
404 				membuf *= 1024;
405 				/* FALLTHROUGH */
406 			case 'Z':
407 				membuf *= 1024;
408 				/* FALLTHROUGH */
409 			case 'E':
410 				membuf *= 1024;
411 				/* FALLTHROUGH */
412 			case 'P':
413 				membuf *= 1024;
414 				/* FALLTHROUGH */
415 			case 'T':
416 				membuf *= 1024;
417 				/* FALLTHROUGH */
418 			case 'G':
419 				membuf *= 1024;
420 				/* FALLTHROUGH */
421 			case 'M':
422 				membuf *= 1024;
423 				/* FALLTHROUGH */
424 			case '\0':
425 			case 'K':
426 				membuf *= 1024;
427 				/* FALLTHROUGH */
428 			case 'b':
429 				break;
430 			case '%':
431 				membuf = (available_free_memory * membuf) /
432 				    100;
433 				break;
434 			default:
435 				fprintf(stderr, "%s: %s\n", strerror(EINVAL),
436 				   optarg);
437 				membuf = available_free_memory;
438 			}
439 		}
440 		return (membuf);
441 	}
442 }
443 
444 /*
445  * Signal handler that clears the temporary files.
446  */
447 static void
448 sig_handler(int sig, siginfo_t *siginfo, void *context)
449 {
450 
451 	sig = sig;
452 	siginfo = siginfo;
453 	context = context;
454 	clear_tmp_files();
455 	exit(-1);
456 }
457 
458 /*
459  * Set signal handler on panic signals.
460  */
461 static void
462 set_signal_handler(void)
463 {
464 	struct sigaction sa;
465 
466 	memset(&sa, 0, sizeof(sa));
467 	sa.sa_sigaction = &sig_handler;
468 	sa.sa_flags = SA_SIGINFO;
469 
470 	if (sigaction(SIGTERM, &sa, NULL) < 0) {
471 		perror("sigaction");
472 		return;
473 	}
474 	if (sigaction(SIGHUP, &sa, NULL) < 0) {
475 		perror("sigaction");
476 		return;
477 	}
478 	if (sigaction(SIGINT, &sa, NULL) < 0) {
479 		perror("sigaction");
480 		return;
481 	}
482 	if (sigaction(SIGQUIT, &sa, NULL) < 0) {
483 		perror("sigaction");
484 		return;
485 	}
486 	if (sigaction(SIGABRT, &sa, NULL) < 0) {
487 		perror("sigaction");
488 		return;
489 	}
490 	if (sigaction(SIGBUS, &sa, NULL) < 0) {
491 		perror("sigaction");
492 		return;
493 	}
494 	if (sigaction(SIGSEGV, &sa, NULL) < 0) {
495 		perror("sigaction");
496 		return;
497 	}
498 	if (sigaction(SIGUSR1, &sa, NULL) < 0) {
499 		perror("sigaction");
500 		return;
501 	}
502 	if (sigaction(SIGUSR2, &sa, NULL) < 0) {
503 		perror("sigaction");
504 		return;
505 	}
506 }
507 
508 /*
509  * Print "unknown" message and exit with status 2.
510  */
511 static void
512 unknown(const char *what)
513 {
514 
515 	errx(2, getstr(3), what);
516 }
517 
518 /*
519  * Check whether contradictory input options are used.
520  */
521 static void
522 check_mutually_exclusive_flags(char c, bool *mef_flags)
523 {
524 	int fo_index, mec;
525 	bool found_others, found_this;
526 
527 	found_others = found_this =false;
528 	fo_index = 0;
529 
530 	for (int i = 0; i < NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS; i++) {
531 		mec = mutually_exclusive_flags[i];
532 
533 		if (mec != c) {
534 			if (mef_flags[i]) {
535 				if (found_this)
536 					errx(1, getstr(1), c, mec);
537 				found_others = true;
538 				fo_index = i;
539 			}
540 		} else {
541 			if (found_others)
542 				errx(1, getstr(1), c,
543 				    mutually_exclusive_flags[fo_index]);
544 			mef_flags[i] = true;
545 			found_this = true;
546 		}
547 	}
548 }
549 
550 /*
551  * Initialise sort opts data.
552  */
553 static void
554 set_sort_opts(void)
555 {
556 
557 	memset(&default_sort_mods_object, 0,
558 	    sizeof(default_sort_mods_object));
559 	memset(&sort_opts_vals, 0, sizeof(sort_opts_vals));
560 	default_sort_mods_object.func =
561 	    get_sort_func(&default_sort_mods_object);
562 }
563 
564 /*
565  * Set a sort modifier on a sort modifiers object.
566  */
567 static bool
568 set_sort_modifier(struct sort_mods *sm, int c)
569 {
570 
571 	if (sm) {
572 		switch (c){
573 		case 'b':
574 			sm->bflag = true;
575 			break;
576 		case 'd':
577 			sm->dflag = true;
578 			break;
579 		case 'f':
580 			sm->fflag = true;
581 			break;
582 		case 'g':
583 			sm->gflag = true;
584 			need_hint = true;
585 			break;
586 		case 'i':
587 			sm->iflag = true;
588 			break;
589 		case 'R':
590 			sm->Rflag = true;
591 			need_random = true;
592 			break;
593 		case 'M':
594 			initialise_months();
595 			sm->Mflag = true;
596 			need_hint = true;
597 			break;
598 		case 'n':
599 			sm->nflag = true;
600 			need_hint = true;
601 			print_symbols_on_debug = true;
602 			break;
603 		case 'r':
604 			sm->rflag = true;
605 			break;
606 		case 'V':
607 			sm->Vflag = true;
608 			break;
609 		case 'h':
610 			sm->hflag = true;
611 			need_hint = true;
612 			print_symbols_on_debug = true;
613 			break;
614 		default:
615 			return false;
616 		}
617 		sort_opts_vals.complex_sort = true;
618 		sm->func = get_sort_func(sm);
619 	}
620 	return (true);
621 }
622 
623 /*
624  * Parse POS in -k option.
625  */
626 static int
627 parse_pos(const char *s, struct key_specs *ks, bool *mef_flags, bool second)
628 {
629 	regmatch_t pmatch[4];
630 	regex_t re;
631 	char *c, *f;
632 	const char *sregexp = "^([0-9]+)(\\.[0-9]+)?([bdfirMngRhV]+)?$";
633 	size_t len, nmatch;
634 	int ret;
635 
636 	ret = -1;
637 	nmatch = 4;
638 	c = f = NULL;
639 
640 	if (regcomp(&re, sregexp, REG_EXTENDED) != 0)
641 		return (-1);
642 
643 	if (regexec(&re, s, nmatch, pmatch, 0) != 0)
644 		goto end;
645 
646 	if (pmatch[0].rm_eo <= pmatch[0].rm_so)
647 		goto end;
648 
649 	if (pmatch[1].rm_eo <= pmatch[1].rm_so)
650 		goto end;
651 
652 	len = pmatch[1].rm_eo - pmatch[1].rm_so;
653 	f = sort_malloc((len + 1) * sizeof(char));
654 
655 	strncpy(f, s + pmatch[1].rm_so, len);
656 	f[len] = '\0';
657 
658 	if (second) {
659 		errno = 0;
660 		ks->f2 = (size_t) strtoul(f, NULL, 10);
661 		if (errno != 0)
662 			errx(2, "%s: -k", strerror(errno));
663 		if (ks->f2 == 0) {
664 			warn(getstr(5));
665 			goto end;
666 		}
667 	} else {
668 		errno = 0;
669 		ks->f1 = (size_t) strtoul(f, NULL, 10);
670 		if (errno != 0)
671 			errx(2, "%s: -k", strerror(errno));
672 		if (ks->f1 == 0) {
673 			warn(getstr(5));
674 			goto end;
675 		}
676 	}
677 
678 	if (pmatch[2].rm_eo > pmatch[2].rm_so) {
679 		len = pmatch[2].rm_eo - pmatch[2].rm_so - 1;
680 		c = sort_malloc((len + 1) * sizeof(char));
681 
682 		strncpy(c, s + pmatch[2].rm_so + 1, len);
683 		c[len] = '\0';
684 
685 		if (second) {
686 			errno = 0;
687 			ks->c2 = (size_t) strtoul(c, NULL, 10);
688 			if (errno != 0)
689 				errx(2, "%s: -k", strerror(errno));
690 		} else {
691 			errno = 0;
692 			ks->c1 = (size_t) strtoul(c, NULL, 10);
693 			if (errno != 0)
694 				errx(2, "%s: -k", strerror(errno));
695 			if (ks->c1 == 0) {
696 				warn(getstr(6));
697 				goto end;
698 			}
699 		}
700 	} else {
701 		if (second)
702 			ks->c2 = 0;
703 		else
704 			ks->c1 = 1;
705 	}
706 
707 	if (pmatch[3].rm_eo > pmatch[3].rm_so) {
708 		regoff_t i = 0;
709 
710 		for (i = pmatch[3].rm_so; i < pmatch[3].rm_eo; i++) {
711 			check_mutually_exclusive_flags(s[i], mef_flags);
712 			if (s[i] == 'b') {
713 				if (second)
714 					ks->pos2b = true;
715 				else
716 					ks->pos1b = true;
717 			} else if (!set_sort_modifier(&(ks->sm), s[i]))
718 				goto end;
719 		}
720 	}
721 
722 	ret = 0;
723 
724 end:
725 
726 	if (c)
727 		sort_free(c);
728 	if (f)
729 		sort_free(f);
730 	regfree(&re);
731 
732 	return (ret);
733 }
734 
735 /*
736  * Parse -k option value.
737  */
738 static int
739 parse_k(const char *s, struct key_specs *ks)
740 {
741 	int ret = -1;
742 	bool mef_flags[NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS] =
743 	    { false, false, false, false, false, false };
744 
745 	if (s && *s) {
746 		char *sptr;
747 
748 		sptr = strchr(s, ',');
749 		if (sptr) {
750 			size_t size1;
751 			char *pos1, *pos2;
752 
753 			size1 = sptr - s;
754 
755 			if (size1 < 1)
756 				return (-1);
757 			pos1 = sort_malloc((size1 + 1) * sizeof(char));
758 
759 			strncpy(pos1, s, size1);
760 			pos1[size1] = '\0';
761 
762 			ret = parse_pos(pos1, ks, mef_flags, false);
763 
764 			sort_free(pos1);
765 			if (ret < 0)
766 				return (ret);
767 
768 			pos2 = sort_strdup(sptr + 1);
769 			ret = parse_pos(pos2, ks, mef_flags, true);
770 			sort_free(pos2);
771 		} else
772 			ret = parse_pos(s, ks, mef_flags, false);
773 	}
774 
775 	return (ret);
776 }
777 
778 /*
779  * Parse POS in +POS -POS option.
780  */
781 static int
782 parse_pos_obs(const char *s, int *nf, int *nc, char* sopts)
783 {
784 	regex_t re;
785 	regmatch_t pmatch[4];
786 	char *c, *f;
787 	const char *sregexp = "^([0-9]+)(\\.[0-9]+)?([A-Za-z]+)?$";
788 	int ret;
789 	size_t len, nmatch;
790 
791 	ret = -1;
792 	nmatch = 4;
793 	c = f = NULL;
794 	*nc = *nf = 0;
795 
796 	if (regcomp(&re, sregexp, REG_EXTENDED) != 0)
797 		return (-1);
798 
799 	if (regexec(&re, s, nmatch, pmatch, 0) != 0)
800 		goto end;
801 
802 	if (pmatch[0].rm_eo <= pmatch[0].rm_so)
803 		goto end;
804 
805 	if (pmatch[1].rm_eo <= pmatch[1].rm_so)
806 		goto end;
807 
808 	len = pmatch[1].rm_eo - pmatch[1].rm_so;
809 	f = sort_malloc((len + 1) * sizeof(char));
810 
811 	strncpy(f, s + pmatch[1].rm_so, len);
812 	f[len] = '\0';
813 
814 	errno = 0;
815 	*nf = (size_t) strtoul(f, NULL, 10);
816 	if (errno != 0)
817 		errx(2, getstr(11));
818 
819 	if (pmatch[2].rm_eo > pmatch[2].rm_so) {
820 		len = pmatch[2].rm_eo - pmatch[2].rm_so - 1;
821 		c = sort_malloc((len + 1) * sizeof(char));
822 
823 		strncpy(c, s + pmatch[2].rm_so + 1, len);
824 		c[len] = '\0';
825 
826 		errno = 0;
827 		*nc = (size_t) strtoul(c, NULL, 10);
828 		if (errno != 0)
829 			errx(2, getstr(11));
830 	}
831 
832 	if (pmatch[3].rm_eo > pmatch[3].rm_so) {
833 
834 		len = pmatch[3].rm_eo - pmatch[3].rm_so;
835 
836 		strncpy(sopts, s + pmatch[3].rm_so, len);
837 		sopts[len] = '\0';
838 	}
839 
840 	ret = 0;
841 
842 end:
843 	if (c)
844 		sort_free(c);
845 	if (f)
846 		sort_free(f);
847 	regfree(&re);
848 
849 	return (ret);
850 }
851 
852 /*
853  * "Translate" obsolete +POS1 -POS2 syntax into new -kPOS1,POS2 syntax
854  */
855 void
856 fix_obsolete_keys(int *argc, char **argv)
857 {
858 	char sopt[129];
859 
860 	for (int i = 1; i < *argc; i++) {
861 		char *arg1;
862 
863 		arg1 = argv[i];
864 
865 		if (strlen(arg1) > 1 && arg1[0] == '+') {
866 			int c1, f1;
867 			char sopts1[128];
868 
869 			sopts1[0] = 0;
870 			c1 = f1 = 0;
871 
872 			if (parse_pos_obs(arg1 + 1, &f1, &c1, sopts1) < 0)
873 				continue;
874 			else {
875 				f1 += 1;
876 				c1 += 1;
877 				if (i + 1 < *argc) {
878 					char *arg2 = argv[i + 1];
879 
880 					if (strlen(arg2) > 1 &&
881 					    arg2[0] == '-') {
882 						int c2, f2;
883 						char sopts2[128];
884 
885 						sopts2[0] = 0;
886 						c2 = f2 = 0;
887 
888 						if (parse_pos_obs(arg2 + 1,
889 						    &f2, &c2, sopts2) >= 0) {
890 							if (c2 > 0)
891 								f2 += 1;
892 							sprintf(sopt, "-k%d.%d%s,%d.%d%s",
893 							    f1, c1, sopts1, f2, c2, sopts2);
894 							argv[i] = sort_strdup(sopt);
895 							for (int j = i + 1; j + 1 < *argc; j++)
896 								argv[j] = argv[j + 1];
897 							*argc -= 1;
898 							continue;
899 						}
900 					}
901 				}
902 				sprintf(sopt, "-k%d.%d", f1, c1);
903 				argv[i] = sort_strdup(sopt);
904 			}
905 		}
906 	}
907 }
908 
909 /*
910  * Set random seed
911  */
912 static void
913 set_random_seed(void)
914 {
915 	if (need_random) {
916 
917 		if (strcmp(random_source, DEFAULT_RANDOM_SORT_SEED_FILE) == 0) {
918 			FILE* fseed;
919 			MD5_CTX ctx;
920 			char rsd[MAX_DEFAULT_RANDOM_SEED_DATA_SIZE];
921 			size_t sz = 0;
922 
923 			fseed = openfile(random_source, "r");
924 			while (!feof(fseed)) {
925 				int cr;
926 
927 				cr = fgetc(fseed);
928 				if (cr == EOF)
929 					break;
930 
931 				rsd[sz++] = (char) cr;
932 
933 				if (sz >= MAX_DEFAULT_RANDOM_SEED_DATA_SIZE)
934 					break;
935 			}
936 
937 			closefile(fseed, random_source);
938 
939 			MD5Init(&ctx);
940 			MD5Update(&ctx, rsd, sz);
941 
942 			random_seed = MD5End(&ctx, NULL);
943 			random_seed_size = strlen(random_seed);
944 
945 		} else {
946 			MD5_CTX ctx;
947 			char *b;
948 
949 			MD5Init(&ctx);
950 			b = MD5File(random_source, NULL);
951 			if (b == NULL)
952 				err(2, NULL);
953 
954 			random_seed = b;
955 			random_seed_size = strlen(b);
956 		}
957 
958 		MD5Init(&md5_ctx);
959 		if(random_seed_size>0) {
960 			MD5Update(&md5_ctx, random_seed, random_seed_size);
961 		}
962 	}
963 }
964 
965 /*
966  * Main function.
967  */
968 int
969 main(int argc, char **argv)
970 {
971 	char *outfile, *real_outfile;
972 	int c, result;
973 	bool mef_flags[NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS] =
974 	    { false, false, false, false, false, false };
975 
976 	result = 0;
977 	outfile = sort_strdup("-");
978 	real_outfile = NULL;
979 
980 	struct sort_mods *sm = &default_sort_mods_object;
981 
982 	init_tmp_files();
983 
984 	set_signal_handler();
985 
986 	set_hw_params();
987 	set_locale();
988 	set_tmpdir();
989 	set_sort_opts();
990 
991 #if 0
992 	{
993 		static int counter = 0;
994 		char fn[128];
995 		sprintf(fn, "/var/tmp/debug.sort.%d", counter++);
996 		FILE* f = fopen(fn, "w");
997 		fprintf(f, ">>sort>>");
998 		for (int i = 0; i < argc; i++) {
999 			fprintf(f, "<%s>", argv[i]);
1000 		}
1001 		fprintf(f, "<<sort<<\n");
1002 		fclose(f);
1003 	}
1004 #endif
1005 
1006 	fix_obsolete_keys(&argc, argv);
1007 
1008 	while (((c = getopt_long(argc, argv, OPTIONS, long_options, NULL))
1009 	    != -1)) {
1010 
1011 		check_mutually_exclusive_flags(c, mef_flags);
1012 
1013 		if (!set_sort_modifier(sm, c)) {
1014 
1015 			switch (c) {
1016 			case 'c':
1017 				sort_opts_vals.cflag = true;
1018 				if (optarg) {
1019 					if (!strcmp(optarg, "diagnose-first"))
1020 						;
1021 					else if (!strcmp(optarg, "silent") ||
1022 					    !strcmp(optarg, "quiet"))
1023 						sort_opts_vals.csilentflag = true;
1024 					else if (*optarg)
1025 						unknown(optarg);
1026 				}
1027 				break;
1028 			case 'C':
1029 				sort_opts_vals.cflag = true;
1030 				sort_opts_vals.csilentflag = true;
1031 				break;
1032 			case 'k':
1033 			{
1034 				sort_opts_vals.complex_sort = true;
1035 				sort_opts_vals.kflag = true;
1036 
1037 				keys_num++;
1038 				keys = sort_realloc(keys, keys_num *
1039 				    sizeof(struct key_specs));
1040 				memset(&(keys[keys_num - 1]), 0,
1041 				    sizeof(struct key_specs));
1042 
1043 				if (parse_k(optarg, &(keys[keys_num - 1]))
1044 				    < 0) {
1045 					errx(2, "%s: -k %s\n",
1046 					    strerror(EINVAL), optarg);
1047 				}
1048 
1049 				break;
1050 			}
1051 			case 'm':
1052 				sort_opts_vals.mflag = true;
1053 				break;
1054 			case 'o':
1055 				outfile = sort_realloc(outfile, sizeof(char) *
1056 				    (strlen(optarg) + 1));
1057 				strlcpy(outfile, optarg, (strlen(optarg) + 1));
1058 				break;
1059 			case 's':
1060 				sort_opts_vals.sflag = true;
1061 				break;
1062 			case 'S':
1063 				available_free_memory =
1064 				    parse_memory_buffer_value(optarg);
1065 				break;
1066 			case 'T':
1067 				tmpdir = sort_strdup(optarg);
1068 				break;
1069 			case 't':
1070 				if (strlen(optarg) > 1) {
1071 					if (strcmp(optarg, "\\0")) {
1072 						errx(2, "%s: %s\n",
1073 						    strerror(EINVAL), optarg);
1074 					}
1075 					*optarg = 0;
1076 				}
1077 				sort_opts_vals.tflag = true;
1078 				sort_opts_vals.field_sep = btowc(optarg[0]);
1079 				if (sort_opts_vals.field_sep == WEOF) {
1080 					errno = EINVAL;
1081 					err(2, NULL);
1082 				}
1083 				if (!gnusort_numeric_compatibility) {
1084 					if (symbol_decimal_point == sort_opts_vals.field_sep)
1085 						symbol_decimal_point = WEOF;
1086 					if (symbol_thousands_sep == sort_opts_vals.field_sep)
1087 						symbol_thousands_sep = WEOF;
1088 					if (symbol_negative_sign == sort_opts_vals.field_sep)
1089 						symbol_negative_sign = WEOF;
1090 					if (symbol_positive_sign == sort_opts_vals.field_sep)
1091 						symbol_positive_sign = WEOF;
1092 				}
1093 				break;
1094 			case 'u':
1095 				sort_opts_vals.uflag = true;
1096 				/* stable sort for the correct unique val */
1097 				sort_opts_vals.sflag = true;
1098 				break;
1099 			case 'z':
1100 				sort_opts_vals.zflag = true;
1101 				break;
1102 			case SORT_OPT:
1103 				if (optarg) {
1104 					if (!strcmp(optarg, "general-numeric"))
1105 						set_sort_modifier(sm, 'g');
1106 					else if (!strcmp(optarg, "human-numeric"))
1107 						set_sort_modifier(sm, 'h');
1108 					else if (!strcmp(optarg, "numeric"))
1109 						set_sort_modifier(sm, 'n');
1110 					else if (!strcmp(optarg, "month"))
1111 						set_sort_modifier(sm, 'M');
1112 					else if (!strcmp(optarg, "random"))
1113 						set_sort_modifier(sm, 'R');
1114 					else
1115 						unknown(optarg);
1116 				}
1117 				break;
1118 #if defined(SORT_THREADS)
1119 			case NTHREADS_OPT:
1120 				nthreads = (size_t)(atoi(optarg));
1121 				if (nthreads < 1)
1122 					nthreads = 1;
1123 				if (nthreads > 1024)
1124 					nthreads = 1024;
1125 				break;
1126 #endif
1127 			case QSORT_OPT:
1128 				sort_opts_vals.sort_method = SORT_QSORT;
1129 				break;
1130 			case MERGESORT_OPT:
1131 				sort_opts_vals.sort_method = SORT_MERGESORT;
1132 				break;
1133 			case HEAPSORT_OPT:
1134 				sort_opts_vals.sort_method = SORT_HEAPSORT;
1135 				break;
1136 			case RADIXSORT_OPT:
1137 				sort_opts_vals.sort_method = SORT_RADIXSORT;
1138 				break;
1139 			case RANDOMSOURCE_OPT:
1140 				random_source = strdup(optarg);
1141 				break;
1142 			case COMPRESSPROGRAM_OPT:
1143 				compress_program = strdup(optarg);
1144 				break;
1145 			case FF_OPT:
1146 				read_fns_from_file0(optarg);
1147 				break;
1148 			case BS_OPT:
1149 			{
1150 				errno = 0;
1151 				long mof = strtol(optarg, NULL, 10);
1152 				if (errno != 0)
1153 					errx(2, "--batch-size: %s",
1154 					    strerror(errno));
1155 				if (mof >= 2)
1156 					max_open_files = (size_t) mof + 1;
1157 			}
1158 				break;
1159 			case VERSION_OPT:
1160 				printf("%s\n", VERSION);
1161 				exit(EXIT_SUCCESS);
1162 				/* NOTREACHED */
1163 				break;
1164 			case DEBUG_OPT:
1165 				debug_sort = true;
1166 				break;
1167 			case HELP_OPT:
1168 				usage(false);
1169 				/* NOTREACHED */
1170 				break;
1171 			default:
1172 				usage(true);
1173 				/* NOTREACHED */
1174 			}
1175 		}
1176 	}
1177 
1178 	argc -= optind;
1179 	argv += optind;
1180 
1181 #ifndef WITHOUT_NLS
1182 	catalog = catopen("sort", NL_CAT_LOCALE);
1183 #endif
1184 
1185 	if (sort_opts_vals.cflag && sort_opts_vals.mflag)
1186 		errx(1, getstr(1), 'm', 'c');
1187 
1188 #ifndef WITHOUT_NLS
1189 	catclose(catalog);
1190 #endif
1191 
1192 	if (keys_num == 0) {
1193 		keys_num = 1;
1194 		keys = sort_realloc(keys, sizeof(struct key_specs));
1195 		memset(&(keys[0]), 0, sizeof(struct key_specs));
1196 		keys[0].c1 = 1;
1197 		keys[0].pos1b = default_sort_mods->bflag;
1198 		keys[0].pos2b = default_sort_mods->bflag;
1199 		memcpy(&(keys[0].sm), default_sort_mods,
1200 		    sizeof(struct sort_mods));
1201 	}
1202 
1203 	for (size_t i = 0; i < keys_num; i++) {
1204 		struct key_specs *ks;
1205 
1206 		ks = &(keys[i]);
1207 
1208 		if (sort_modifier_empty(&(ks->sm)) && !(ks->pos1b) &&
1209 		    !(ks->pos2b)) {
1210 			ks->pos1b = sm->bflag;
1211 			ks->pos2b = sm->bflag;
1212 			memcpy(&(ks->sm), sm, sizeof(struct sort_mods));
1213 		}
1214 
1215 		ks->sm.func = get_sort_func(&(ks->sm));
1216 	}
1217 
1218 	if (argc_from_file0 >= 0) {
1219 		argc = argc_from_file0;
1220 		argv = argv_from_file0;
1221 	}
1222 
1223 	if (debug_sort) {
1224 #if defined(SORT_THREADS)
1225 		nthreads = 1;
1226 #endif
1227 		printf("Using collate rules of %s locale\n",
1228 		    setlocale(LC_COLLATE, NULL));
1229 		if (byte_sort)
1230 			printf("Byte sort is used\n");
1231 		if (print_symbols_on_debug) {
1232 			printf("Decimal Point: <%lc>\n", symbol_decimal_point);
1233 			if (symbol_thousands_sep)
1234 				printf("Thousands separator: <%lc>\n",
1235 				    symbol_thousands_sep);
1236 			printf("Positive sign: <%lc>\n", symbol_positive_sign);
1237 			printf("Negative sign: <%lc>\n", symbol_negative_sign);
1238 		}
1239 	}
1240 
1241 	set_random_seed();
1242 
1243 	/* Case when the outfile equals one of the input files: */
1244 	if (strcmp(outfile, "-")) {
1245 
1246 		for(int i = 0; i < argc; ++i) {
1247 			if (strcmp(argv[i], outfile) == 0) {
1248 				real_outfile = sort_strdup(outfile);
1249 				for(;;) {
1250 					char* tmp = sort_malloc(strlen(outfile) +
1251 					    strlen(".tmp") + 1);
1252 
1253 					strcpy(tmp, outfile);
1254 					strcpy(tmp + strlen(tmp), ".tmp");
1255 					sort_free(outfile);
1256 					outfile = tmp;
1257 					if (access(outfile, F_OK) < 0)
1258 						break;
1259 				}
1260 				tmp_file_atexit(outfile);
1261 			}
1262 		}
1263 	}
1264 
1265 	if (!sort_opts_vals.cflag && !sort_opts_vals.mflag) {
1266 		struct file_list fl;
1267 		struct sort_list list;
1268 
1269 		sort_list_init(&list);
1270 		file_list_init(&fl, true);
1271 
1272 		if (argc < 1)
1273 			procfile("-", &list, &fl);
1274 		else {
1275 			while (argc > 0) {
1276 				procfile(*argv, &list, &fl);
1277 				--argc;
1278 				++argv;
1279 			}
1280 		}
1281 
1282 		if (fl.count < 1)
1283 			sort_list_to_file(&list, outfile);
1284 		else {
1285 			if (list.count > 0) {
1286 				char *flast = new_tmp_file_name();
1287 
1288 				sort_list_to_file(&list, flast);
1289 				file_list_add(&fl, flast, false);
1290 			}
1291 			merge_files(&fl, outfile);
1292 		}
1293 
1294 		file_list_clean(&fl);
1295 
1296 		/*
1297 		 * We are about to exit the program, so we can ignore
1298 		 * the clean-up for speed
1299 		 *
1300 		 * sort_list_clean(&list);
1301 		 */
1302 
1303 	} else if (sort_opts_vals.cflag) {
1304 		result = (argc == 0) ? (check("-")) : (check(*argv));
1305 	} else if (sort_opts_vals.mflag) {
1306 		struct file_list fl;
1307 
1308 		file_list_init(&fl, false);
1309 		file_list_populate(&fl, argc, argv, true);
1310 		merge_files(&fl, outfile);
1311 		file_list_clean(&fl);
1312 	}
1313 
1314 	if (real_outfile) {
1315 		unlink(real_outfile);
1316 		if (rename(outfile, real_outfile) < 0)
1317 			err(2, NULL);
1318 		sort_free(real_outfile);
1319 	}
1320 
1321 	sort_free(outfile);
1322 
1323 	return (result);
1324 }
1325