~gpanders/iboot

82ec4a6b3d91281ee1f3c9131364c7decc7091ed — Greg Anders 3 months ago
Initial commit
4 files changed, 97 insertions(+), 0 deletions(-)

A .gitignore
A Makefile
A config.def.h
A netpower.c
A  => .gitignore +2 -0
@@ 1,2 @@
config.h
netpower

A  => Makefile +13 -0
@@ 1,13 @@
CFLAGS := -Wall -Wpedantic

netpower: netpower.c config.h
	$(CC) $(CFLAGS) -o $@ $<

config.h: config.def.h
	cp $< $@

install:
	install -m 0755 netpower /usr/local/bin/

clean:
	rm -rf netpower

A  => config.def.h +3 -0
@@ 1,3 @@
static const char ADDRESS[]  = "192.168.1.254";
static const char PORT[]     = "80";
static const char PASSWORD[] = "";

A  => netpower.c +79 -0
@@ 1,79 @@
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#include "config.h"

int main(int argc, char *argv[])
{
	if (argc < 2) {
		fprintf(stderr, "Usage: %s <n|f|c|q>\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	char action = argv[1][0];

	if (action != 'n' && action != 'f' && action != 'c' && action != 'q') {
		fprintf(stderr, "Invalid action: %c\n", action);
		exit(EXIT_FAILURE);
	}

	int sockfd;
	struct addrinfo *result, *rp;
	struct addrinfo hints = {
		.ai_family = AF_INET,
		.ai_socktype = SOCK_STREAM,
		.ai_flags = 0,
		.ai_protocol = 0,
	};

	int s = getaddrinfo(ADDRESS, PORT, &hints, &result);
	if (s != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
		exit(EXIT_FAILURE);
	}

	for (rp = result; rp != NULL; rp = rp->ai_next) {
		sockfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
		if (sockfd == -1) {
			continue;
		}

		if (connect(sockfd, rp->ai_addr, rp->ai_addrlen) != -1) {
			break;
		}

		close(sockfd);
	}

	if (rp == NULL) {
		fprintf(stderr, "Could not connect\n");
		exit(EXIT_FAILURE);
	}

	freeaddrinfo(result);

	char buf[16];
	sprintf(buf, "%s%c\r", PASSWORD, action);

	int buflen = strnlen(buf, 16);
	if (write(sockfd, buf, buflen) != buflen) {
		fprintf(stderr, "partial/failed write\n");
		exit(EXIT_FAILURE);
	}

	memset(buf, 0, 16);
	ssize_t nread = read(sockfd, buf, 16);
	if (nread == -1) {
		perror("read");
		exit(EXIT_FAILURE);
	}

	printf("%s\n", buf);

	exit(EXIT_SUCCESS);
}