]> git.ipfire.org Git - thirdparty/openssl.git/blob - demos/bio/sconnect.c
Remove /* foo.c */ comments
[thirdparty/openssl.git] / demos / bio / sconnect.c
1 /*-
2 * A minimal program to do SSL to a passed host and port.
3 * It is actually using non-blocking IO but in a very simple manner
4 * sconnect host:port - it does a 'GET / HTTP/1.0'
5 *
6 * cc -I../../include sconnect.c -L../.. -lssl -lcrypto
7 */
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <string.h>
12 #include <openssl/err.h>
13 #include <openssl/ssl.h>
14
15 #define HOSTPORT "localhost:4433"
16 #define CAFILE "root.pem"
17
18 extern int errno;
19
20 int main(argc, argv)
21 int argc;
22 char *argv[];
23 {
24 const char *hostport = HOSTPORT;
25 const char *CAfile = CAFILE;
26 char *hostname;
27 char *cp;
28 BIO *out = NULL;
29 char buf[1024 * 10], *p;
30 SSL_CTX *ssl_ctx = NULL;
31 SSL *ssl;
32 BIO *ssl_bio;
33 int i, len, off, ret = 1;
34
35 if (argc > 1)
36 hostport = argv[1];
37 if (argc > 2)
38 CAfile = argv[2];
39
40 hostname = OPENSSL_strdup(hostport);
41 if ((cp = strchr(hostname, ':')) != NULL)
42 *cp = 0;
43
44 #ifdef WATT32
45 dbug_init();
46 sock_init();
47 #endif
48
49 /* Lets get nice error messages */
50 SSL_load_error_strings();
51
52 /* Setup all the global SSL stuff */
53 OpenSSL_add_ssl_algorithms();
54 ssl_ctx = SSL_CTX_new(TLS_client_method());
55
56 /* Enable trust chain verification */
57 SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
58 SSL_CTX_load_verify_locations(ssl_ctx, CAfile, NULL);
59
60 /* Lets make a SSL structure */
61 ssl = SSL_new(ssl_ctx);
62 SSL_set_connect_state(ssl);
63
64 /* Enable peername verification */
65 if (SSL_set1_host(ssl, hostname) <= 0)
66 goto err;
67
68 /* Use it inside an SSL BIO */
69 ssl_bio = BIO_new(BIO_f_ssl());
70 BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE);
71
72 /* Lets use a connect BIO under the SSL BIO */
73 out = BIO_new(BIO_s_connect());
74 BIO_set_conn_hostname(out, hostport);
75 BIO_set_nbio(out, 1);
76 out = BIO_push(ssl_bio, out);
77
78 p = "GET / HTTP/1.0\r\n\r\n";
79 len = strlen(p);
80
81 off = 0;
82 for (;;) {
83 i = BIO_write(out, &(p[off]), len);
84 if (i <= 0) {
85 if (BIO_should_retry(out)) {
86 fprintf(stderr, "write DELAY\n");
87 sleep(1);
88 continue;
89 } else {
90 goto err;
91 }
92 }
93 off += i;
94 len -= i;
95 if (len <= 0)
96 break;
97 }
98
99 for (;;) {
100 i = BIO_read(out, buf, sizeof(buf));
101 if (i == 0)
102 break;
103 if (i < 0) {
104 if (BIO_should_retry(out)) {
105 fprintf(stderr, "read DELAY\n");
106 sleep(1);
107 continue;
108 }
109 goto err;
110 }
111 fwrite(buf, 1, i, stdout);
112 }
113
114 ret = 1;
115 goto done;
116
117 err:
118 if (ERR_peek_error() == 0) { /* system call error */
119 fprintf(stderr, "errno=%d ", errno);
120 perror("error");
121 } else
122 ERR_print_errors_fp(stderr);
123 done:
124 BIO_free_all(out);
125 SSL_CTX_free(ssl_ctx);
126 return (ret == 1);
127 }