server-cmod.c 2.4 KB

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