From 26c3d216efec8a9c7d9971c957d57de3432a8ca6 Mon Sep 17 00:00:00 2001 From: uvos Date: Tue, 11 Jun 2024 14:48:02 +0200 Subject: [PATCH] inital commit --- build.sh | 3 ++ main.c | 128 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 131 insertions(+) create mode 100755 build.sh create mode 100644 main.c diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..d2089b1 --- /dev/null +++ b/build.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +gcc main.c -lasound -o devicewatchdog diff --git a/main.c b/main.c new file mode 100644 index 0000000..2ae635f --- /dev/null +++ b/main.c @@ -0,0 +1,128 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define REBOOT_FILE "/var/cache/wdreboot" + +void free_str_array(char** array) +{ + for(size_t i = 0; array[i]; ++i) + free(array[i]); + + free(array); +} + +char** get_alsa_card_names(void) +{ + size_t array_len = 4; + char **array = (char**)malloc(array_len*sizeof(*array)); + + int card = -1; + size_t index = 0; + while(true) + { + int ret = snd_card_next(&card); + if(ret < 0 || card < 0) + break; + + if(index >= array_len-1) + { + array_len = array_len*2; + array = realloc(array, array_len*sizeof(*array)); + } + + char *name = NULL; + ret = snd_card_get_name(card, &name); + if(ret < 0 || !name) + break; + + array[index] = name; + ++index; + } + + array[index] = NULL; + + return array; +} + +bool reboot_file_exists(void) +{ + struct stat buf; + int ret = stat(REBOOT_FILE, &buf); + return ret == 0; +} + +void reboot_system(bool dry_run) +{ + if(reboot_file_exists()) + { + puts("Not rebooting as a reboot was executed before"); + return; + } + + int fd = open(REBOOT_FILE, O_WRONLY | O_CREAT); + close(fd); + + if(!dry_run) + system("systemctl reboot"); +} + + +int main(int argc, char** argv) +{ + bool dry_run = false; + if(argc > 1) + { + dry_run = true; + puts("dry run only"); + } + + char** card_array = get_alsa_card_names(); + bool found_cfx = false; + for(size_t i = 0; card_array[i]; ++i) + { + printf("Card %zu: %s\n", i, card_array[i]); + } + free_str_array(card_array); + + struct ifaddrs* ifap_list; + int ret = getifaddrs(&ifap_list); + if(ret < 0) + { + fprintf(stderr, "Unable to read network interfaces: %s", strerror(errno)); + return 0; + } + + size_t ifcount = 0; + for(struct ifaddrs* ifap = ifap_list; ifap; ifap = ifap->ifa_next) + { + printf("If: %s\n", ifap->ifa_name); + ++ifcount; + } + printf("If count: %zu\n", ifcount); + freeifaddrs(ifap_list); + + if(!found_cfx) + { + puts("Executeing shutdown because crateive xifi soundcard was not found"); + reboot_system(dry_run); + } + else if(ifcount < 6) + { + puts("Executeing shutdown because not all network interfaces are avialable"); + reboot_system(dry_run); + } + else + { + puts("System is all good"); + remove(REBOOT_FILE); + } + + return 0; +}