server-cmod.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* NOCW */
  2. /* demos/bio/server-cmod.c */
  3. /*
  4. * A minimal TLS server it ses SSL_CTX_config and a configuration file to
  5. * set most server parameters.
  6. */
  7. #include <stdio.h>
  8. #include <signal.h>
  9. #include <openssl/err.h>
  10. #include <openssl/ssl.h>
  11. #include <openssl/conf.h>
  12. int main(int argc, char *argv[])
  13. {
  14. unsigned char buf[512];
  15. char *port = "*:4433";
  16. BIO *in = NULL;
  17. BIO *ssl_bio, *tmp;
  18. SSL_CTX *ctx;
  19. int ret = 1, i;
  20. SSL_load_error_strings();
  21. /* Add ciphers and message digests */
  22. OpenSSL_add_ssl_algorithms();
  23. if (CONF_modules_load_file("cmod.cnf", "testapp", 0) <= 0) {
  24. fprintf(stderr, "Error processing config file\n");
  25. goto err;
  26. }
  27. ctx = SSL_CTX_new(TLS_server_method());
  28. if (SSL_CTX_config(ctx, "server") == 0) {
  29. fprintf(stderr, "Error configuring server.\n");
  30. goto err;
  31. }
  32. /* Setup server side SSL bio */
  33. ssl_bio = BIO_new_ssl(ctx, 0);
  34. if ((in = BIO_new_accept(port)) == NULL)
  35. goto err;
  36. /*
  37. * This means that when a new connection is accepted on 'in', The ssl_bio
  38. * will be 'duplicated' and have the new socket BIO push into it.
  39. * Basically it means the SSL BIO will be automatically setup
  40. */
  41. BIO_set_accept_bios(in, ssl_bio);
  42. again:
  43. /*
  44. * The first call will setup the accept socket, and the second will get a
  45. * socket. In this loop, the first actual accept will occur in the
  46. * BIO_read() function.
  47. */
  48. if (BIO_do_accept(in) <= 0)
  49. goto err;
  50. for (;;) {
  51. i = BIO_read(in, buf, sizeof(buf));
  52. if (i == 0) {
  53. /*
  54. * If we have finished, remove the underlying BIO stack so the
  55. * next time we call any function for this BIO, it will attempt
  56. * to do an accept
  57. */
  58. printf("Done\n");
  59. tmp = BIO_pop(in);
  60. BIO_free_all(tmp);
  61. goto again;
  62. }
  63. if (i < 0) {
  64. if (BIO_should_retry(in))
  65. continue;
  66. goto err;
  67. }
  68. fwrite(buf, 1, i, stdout);
  69. fflush(stdout);
  70. }
  71. ret = 0;
  72. err:
  73. if (ret) {
  74. ERR_print_errors_fp(stderr);
  75. }
  76. BIO_free(in);
  77. exit(ret);
  78. return (!ret);
  79. }