You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
2.8 KiB

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include "utils.h"
  6. #include "jconf.h"
  7. #include "json.h"
  8. #include "string.h"
  9. static char *to_string(const json_value *value) {
  10. if (value->type == json_string) {
  11. return strndup(value->u.string.ptr, value->u.string.length);
  12. } else if (value->type == json_integer) {
  13. return strdup(itoa(value->u.integer));
  14. } else if (value->type == json_null) {
  15. return "null";
  16. } else {
  17. LOGE("%d", value->type);
  18. FATAL("Invalid config format.");
  19. }
  20. return 0;
  21. }
  22. static int to_int(const json_value *value) {
  23. if (value->type == json_string) {
  24. return atoi(value->u.string.ptr);
  25. } else if (value->type == json_integer) {
  26. return value->u.integer;
  27. } else {
  28. FATAL("Invalid config format.");
  29. }
  30. return 0;
  31. }
  32. jconf_t *read_jconf(const char* file) {
  33. static jconf_t conf;
  34. char *buf;
  35. json_value *obj;
  36. FILE *f = fopen(file, "r");
  37. if (f == NULL) FATAL("Invalid config path.");
  38. fseek(f, 0, SEEK_END);
  39. long pos = ftell(f);
  40. fseek(f, 0, SEEK_SET);
  41. if (pos >= MAX_CONF_SIZE) FATAL("Too large config file.");
  42. buf = malloc(pos);
  43. if (buf == NULL) FATAL("No enough memory.");
  44. fread(buf, pos, 1, f);
  45. fclose(f);
  46. obj = json_parse(buf);
  47. if (obj->type == json_object) {
  48. int i, j;
  49. for (i = 0; i < obj->u.object.length; i++) {
  50. char *name = obj->u.object.values[i].name;
  51. json_value *value = obj->u.object.values[i].value;
  52. if (strcmp(name, "server") == 0) {
  53. if (value->type == json_array) {
  54. for (j = 0; j < value->u.array.length; j++) {
  55. if (j >= MAX_REMOTE_NUM) break;
  56. json_value *v = value->u.array.values[j];
  57. conf.remote_host[j] = to_string(v);
  58. conf.remote_num = j + 1;
  59. }
  60. } else if (value->type == json_string) {
  61. conf.remote_host[0] = to_string(value);
  62. conf.remote_num = 1;
  63. }
  64. } else if (strcmp(name, "server_port") == 0) {
  65. conf.remote_port = to_string(value);
  66. } else if (strcmp(name, "local_port") == 0) {
  67. conf.local_port = to_string(value);
  68. } else if (strcmp(name, "password") == 0) {
  69. conf.password = to_string(value);
  70. } else if (strcmp(name, "method") == 0) {
  71. conf.method = to_string(value);
  72. } else if (strcmp(name, "timeout") == 0) {
  73. conf.timeout = to_string(value);
  74. }
  75. }
  76. } else {
  77. FATAL("Invalid config file");
  78. }
  79. free(buf);
  80. json_value_free(obj);
  81. return &conf;
  82. }