host.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* Shared runtime setup for browser-host and host-curl. */
  2. #include <limits.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <unistd.h>
  7. #include "host.h"
  8. #include "fs.h"
  9. struct host_options host_opts;
  10. char host_root[1024];
  11. char host_repo[1024];
  12. char host_curl_bin[1024];
  13. static void dirname_in_place(char *p)
  14. {
  15. char *slash = strrchr(p, '/');
  16. if (!slash) {
  17. strcpy(p, ".");
  18. return;
  19. }
  20. if (slash == p)
  21. slash[1] = '\0';
  22. else
  23. *slash = '\0';
  24. }
  25. static void exe_dir(char *out, size_t cap, const char *argv0)
  26. {
  27. ssize_t n = readlink("/proc/self/exe", out, cap - 1);
  28. if (n > 0) {
  29. out[n] = '\0';
  30. dirname_in_place(out);
  31. return;
  32. }
  33. if (argv0 && argv0[0]) {
  34. snprintf(out, cap, "%s", argv0);
  35. dirname_in_place(out);
  36. return;
  37. }
  38. out[0] = '\0';
  39. }
  40. int host_runtime_init(const char *argv0, const char *root)
  41. {
  42. const char *env_root = getenv("NEBOS_HOST_ROOT");
  43. const char *env_curl = getenv("NEBOS_HOST_CURL");
  44. char exe[1024];
  45. if (!root || !root[0])
  46. root = env_root && env_root[0] ? env_root :
  47. "/tmp/opencode/nebos-browser-root";
  48. snprintf(host_root, sizeof(host_root), "%s", root);
  49. /* Drop a trailing slash except for "/". */
  50. if (strlen(host_root) > 1 && host_root[strlen(host_root) - 1] == '/')
  51. host_root[strlen(host_root) - 1] = '\0';
  52. exe_dir(exe, sizeof(exe), argv0);
  53. snprintf(host_repo, sizeof(host_repo), "%s", exe);
  54. if (env_curl && env_curl[0])
  55. snprintf(host_curl_bin, sizeof(host_curl_bin), "%s", env_curl);
  56. else
  57. snprintf(host_curl_bin, sizeof(host_curl_bin), "%s/host-curl",
  58. exe);
  59. setenv("NEBOS_HOST_ROOT", host_root, 1);
  60. setenv("NEBOS_HOST_CURL", host_curl_bin, 1);
  61. if (host_fs_init(host_root) != 0) {
  62. fprintf(stderr, "browser-host: cannot create profile root %s\n",
  63. host_root);
  64. return -1;
  65. }
  66. return 0;
  67. }