tor_api.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file tor_api.c
  8. **/
  9. #include "or/tor_api.h"
  10. #include "or/tor_api_internal.h"
  11. // Include this after the above headers, to insure that they don't
  12. // depend on anything else.
  13. #include "orconfig.h"
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. // We don't want to use tor_malloc and tor_free here, since this needs
  18. // to run before anything is initialized at all, and ought to run when
  19. // we're not linked to anything at all.
  20. #define raw_malloc malloc
  21. #define raw_free free
  22. tor_main_configuration_t *
  23. tor_main_configuration_new(void)
  24. {
  25. static const char *fake_argv[] = { "tor" };
  26. tor_main_configuration_t *cfg = raw_malloc(sizeof(*cfg));
  27. if (cfg == NULL)
  28. return NULL;
  29. memset(cfg, 0, sizeof(*cfg));
  30. cfg->argc = 1;
  31. cfg->argv = (char **) fake_argv;
  32. return cfg;
  33. }
  34. int
  35. tor_main_configuration_set_command_line(tor_main_configuration_t *cfg,
  36. int argc, char *argv[])
  37. {
  38. if (cfg == NULL)
  39. return -1;
  40. cfg->argc = argc;
  41. cfg->argv = argv;
  42. return 0;
  43. }
  44. void
  45. tor_main_configuration_free(tor_main_configuration_t *cfg)
  46. {
  47. if (cfg == NULL)
  48. return;
  49. raw_free(cfg);
  50. }
  51. /* Main entry point for the Tor process. Called from main().
  52. *
  53. * This function is distinct from main() only so we can link main.c into
  54. * the unittest binary without conflicting with the unittests' main.
  55. *
  56. * Some embedders have historically called this function; but that usage is
  57. * deprecated: they should use tor_run_main() instead.
  58. */
  59. int
  60. tor_main(int argc, char *argv[])
  61. {
  62. tor_main_configuration_t *cfg = tor_main_configuration_new();
  63. if (!cfg) {
  64. puts("INTERNAL ERROR: Allocation failure. Cannot proceed");
  65. return 1;
  66. }
  67. if (tor_main_configuration_set_command_line(cfg, argc, argv) < 0) {
  68. puts("INTERNAL ERROR: Can't set command line. Cannot proceed.");
  69. return 1;
  70. }
  71. int rv = tor_run_main(cfg);
  72. tor_main_configuration_free(cfg);
  73. return rv;
  74. }