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