#include #include #include #include #include #include #include "log.h" #include "acpi.h" #include "utils.h" /** * @brief parse output of acpid * * @param str input from acpi socket * @param out the parsed version of it * @return 0 on success */ int acpi_parse(char *str, char **out) { int i, section_num, last_section_pos; size_t section_size; if (strlen(str) <= 1) { log_warn("failed to parse acpid input string: it doesn't exist!"); return 1; } for (last_section_pos = section_num = i = 0; i <= strlen(str); i++) { if (str[i] != ' ' && str[i] != '\n' && str[i] != '\0') { continue; } /* grab correct information of the current section */ section_size = i - last_section_pos; /* copy over the data into the new buffer */ out[section_num] = get_substring(str, last_section_pos, section_size); /* set the last_section_pos for the next section */ last_section_pos = i + 1; section_num++; } return 0; } /** * @brief cleanup the results of acpi_parse * * @param out the pointer to the output from acpi_parse */ void acpi_clean_parse(char *out[4]) { int i; for (i = 0; i < 4; i++) { if (out[i]) { free(out[i]); } } } /** * @brief create a new acpi socket connection * * @param socket_file path to the socket file * @return the socket fd */ int acpi_create_socket(char *socket_file) { int sock_fd; struct sockaddr_un addr = { 0 }; /* create a new socket connection */ sock_fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); if (sock_fd < 0) { log_fatal("failed to create a new socket: %s", strerror(errno)); return 1; } /* setup the socket */ addr.sun_family = AF_UNIX; strncpy(addr.sun_path, socket_file, strlen(socket_file) + 1); /* connect */ if (connect(sock_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { if (close(sock_fd) < 0) { log_fatal("failed to close socket close: %s", strerror(errno)); } log_fatal("failed to connect to the socket: %s", strerror(errno)); return 1; } return sock_fd; } /** * @brief close the socket connection * * @param sockfd the sockets fd * @return 0 on success 1 on error */ int acpi_close_socket(int sockfd) { if (close(sockfd) < 0) { log_fatal("failed to close socket: %s", strerror(errno)); return 1; } return 0; }