server-cmod.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright 2015-2025 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 = NULL;
  25. BIO *tmp;
  26. SSL_CTX *ctx;
  27. int ret = EXIT_FAILURE, i;
  28. ctx = SSL_CTX_new(TLS_server_method());
  29. if (CONF_modules_load_file("cmod.cnf", "testapp", 0) <= 0) {
  30. fprintf(stderr, "Error processing config file\n");
  31. goto err;
  32. }
  33. if (SSL_CTX_config(ctx, "server") == 0) {
  34. fprintf(stderr, "Error configuring server.\n");
  35. goto err;
  36. }
  37. /* Setup server side SSL bio */
  38. ssl_bio = BIO_new_ssl(ctx, 0);
  39. if ((in = BIO_new_accept(port)) == NULL)
  40. goto err;
  41. /*
  42. * This means that when a new connection is accepted on 'in', The ssl_bio
  43. * will be 'duplicated' and have the new socket BIO push into it.
  44. * Basically it means the SSL BIO will be automatically setup
  45. */
  46. BIO_set_accept_bios(in, ssl_bio);
  47. ssl_bio = NULL;
  48. again:
  49. /*
  50. * The first call will setup the accept socket, and the second will get a
  51. * socket. In this loop, the first actual accept will occur in the
  52. * BIO_read() function.
  53. */
  54. if (BIO_do_accept(in) <= 0)
  55. goto err;
  56. for (;;) {
  57. i = BIO_read(in, buf, sizeof(buf));
  58. if (i == 0) {
  59. /*
  60. * If we have finished, remove the underlying BIO stack so the
  61. * next time we call any function for this BIO, it will attempt
  62. * to do an accept
  63. */
  64. printf("Done\n");
  65. tmp = BIO_pop(in);
  66. BIO_free_all(tmp);
  67. goto again;
  68. }
  69. if (i < 0) {
  70. if (BIO_should_retry(in))
  71. continue;
  72. goto err;
  73. }
  74. fwrite(buf, 1, i, stdout);
  75. fflush(stdout);
  76. }
  77. ret = EXIT_SUCCESS;
  78. err:
  79. if (ret != EXIT_SUCCESS)
  80. ERR_print_errors_fp(stderr);
  81. BIO_free(in);
  82. BIO_free_all(ssl_bio);
  83. return ret;
  84. }