saccept.c 2.2 KB

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