xref: /freebsd/usr.bin/units/units.c (revision 3ae0125a99dc29a8f8ca9ba933825e2447b54c6b)
1 /*
2  * units.c   Copyright (c) 1993 by Adrian Mariano (adrian@cam.cornell.edu)
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. The name of the author may not be used to endorse or promote products
10  *    derived from this software without specific prior written permission.
11  * Disclaimer:  This software is provided by the author "as is".  The author
12  * shall not be liable for any damages caused in any way by this software.
13  *
14  * I would appreciate (though I do not require) receiving a copy of any
15  * improvements you might make to this program.
16  */
17 
18 #ifndef lint
19 static const char rcsid[] =
20   "$FreeBSD$";
21 #endif /* not lint */
22 
23 #include <ctype.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 
31 #include <sys/capsicum.h>
32 
33 #include "pathnames.h"
34 
35 #ifndef UNITSFILE
36 #define UNITSFILE _PATH_UNITSLIB
37 #endif
38 
39 #define MAXUNITS 1000
40 #define MAXPREFIXES 100
41 
42 #define MAXSUBUNITS 500
43 
44 #define PRIMITIVECHAR '!'
45 
46 static const char *powerstring = "^";
47 
48 static struct {
49 	char *uname;
50 	char *uval;
51 }      unittable[MAXUNITS];
52 
53 struct unittype {
54 	char *numerator[MAXSUBUNITS];
55 	char *denominator[MAXSUBUNITS];
56 	double factor;
57 	double offset;
58 	int quantity;
59 };
60 
61 static struct {
62 	char *prefixname;
63 	char *prefixval;
64 }      prefixtable[MAXPREFIXES];
65 
66 
67 static char NULLUNIT[] = "";
68 
69 #ifdef MSDOS
70 #define SEPARATOR      ";"
71 #else
72 #define SEPARATOR      ":"
73 #endif
74 
75 static int unitcount;
76 static int prefixcount;
77 
78 char	*dupstr(const char *str);
79 void	 readunits(const char *userfile);
80 void	 initializeunit(struct unittype * theunit);
81 int	 addsubunit(char *product[], char *toadd);
82 void	 showunit(struct unittype * theunit);
83 void	 zeroerror(void);
84 int	 addunit(struct unittype *theunit, char *toadd, int flip, int quantity);
85 int	 compare(const void *item1, const void *item2);
86 void	 sortunit(struct unittype * theunit);
87 void	 cancelunit(struct unittype * theunit);
88 char	*lookupunit(const char *unit);
89 int	 reduceproduct(struct unittype * theunit, int flip);
90 int	 reduceunit(struct unittype * theunit);
91 int	 compareproducts(char **one, char **two);
92 int	 compareunits(struct unittype * first, struct unittype * second);
93 int	 completereduce(struct unittype * unit);
94 void	 showanswer(struct unittype * have, struct unittype * want);
95 void	 usage(void);
96 
97 char *
98 dupstr(const char *str)
99 {
100 	char *ret;
101 
102 	ret = malloc(strlen(str) + 1);
103 	if (!ret)
104 		errx(3, "memory allocation error");
105 	strcpy(ret, str);
106 	return (ret);
107 }
108 
109 
110 void
111 readunits(const char *userfile)
112 {
113 	FILE *unitfile;
114 	char line[512], *lineptr;
115 	int len, linenum, i;
116 	cap_rights_t unitfilerights;
117 
118 	unitcount = 0;
119 	linenum = 0;
120 
121 	if (userfile) {
122 		unitfile = fopen(userfile, "rt");
123 		if (!unitfile)
124 			errx(1, "unable to open units file '%s'", userfile);
125 	}
126 	else {
127 		unitfile = fopen(UNITSFILE, "rt");
128 		if (!unitfile) {
129 			char *direc, *env;
130 			char filename[1000];
131 
132 			env = getenv("PATH");
133 			if (env) {
134 				direc = strtok(env, SEPARATOR);
135 				while (direc) {
136 					snprintf(filename, sizeof(filename),
137 					    "%s/%s", direc, UNITSFILE);
138 					unitfile = fopen(filename, "rt");
139 					if (unitfile)
140 						break;
141 					direc = strtok(NULL, SEPARATOR);
142 				}
143 			}
144 			if (!unitfile)
145 				errx(1, "can't find units file '%s'", UNITSFILE);
146 		}
147 	}
148 	if (cap_enter() < 0 && errno != ENOSYS)
149 		err(1, "unable to enter capability mode");
150 	cap_rights_init(&unitfilerights, CAP_READ, CAP_FSTAT);
151 	if (cap_rights_limit(fileno(unitfile), &unitfilerights) < 0
152 		&& errno != ENOSYS)
153 		err(1, "cap_rights_limit() failed");
154 	while (!feof(unitfile)) {
155 		if (!fgets(line, sizeof(line), unitfile))
156 			break;
157 		linenum++;
158 		lineptr = line;
159 		if (*lineptr == '/')
160 			continue;
161 		lineptr += strspn(lineptr, " \n\t");
162 		len = strcspn(lineptr, " \n\t");
163 		lineptr[len] = 0;
164 		if (!strlen(lineptr))
165 			continue;
166 		if (lineptr[strlen(lineptr) - 1] == '-') { /* it's a prefix */
167 			if (prefixcount == MAXPREFIXES) {
168 				warnx("memory for prefixes exceeded in line %d", linenum);
169 				continue;
170 			}
171 			lineptr[strlen(lineptr) - 1] = 0;
172 			prefixtable[prefixcount].prefixname = dupstr(lineptr);
173 			for (i = 0; i < prefixcount; i++)
174 				if (!strcmp(prefixtable[i].prefixname, lineptr)) {
175 					warnx("redefinition of prefix '%s' on line %d ignored",
176 					    lineptr, linenum);
177 					continue;
178 				}
179 			lineptr += len + 1;
180 			lineptr += strspn(lineptr, " \n\t");
181 			len = strcspn(lineptr, "\n\t");
182 			if (len == 0) {
183 				warnx("unexpected end of prefix on line %d",
184 				    linenum);
185 				continue;
186 			}
187 			lineptr[len] = 0;
188 			prefixtable[prefixcount++].prefixval = dupstr(lineptr);
189 		}
190 		else {		/* it's not a prefix */
191 			if (unitcount == MAXUNITS) {
192 				warnx("memory for units exceeded in line %d", linenum);
193 				continue;
194 			}
195 			unittable[unitcount].uname = dupstr(lineptr);
196 			for (i = 0; i < unitcount; i++)
197 				if (!strcmp(unittable[i].uname, lineptr)) {
198 					warnx("redefinition of unit '%s' on line %d ignored",
199 					    lineptr, linenum);
200 					continue;
201 				}
202 			lineptr += len + 1;
203 			lineptr += strspn(lineptr, " \n\t");
204 			if (!strlen(lineptr)) {
205 				warnx("unexpected end of unit on line %d",
206 				    linenum);
207 				continue;
208 			}
209 			len = strcspn(lineptr, "\n\t");
210 			lineptr[len] = 0;
211 			unittable[unitcount++].uval = dupstr(lineptr);
212 		}
213 	}
214 	fclose(unitfile);
215 }
216 
217 void
218 initializeunit(struct unittype * theunit)
219 {
220 	theunit->numerator[0] = theunit->denominator[0] = NULL;
221 	theunit->factor = 1.0;
222 	theunit->offset = 0.0;
223 	theunit->quantity = 0;
224 }
225 
226 
227 int
228 addsubunit(char *product[], char *toadd)
229 {
230 	char **ptr;
231 
232 	for (ptr = product; *ptr && *ptr != NULLUNIT; ptr++);
233 	if (ptr >= product + MAXSUBUNITS) {
234 		warnx("memory overflow in unit reduction");
235 		return 1;
236 	}
237 	if (!*ptr)
238 		*(ptr + 1) = 0;
239 	*ptr = dupstr(toadd);
240 	return 0;
241 }
242 
243 
244 void
245 showunit(struct unittype * theunit)
246 {
247 	char **ptr;
248 	int printedslash;
249 	int counter = 1;
250 
251 	printf("\t%.8g", theunit->factor);
252 	if (theunit->offset)
253 		printf("&%.8g", theunit->offset);
254 	for (ptr = theunit->numerator; *ptr; ptr++) {
255 		if (ptr > theunit->numerator && **ptr &&
256 		    !strcmp(*ptr, *(ptr - 1)))
257 			counter++;
258 		else {
259 			if (counter > 1)
260 				printf("%s%d", powerstring, counter);
261 			if (**ptr)
262 				printf(" %s", *ptr);
263 			counter = 1;
264 		}
265 	}
266 	if (counter > 1)
267 		printf("%s%d", powerstring, counter);
268 	counter = 1;
269 	printedslash = 0;
270 	for (ptr = theunit->denominator; *ptr; ptr++) {
271 		if (ptr > theunit->denominator && **ptr &&
272 		    !strcmp(*ptr, *(ptr - 1)))
273 			counter++;
274 		else {
275 			if (counter > 1)
276 				printf("%s%d", powerstring, counter);
277 			if (**ptr) {
278 				if (!printedslash)
279 					printf(" /");
280 				printedslash = 1;
281 				printf(" %s", *ptr);
282 			}
283 			counter = 1;
284 		}
285 	}
286 	if (counter > 1)
287 		printf("%s%d", powerstring, counter);
288 	printf("\n");
289 }
290 
291 
292 void
293 zeroerror(void)
294 {
295 	warnx("unit reduces to zero");
296 }
297 
298 /*
299    Adds the specified string to the unit.
300    Flip is 0 for adding normally, 1 for adding reciprocal.
301    Quantity is 1 if this is a quantity to be converted rather than a pure unit.
302 
303    Returns 0 for successful addition, nonzero on error.
304 */
305 
306 int
307 addunit(struct unittype * theunit, char *toadd, int flip, int quantity)
308 {
309 	char *scratch, *savescr;
310 	char *item;
311 	char *divider, *slash, *offset;
312 	int doingtop;
313 
314 	if (!strlen(toadd))
315 		return 1;
316 
317 	savescr = scratch = dupstr(toadd);
318 	for (slash = scratch + 1; *slash; slash++)
319 		if (*slash == '-' &&
320 		    (tolower(*(slash - 1)) != 'e' ||
321 		    !strchr(".0123456789", *(slash + 1))))
322 			*slash = ' ';
323 	slash = strchr(scratch, '/');
324 	if (slash)
325 		*slash = 0;
326 	doingtop = 1;
327 	do {
328 		item = strtok(scratch, " *\t\n/");
329 		while (item) {
330 			if (strchr("0123456789.", *item)) { /* item is a number */
331 				double num, offsetnum;
332 
333 				if (quantity)
334 					theunit->quantity = 1;
335 
336 				offset = strchr(item, '&');
337 				if (offset) {
338 					*offset = 0;
339 					offsetnum = atof(offset+1);
340 				} else
341 					offsetnum = 0.0;
342 
343 				divider = strchr(item, '|');
344 				if (divider) {
345 					*divider = 0;
346 					num = atof(item);
347 					if (!num) {
348 						zeroerror();
349 						return 1;
350 					}
351 					if (doingtop ^ flip) {
352 						theunit->factor *= num;
353 						theunit->offset *= num;
354 					} else {
355 						theunit->factor /= num;
356 						theunit->offset /= num;
357 					}
358 					num = atof(divider + 1);
359 					if (!num) {
360 						zeroerror();
361 						return 1;
362 					}
363 					if (doingtop ^ flip) {
364 						theunit->factor /= num;
365 						theunit->offset /= num;
366 					} else {
367 						theunit->factor *= num;
368 						theunit->offset *= num;
369 					}
370 				}
371 				else {
372 					num = atof(item);
373 					if (!num) {
374 						zeroerror();
375 						return 1;
376 					}
377 					if (doingtop ^ flip) {
378 						theunit->factor *= num;
379 						theunit->offset *= num;
380 					} else {
381 						theunit->factor /= num;
382 						theunit->offset /= num;
383 					}
384 				}
385 				if (doingtop ^ flip)
386 					theunit->offset += offsetnum;
387 			}
388 			else {	/* item is not a number */
389 				int repeat = 1;
390 
391 				if (strchr("23456789",
392 				    item[strlen(item) - 1])) {
393 					repeat = item[strlen(item) - 1] - '0';
394 					item[strlen(item) - 1] = 0;
395 				}
396 				for (; repeat; repeat--)
397 					if (addsubunit(doingtop ^ flip ? theunit->numerator : theunit->denominator, item))
398 						return 1;
399 			}
400 			item = strtok(NULL, " *\t/\n");
401 		}
402 		doingtop--;
403 		if (slash) {
404 			scratch = slash + 1;
405 		}
406 		else
407 			doingtop--;
408 	} while (doingtop >= 0);
409 	free(savescr);
410 	return 0;
411 }
412 
413 
414 int
415 compare(const void *item1, const void *item2)
416 {
417 	return strcmp(*(const char * const *)item1, *(const char * const *)item2);
418 }
419 
420 
421 void
422 sortunit(struct unittype * theunit)
423 {
424 	char **ptr;
425 	unsigned int count;
426 
427 	for (count = 0, ptr = theunit->numerator; *ptr; ptr++, count++);
428 	qsort(theunit->numerator, count, sizeof(char *), compare);
429 	for (count = 0, ptr = theunit->denominator; *ptr; ptr++, count++);
430 	qsort(theunit->denominator, count, sizeof(char *), compare);
431 }
432 
433 
434 void
435 cancelunit(struct unittype * theunit)
436 {
437 	char **den, **num;
438 	int comp;
439 
440 	den = theunit->denominator;
441 	num = theunit->numerator;
442 
443 	while (*num && *den) {
444 		comp = strcmp(*den, *num);
445 		if (!comp) {
446 /*      if (*den!=NULLUNIT) free(*den);
447       if (*num!=NULLUNIT) free(*num);*/
448 			*den++ = NULLUNIT;
449 			*num++ = NULLUNIT;
450 		}
451 		else if (comp < 0)
452 			den++;
453 		else
454 			num++;
455 	}
456 }
457 
458 
459 
460 
461 /*
462    Looks up the definition for the specified unit.
463    Returns a pointer to the definition or a null pointer
464    if the specified unit does not appear in the units table.
465 */
466 
467 static char buffer[100];	/* buffer for lookupunit answers with
468 				   prefixes */
469 
470 char *
471 lookupunit(const char *unit)
472 {
473 	int i;
474 	char *copy;
475 
476 	for (i = 0; i < unitcount; i++) {
477 		if (!strcmp(unittable[i].uname, unit))
478 			return unittable[i].uval;
479 	}
480 
481 	if (unit[strlen(unit) - 1] == '^') {
482 		copy = dupstr(unit);
483 		copy[strlen(copy) - 1] = 0;
484 		for (i = 0; i < unitcount; i++) {
485 			if (!strcmp(unittable[i].uname, copy)) {
486 				strlcpy(buffer, copy, sizeof(buffer));
487 				free(copy);
488 				return buffer;
489 			}
490 		}
491 		free(copy);
492 	}
493 	if (unit[strlen(unit) - 1] == 's') {
494 		copy = dupstr(unit);
495 		copy[strlen(copy) - 1] = 0;
496 		for (i = 0; i < unitcount; i++) {
497 			if (!strcmp(unittable[i].uname, copy)) {
498 				strlcpy(buffer, copy, sizeof(buffer));
499 				free(copy);
500 				return buffer;
501 			}
502 		}
503 		if (copy[strlen(copy) - 1] == 'e') {
504 			copy[strlen(copy) - 1] = 0;
505 			for (i = 0; i < unitcount; i++) {
506 				if (!strcmp(unittable[i].uname, copy)) {
507 					strlcpy(buffer, copy, sizeof(buffer));
508 					free(copy);
509 					return buffer;
510 				}
511 			}
512 		}
513 		free(copy);
514 	}
515 	for (i = 0; i < prefixcount; i++) {
516 		size_t len = strlen(prefixtable[i].prefixname);
517 		if (!strncmp(prefixtable[i].prefixname, unit, len)) {
518 			if (!strlen(unit + len) || lookupunit(unit + len)) {
519 				snprintf(buffer, sizeof(buffer), "%s %s",
520 				    prefixtable[i].prefixval, unit + len);
521 				return buffer;
522 			}
523 		}
524 	}
525 	return 0;
526 }
527 
528 
529 
530 /*
531    reduces a product of symbolic units to primitive units.
532    The three low bits are used to return flags:
533 
534      bit 0 (1) set on if reductions were performed without error.
535      bit 1 (2) set on if no reductions are performed.
536      bit 2 (4) set on if an unknown unit is discovered.
537 */
538 
539 
540 #define ERROR 4
541 
542 int
543 reduceproduct(struct unittype * theunit, int flip)
544 {
545 
546 	char *toadd;
547 	char **product;
548 	int didsomething = 2;
549 
550 	if (flip)
551 		product = theunit->denominator;
552 	else
553 		product = theunit->numerator;
554 
555 	for (; *product; product++) {
556 
557 		for (;;) {
558 			if (!strlen(*product))
559 				break;
560 			toadd = lookupunit(*product);
561 			if (!toadd) {
562 				printf("unknown unit '%s'\n", *product);
563 				return ERROR;
564 			}
565 			if (strchr(toadd, PRIMITIVECHAR))
566 				break;
567 			didsomething = 1;
568 			if (*product != NULLUNIT) {
569 				free(*product);
570 				*product = NULLUNIT;
571 			}
572 			if (addunit(theunit, toadd, flip, 0))
573 				return ERROR;
574 		}
575 	}
576 	return didsomething;
577 }
578 
579 
580 /*
581    Reduces numerator and denominator of the specified unit.
582    Returns 0 on success, or 1 on unknown unit error.
583 */
584 
585 int
586 reduceunit(struct unittype * theunit)
587 {
588 	int ret;
589 
590 	ret = 1;
591 	while (ret & 1) {
592 		ret = reduceproduct(theunit, 0) | reduceproduct(theunit, 1);
593 		if (ret & 4)
594 			return 1;
595 	}
596 	return 0;
597 }
598 
599 
600 int
601 compareproducts(char **one, char **two)
602 {
603 	while (*one || *two) {
604 		if (!*one && *two != NULLUNIT)
605 			return 1;
606 		if (!*two && *one != NULLUNIT)
607 			return 1;
608 		if (*one == NULLUNIT)
609 			one++;
610 		else if (*two == NULLUNIT)
611 			two++;
612 		else if (strcmp(*one, *two))
613 			return 1;
614 		else
615 			one++, two++;
616 	}
617 	return 0;
618 }
619 
620 
621 /* Return zero if units are compatible, nonzero otherwise */
622 
623 int
624 compareunits(struct unittype * first, struct unittype * second)
625 {
626 	return
627 	compareproducts(first->numerator, second->numerator) ||
628 	compareproducts(first->denominator, second->denominator);
629 }
630 
631 
632 int
633 completereduce(struct unittype * unit)
634 {
635 	if (reduceunit(unit))
636 		return 1;
637 	sortunit(unit);
638 	cancelunit(unit);
639 	return 0;
640 }
641 
642 
643 void
644 showanswer(struct unittype * have, struct unittype * want)
645 {
646 	if (compareunits(have, want)) {
647 		printf("conformability error\n");
648 		showunit(have);
649 		showunit(want);
650 	}
651 	else if (have->offset != want->offset) {
652 		if (want->quantity)
653 			printf("WARNING: conversion of non-proportional quantities.\n");
654 		printf("\t");
655 		if (have->quantity)
656 			printf("%.8g\n",
657 			    (have->factor + have->offset-want->offset)/want->factor);
658 		else
659 			printf(" (-> x*%.8g %+.8g)\n\t (<- y*%.8g %+.8g)\n",
660 			    have->factor / want->factor,
661 			    (have->offset-want->offset)/want->factor,
662 			    want->factor / have->factor,
663 			    (want->offset - have->offset)/have->factor);
664 	}
665 	else
666 		printf("\t* %.8g\n\t/ %.8g\n", have->factor / want->factor,
667 		    want->factor / have->factor);
668 }
669 
670 
671 void
672 usage(void)
673 {
674 	fprintf(stderr,
675 		"usage: units [-f unitsfile] [-q] [-v] [from-unit to-unit]\n");
676 	exit(3);
677 }
678 
679 
680 int
681 main(int argc, char **argv)
682 {
683 
684 	struct unittype have, want;
685 	char havestr[81], wantstr[81];
686 	int optchar;
687 	char *userfile = 0;
688 	int quiet = 0;
689 
690 	while ((optchar = getopt(argc, argv, "Vqf:")) != -1) {
691 		switch (optchar) {
692 		case 'f':
693 			userfile = optarg;
694 			break;
695 		case 'q':
696 			quiet = 1;
697 			break;
698 		case 'V':
699 			fprintf(stderr, "FreeBSD units\n");
700 			usage();
701 			break;
702 		default:
703 			usage();
704 		}
705 	}
706 
707 	if (optind != argc - 2 && optind != argc)
708 		usage();
709 
710 	readunits(userfile);
711 
712 	if (optind == argc - 2) {
713 		strlcpy(havestr, argv[optind], sizeof(havestr));
714 		strlcpy(wantstr, argv[optind + 1], sizeof(wantstr));
715 		initializeunit(&have);
716 		addunit(&have, havestr, 0, 1);
717 		completereduce(&have);
718 		initializeunit(&want);
719 		addunit(&want, wantstr, 0, 1);
720 		completereduce(&want);
721 		showanswer(&have, &want);
722 	}
723 	else {
724 		if (!quiet)
725 			printf("%d units, %d prefixes\n", unitcount,
726 			    prefixcount);
727 		for (;;) {
728 			do {
729 				initializeunit(&have);
730 				if (!quiet)
731 					printf("You have: ");
732 				if (!fgets(havestr, sizeof(havestr), stdin)) {
733 					if (!quiet)
734 						putchar('\n');
735 					exit(0);
736 				}
737 			} while (addunit(&have, havestr, 0, 1) ||
738 			    completereduce(&have));
739 			do {
740 				initializeunit(&want);
741 				if (!quiet)
742 					printf("You want: ");
743 				if (!fgets(wantstr, sizeof(wantstr), stdin)) {
744 					if (!quiet)
745 						putchar('\n');
746 					exit(0);
747 				}
748 			} while (addunit(&want, wantstr, 0, 1) ||
749 			    completereduce(&want));
750 			showanswer(&have, &want);
751 		}
752 	}
753 
754 	return(0);
755 }
756