Imported Upstream version 3.0.30
[platform/upstream/gnutls.git] / tests / rng-fork.c
1 /*
2  * Copyright (C) 2008-2012 Free Software Foundation, Inc.
3  *
4  * Author: Nikos Mavrogiannopoulos
5  *
6  * This file is part of GnuTLS.
7  *
8  * GnuTLS is free software: you can redistribute it and/or modify it
9  * under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuTLS is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with GnuTLS.  If not, see <http://www.gnu.org/licenses/>.
20  *
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26
27 #include <stdio.h>
28 #include <unistd.h>
29 #include <sys/types.h>
30 #if !defined(_WIN32)
31 #include <sys/wait.h>
32 #endif
33
34 #include "utils.h"
35 #include <gnutls/gnutls.h>
36 #include <gnutls/crypto.h>
37
38 #if !defined(_WIN32)
39 static void dump(const char* name, unsigned char* buf, int buf_size)
40 {
41 int i;
42   printf("%s: ", name);
43   for(i=0;i<buf_size;i++)
44     printf("%.2x:", buf[i]);
45   printf("\n");
46 }
47   
48 #define FILENAME "./rng-test"
49    
50 void
51 doit (void)
52 {
53   unsigned char buf1[32];
54   unsigned char buf2[32];
55   pid_t pid;
56   int ret;
57   FILE* fp;
58
59   gnutls_global_init ();
60   pid = fork();
61   if (pid == 0)
62     {
63       fp = fopen(FILENAME, "w");
64       if (fp == NULL)
65         fail("cannot open file");
66       
67       gnutls_rnd (GNUTLS_RND_RANDOM, buf1, sizeof (buf1));
68       if (debug) dump("buf1", buf1, sizeof(buf1));
69       
70       fwrite(buf1, 1, sizeof(buf1), fp);
71       fclose(fp);
72     }
73   else
74     {
75       /* daddy */
76       gnutls_rnd (GNUTLS_RND_RANDOM, buf2, sizeof (buf2));
77       if (debug) dump("buf2", buf2, sizeof(buf2));
78       waitpid(pid, NULL, 0);
79       
80       fp = fopen(FILENAME, "r");
81       if (fp == NULL)
82         fail("cannot open file");
83         
84       ret = fread(buf1, 1, sizeof(buf1), fp);
85       
86       fclose(fp);
87       remove(FILENAME);
88       
89       if (ret != sizeof(buf1))
90         {
91           fail("error testing the random generator.");
92           return;
93         }
94
95       if (memcmp(buf1, buf2, sizeof(buf1))==0)
96         {
97           fail("error in the random generator. Produces same valus after fork()");
98           return;
99         }
100       if(debug)
101         success("success\n");
102     }
103
104   gnutls_global_deinit ();
105 }
106 #else
107 void
108 doit (void)
109 {
110   exit (77);
111 }
112 #endif