Check if stdout is a terminal, if so, print a verbose message.
[tinc] / src / genauth.c
1 /*
2     genauth.c -- generate a random passphrase
3     Copyright (C) 1998,99 Ivo Timmermans <zarq@iname.com>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include "config.h"
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <time.h>
25
26 #include <xalloc.h>
27
28 #include "encr.h"
29
30 unsigned char initvec[] = { 0x22, 0x7b, 0xad, 0x55, 0x41, 0xf4, 0x3e, 0xf3 };
31
32 int main(int argc, char **argv)
33 {
34   FILE *fp;
35   int bits, c, i, bytes;
36   unsigned char *p;
37
38   if(argc != 2)
39     {
40       fprintf(stderr, "Usage: %s bits\n", argv[0]);
41       return 1;
42     }
43
44   if(!(bits = atol(argv[1])))
45     {
46       fprintf(stderr, "Illegal number: %s\n", argv[1]);
47       return 1;
48     }
49
50   bits = ((bits - 1) | 63) + 1;
51   fprintf(stderr, "Generating %d bits number", bits);
52   bytes = bits >> 3;
53
54   if((fp = fopen("/dev/urandom", "r")) == NULL)
55     {
56       perror("Opening /dev/urandom");
57       return 1;
58     }
59
60   p = xmalloc(bytes);
61
62   setbuf(stdout, NULL);
63   for(i = 0; i < bytes; i++)
64     {
65       c = fgetc(fp);
66       if(feof(fp))
67         {
68           puts("");
69           fprintf(stderr, "File was empty!\n");
70         }
71       p[i] = c;
72     }
73   fclose(fp);
74
75   if(isatty(1))
76     {
77       fprintf(stderr, ": done.\nThe following line should be ENTIRELY copied into a passphrase file:\n");
78       printf("%d ", bits);
79       for(i = 0; i < bytes; i++)
80         printf("%02x", p[i]);
81       puts("");
82     }
83   else
84     {
85       printf("%d ", bits);
86       for(i = 0; i < bytes; i++)
87         printf("%02x", p[i]);
88       puts("");
89       fprintf(stderr, ": done.\n");
90     }
91
92   return 0;
93 }
94
95