stations.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <unistd.h>
  4. #include <stdbool.h>
  5. #include <json-c/json.h>
  6. #include <iwinfo.h>
  7. #include <net/if.h>
  8. #define STR(x) #x
  9. #define XSTR(x) STR(x)
  10. #define BATIF_PREFIX "/sys/class/net/bat0/lower_"
  11. static struct json_object *get_stations(const struct iwinfo_ops *iw, const char *ifname) {
  12. int len;
  13. char buf[IWINFO_BUFSIZE];
  14. struct json_object *stations = json_object_new_object();
  15. if (iw->assoclist(ifname, buf, &len) == -1)
  16. return stations;
  17. // This is just: for entry in assoclist(ifname)
  18. for (struct iwinfo_assoclist_entry *entry = (struct iwinfo_assoclist_entry *)buf;
  19. (char*)(entry+1) <= buf + len; entry++) {
  20. struct json_object *station = json_object_new_object();
  21. json_object_object_add(station, "signal", json_object_new_int(entry->signal));
  22. json_object_object_add(station, "noise", json_object_new_int(entry->noise));
  23. json_object_object_add(station, "inactive", json_object_new_int(entry->inactive));
  24. char macstr[18];
  25. snprintf(macstr, sizeof(macstr), "%02x:%02x:%02x:%02x:%02x:%02x",
  26. entry->mac[0], entry->mac[1], entry->mac[2],
  27. entry->mac[3], entry->mac[4], entry->mac[5]);
  28. json_object_object_add(stations, macstr, station);
  29. }
  30. return stations;
  31. }
  32. static void badrequest() {
  33. printf("Status: 400 Bad Request\n\n");
  34. exit(1);
  35. }
  36. bool interface_is_valid(const char *ifname) {
  37. if (strlen(ifname) > IF_NAMESIZE)
  38. return false;
  39. if (strchr(ifname, '/') != NULL)
  40. return false;
  41. char *path = alloca(1 + strlen(BATIF_PREFIX) + strlen(ifname));
  42. sprintf(path, "%s%s", BATIF_PREFIX, ifname);
  43. return access(path, F_OK) == 0;
  44. }
  45. int main(void) {
  46. char *ifname = getenv("QUERY_STRING");
  47. if (ifname == NULL)
  48. badrequest();
  49. if (!interface_is_valid(ifname))
  50. badrequest();
  51. const struct iwinfo_ops *iw = iwinfo_backend(ifname);
  52. if (iw == NULL)
  53. badrequest();
  54. printf("Access-Control-Allow-Origin: *\n");
  55. printf("Content-type: text/event-stream\n\n");
  56. while (true) {
  57. struct json_object *obj;
  58. obj = get_stations(iw, ifname);
  59. printf("data: %s\n\n", json_object_to_json_string_ext(obj, JSON_C_TO_STRING_PLAIN));
  60. fflush(stdout);
  61. json_object_put(obj);
  62. usleep(150000);
  63. }
  64. return 0;
  65. }