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.

102 lines
2.9 KiB

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