Home | History | Annotate | Line # | Download | only in caesar
caesar.c revision 1.15
      1 /*	$NetBSD: caesar.c,v 1.15 2005/05/23 23:02:30 rillig Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1989, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Rick Adams.
      9  *
     10  * Authors:
     11  *	Stan King, John Eldridge, based on algorithm suggested by
     12  *	Bob Morris
     13  * 29-Sep-82
     14  *      Roland Illig, 2005
     15  *
     16  * Redistribution and use in source and binary forms, with or without
     17  * modification, are permitted provided that the following conditions
     18  * are met:
     19  * 1. Redistributions of source code must retain the above copyright
     20  *    notice, this list of conditions and the following disclaimer.
     21  * 2. Redistributions in binary form must reproduce the above copyright
     22  *    notice, this list of conditions and the following disclaimer in the
     23  *    documentation and/or other materials provided with the distribution.
     24  * 3. Neither the name of the University nor the names of its contributors
     25  *    may be used to endorse or promote products derived from this software
     26  *    without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     38  * SUCH DAMAGE.
     39  */
     40 
     41 #include <sys/cdefs.h>
     42 #ifndef lint
     43 __COPYRIGHT("@(#) Copyright (c) 1989, 1993\n\
     44 	The Regents of the University of California.  All rights reserved.\n");
     45 #endif /* not lint */
     46 
     47 #ifndef lint
     48 #if 0
     49 static char sccsid[] = "@(#)caesar.c	8.1 (Berkeley) 5/31/93";
     50 #else
     51 __RCSID("$NetBSD: caesar.c,v 1.15 2005/05/23 23:02:30 rillig Exp $");
     52 #endif
     53 #endif /* not lint */
     54 
     55 #include <ctype.h>
     56 #include <err.h>
     57 #include <errno.h>
     58 #include <limits.h>
     59 #include <math.h>
     60 #include <stdio.h>
     61 #include <string.h>
     62 #include <stdlib.h>
     63 #include <unistd.h>
     64 
     65 #define NCHARS			(1 << CHAR_BIT)
     66 #define LETTERS			(26)
     67 
     68 /*
     69  * letter frequencies (taken from some unix(tm) documentation)
     70  * (unix is a trademark of Bell Laboratories)
     71  */
     72 static const unsigned char upper[LETTERS] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
     73 static const unsigned char lower[LETTERS] = "abcdefghijklmnopqrstuvwxyz";
     74 static double stdf[LETTERS] = {
     75 	7.97, 1.35, 3.61, 4.78, 12.37, 2.01, 1.46, 4.49, 6.39, 0.04,
     76 	0.42, 3.81, 2.69, 5.92,  6.96, 2.91, 0.08, 6.63, 8.77, 9.68,
     77 	2.62, 0.81, 1.88, 0.23,  2.07, 0.06
     78 };
     79 
     80 static unsigned char rottbl[NCHARS];
     81 
     82 
     83 static void
     84 init_rottbl(int rot)
     85 {
     86 	size_t i;
     87 
     88 	rot %= LETTERS;
     89 
     90 	for (i = 0; i < NCHARS; i++)
     91 		rottbl[i] = (unsigned char)i;
     92 
     93 	for (i = 0; i < LETTERS; i++)
     94 		rottbl[upper[i]] = upper[(i + rot) % LETTERS];
     95 
     96 	for (i = 0; i < LETTERS; i++)
     97 		rottbl[lower[i]] = lower[(i + rot) % LETTERS];
     98 }
     99 
    100 static void __attribute__((__noreturn__))
    101 printrot(const char *arg)
    102 {
    103 	int ch;
    104 	long rot;
    105 	char *endp;
    106 
    107 	errno = 0;
    108 	rot = strtol(arg, &endp, 10);
    109 	if (*endp != '\0') {
    110 		errx(EXIT_FAILURE, "bad rotation value: %s", arg);
    111 		/* NOTREACHED */
    112 	}
    113 	if (errno == ERANGE || rot < 0 || rot > INT_MAX) {
    114 		errx(EXIT_FAILURE, "rotation value out of range: %s", arg);
    115 		/* NOTREACHED */
    116 	}
    117 	init_rottbl((int)rot);
    118 
    119 	while ((ch = getchar()) != EOF) {
    120 		if (putchar(rottbl[ch]) == EOF) {
    121 			err(EXIT_FAILURE, "writing to stdout");
    122 			/* NOTREACHED */
    123 		}
    124 	}
    125 	exit(EXIT_SUCCESS);
    126 	/* NOTREACHED */
    127 }
    128 
    129 int
    130 main(int argc, char **argv)
    131 {
    132 	ssize_t i, nread, ntotal;
    133 	double dot, winnerdot;
    134 	int try, winner;
    135 	unsigned char inbuf[2048];
    136 	unsigned int obs[NCHARS];
    137 
    138 	/* revoke setgid privileges */
    139 	(void)setgid(getgid());
    140 
    141 	if (argc > 1) {
    142 		printrot(argv[1]);
    143 		/* NOTREACHED */
    144 	}
    145 
    146 	/* adjust frequency table to weight low probs REAL low */
    147 	for (i = 0; i < LETTERS; i++)
    148 		stdf[i] = log(stdf[i]) + log(LETTERS / 100.0);
    149 
    150 	/* zero out observation table */
    151 	(void)memset(obs, 0, sizeof(obs));
    152 
    153 	for (ntotal = 0; (size_t) ntotal < sizeof(inbuf); ntotal += nread) {
    154 		nread = read(STDIN_FILENO, &inbuf[ntotal],
    155 		             sizeof(inbuf) - ntotal);
    156 		if (nread < 0) {
    157 			err(EXIT_FAILURE, "reading from stdin");
    158 			/* NOTREACHED */
    159 		}
    160 		if (nread == 0)
    161 			break;
    162 	}
    163 
    164 	for (i = 0; i < ntotal; i++)
    165 		obs[inbuf[i]]++;
    166 
    167 	/*
    168 	 * now "dot" the freqs with the observed letter freqs
    169 	 * and keep track of best fit
    170 	 */
    171 	winner = 0;
    172 	winnerdot = 0.0;
    173 	for (try = 0; try < LETTERS; try++) {
    174 		dot = 0.0;
    175 		for (i = 0; i < LETTERS; i++)
    176 			dot += (obs[upper[i]] + obs[lower[i]])
    177 			     * stdf[(i + try) % LETTERS];
    178 
    179 		if (try == 0 || dot > winnerdot) {
    180 			/* got a new winner! */
    181 			winner = try;
    182 			winnerdot = dot;
    183 		}
    184 	}
    185 	init_rottbl(winner);
    186 
    187 	while (ntotal > 0) {
    188 		for (i = 0; i < ntotal; i++) {
    189 			if (putchar(rottbl[inbuf[i]]) == EOF) {
    190 				err(EXIT_FAILURE, "writing to stdout");
    191 				/* NOTREACHED */
    192 			}
    193 		}
    194 		if ((ntotal = read(STDIN_FILENO, inbuf, sizeof(inbuf))) < 0) {
    195 			err(EXIT_FAILURE, "reading from stdin");
    196 			/* NOTREACHED */
    197 		}
    198 	}
    199 	exit(EXIT_FAILURE);
    200 	/* NOTREACHED */
    201 }
    202