sconnect.c 2.0 KB

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