Added derdump.py, a fault-tolerant developer-friendly DER / ASN.1 pretty printer
[hexio] / outputter.c
1 #include <unistd.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <sys/time.h>
5 #include <signal.h>
6 #include <errno.h>
7
8
9 /* Outputter reads input from stdin and prints it in hex on stdout.
10  * It will collect lines of one character plus anything that arrives
11  * within a second after that first character, limited to a maximum
12  * number of characters that just fits on a 80-char wide display.
13  */
14
15
16 #define BYTES_PER_LINE 24
17
18 unsigned long timersofar = 123;
19
20 void tick (int signal) {
21         timersofar++;
22 }
23
24 struct itimerval tickival = { { 0, 0 } , { 1, 0 } };
25 struct itimerval stopival = { { 0, 0 } , { 0, 0 } };
26
27 int main (int argc, char *argv []) {
28         unsigned char buf [BYTES_PER_LINE];
29         unsigned long timer;
30         size_t len;
31         size_t offset = 0;
32         if (signal (SIGALRM, tick) == SIG_ERR) {
33                 perror ("Failed to install interval handler");
34                 exit (1);
35         }
36         system ("stty raw -echo");
37         printf ("*** outputter starts -- in hex mode ***\r\n");
38         fflush (stdout);
39 /*
40         while (timersofar = timer,
41                         len = read (0, buf, BYTES_PER_LINE),
42                         (len > 0) || ( errno == SIGALRM ) ) {
43 */
44         while (len = read (0, buf, 1), len > 0) {
45                 size_t i;
46                 int len2;
47                 /* Set a timeout before reading more; ignore problems */
48                 setitimer (ITIMER_REAL, &tickival, NULL);
49                 len2 = read (0, buf + 1, BYTES_PER_LINE - 1);
50                 setitimer (ITIMER_REAL, &stopival, NULL);
51                 if ((len2 == -1) && (errno == EINTR)) {
52                         len2 = 0;
53                 }
54                 if (len2 >= 0) {
55                         len += len2;
56                 }
57                 printf ("%08x", offset);
58                 offset += len;
59                 for (i=0; i<len; i++) {
60                         printf (" %02x", buf [i]);
61                 }
62                 printf ("\r\n");
63                 fflush (stdout);
64                 if (len2 < 0) {
65                         len = -1;
66                         break;
67                 }
68         }
69         if (len < 0) {
70                 perror ("read(2) failed");
71         } else {
72                 printf ("*** outputter ends ***\r\n");
73         }
74         system ("stty cooked echo");
75         return 0;
76 }