sconnect.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. extern int errno;
  16. int main(argc, argv)
  17. int argc;
  18. char *argv[];
  19. {
  20. char *host;
  21. BIO *out;
  22. char buf[1024 * 10], *p;
  23. SSL_CTX *ssl_ctx = NULL;
  24. SSL *ssl;
  25. BIO *ssl_bio;
  26. int i, len, off, ret = 1;
  27. if (argc <= 1)
  28. host = "localhost:4433";
  29. else
  30. host = argv[1];
  31. #ifdef WATT32
  32. dbug_init();
  33. sock_init();
  34. #endif
  35. /* Lets get nice error messages */
  36. SSL_load_error_strings();
  37. /* Setup all the global SSL stuff */
  38. OpenSSL_add_ssl_algorithms();
  39. ssl_ctx = SSL_CTX_new(SSLv23_client_method());
  40. /* Lets make a SSL structure */
  41. ssl = SSL_new(ssl_ctx);
  42. SSL_set_connect_state(ssl);
  43. /* Use it inside an SSL BIO */
  44. ssl_bio = BIO_new(BIO_f_ssl());
  45. BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE);
  46. /* Lets use a connect BIO under the SSL BIO */
  47. out = BIO_new(BIO_s_connect());
  48. BIO_set_conn_hostname(out, host);
  49. BIO_set_nbio(out, 1);
  50. out = BIO_push(ssl_bio, out);
  51. p = "GET / HTTP/1.0\r\n\r\n";
  52. len = strlen(p);
  53. off = 0;
  54. for (;;) {
  55. i = BIO_write(out, &(p[off]), len);
  56. if (i <= 0) {
  57. if (BIO_should_retry(out)) {
  58. fprintf(stderr, "write DELAY\n");
  59. sleep(1);
  60. continue;
  61. } else {
  62. goto err;
  63. }
  64. }
  65. off += i;
  66. len -= i;
  67. if (len <= 0)
  68. break;
  69. }
  70. for (;;) {
  71. i = BIO_read(out, buf, sizeof(buf));
  72. if (i == 0)
  73. break;
  74. if (i < 0) {
  75. if (BIO_should_retry(out)) {
  76. fprintf(stderr, "read DELAY\n");
  77. sleep(1);
  78. continue;
  79. }
  80. goto err;
  81. }
  82. fwrite(buf, 1, i, stdout);
  83. }
  84. ret = 1;
  85. if (0) {
  86. err:
  87. if (ERR_peek_error() == 0) { /* system call error */
  88. fprintf(stderr, "errno=%d ", errno);
  89. perror("error");
  90. } else
  91. ERR_print_errors_fp(stderr);
  92. }
  93. BIO_free_all(out);
  94. if (ssl_ctx != NULL)
  95. SSL_CTX_free(ssl_ctx);
  96. exit(!ret);
  97. return (ret);
  98. }