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