saccept.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. /* NOCW */
  2. /* demos/bio/saccept.c */
  3. /*-
  4. * A minimal program to serve an SSL connection.
  5. * It uses blocking.
  6. * saccept host:port
  7. * host is the interface IP to use. If any interface, use *:port
  8. * The default it *:4433
  9. *
  10. * cc -I../../include saccept.c -L../.. -lssl -lcrypto -ldl
  11. */
  12. #include <stdio.h>
  13. #include <signal.h>
  14. #include <openssl/err.h>
  15. #include <openssl/ssl.h>
  16. #define CERT_FILE "server.pem"
  17. BIO *in = NULL;
  18. void close_up()
  19. {
  20. if (in != NULL)
  21. BIO_free(in);
  22. }
  23. int main(argc, argv)
  24. int argc;
  25. char *argv[];
  26. {
  27. char *port = NULL;
  28. BIO *ssl_bio, *tmp;
  29. SSL_CTX *ctx;
  30. SSL *ssl;
  31. char buf[512];
  32. int ret = 1, i;
  33. if (argc <= 1)
  34. port = "*:4433";
  35. else
  36. port = argv[1];
  37. signal(SIGINT, close_up);
  38. SSL_load_error_strings();
  39. #ifdef WATT32
  40. dbug_init();
  41. sock_init();
  42. #endif
  43. /* Add ciphers and message digests */
  44. OpenSSL_add_ssl_algorithms();
  45. ctx = SSL_CTX_new(SSLv23_server_method());
  46. if (!SSL_CTX_use_certificate_file(ctx, CERT_FILE, SSL_FILETYPE_PEM))
  47. goto err;
  48. if (!SSL_CTX_use_PrivateKey_file(ctx, CERT_FILE, SSL_FILETYPE_PEM))
  49. goto err;
  50. if (!SSL_CTX_check_private_key(ctx))
  51. goto err;
  52. /* Setup server side SSL bio */
  53. ssl = SSL_new(ctx);
  54. ssl_bio = BIO_new_ssl(ctx, 0);
  55. if ((in = BIO_new_accept(port)) == NULL)
  56. goto err;
  57. /*
  58. * This means that when a new connection is accepted on 'in', The ssl_bio
  59. * will be 'duplicated' and have the new socket BIO push into it.
  60. * Basically it means the SSL BIO will be automatically setup
  61. */
  62. BIO_set_accept_bios(in, ssl_bio);
  63. again:
  64. /*
  65. * The first call will setup the accept socket, and the second will get a
  66. * socket. In this loop, the first actual accept will occur in the
  67. * BIO_read() function.
  68. */
  69. if (BIO_do_accept(in) <= 0)
  70. goto err;
  71. for (;;) {
  72. i = BIO_read(in, buf, 512);
  73. if (i == 0) {
  74. /*
  75. * If we have finished, remove the underlying BIO stack so the
  76. * next time we call any function for this BIO, it will attempt
  77. * to do an accept
  78. */
  79. printf("Done\n");
  80. tmp = BIO_pop(in);
  81. BIO_free_all(tmp);
  82. goto again;
  83. }
  84. if (i < 0)
  85. goto err;
  86. fwrite(buf, 1, i, stdout);
  87. fflush(stdout);
  88. }
  89. ret = 0;
  90. err:
  91. if (ret) {
  92. ERR_print_errors_fp(stderr);
  93. }
  94. if (in != NULL)
  95. BIO_free(in);
  96. exit(ret);
  97. return (!ret);
  98. }