tmcc.c 2.47 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <errno.h>
#include <syslog.h>
#include <unistd.h>
#include <signal.h>
#include <stdarg.h>
#include <sys/time.h>
#include <time.h>
#include <assert.h>
#include "decls.h"

#ifdef LBS
#define	MASTERNODE	"206.163.153.25"
#else
#define	MASTERNODE	"155.99.212.70"
#endif

void		sigcatcher(int foo);

main(int argc, char **argv)
{
	int			sock, length, data, n, cc, err, i;
	struct sockaddr_in	name, client;
	struct timeval		tv;
	struct itimerval	timo;
	char			buf[BUFSIZ], *bp, *response = "";

	if (argc < 2 || argc > 3) {
		fprintf(stderr, "usage: %s <command>\n", argv[0]);
		exit(1);
	}

	while (1) {
		/* Create socket from which to read. */
		sock = socket(AF_INET, SOCK_STREAM, 0);
		if (sock < 0) {
			perror("creating stream socket:");
			exit(1);
		}

		/* Create name. */
		name.sin_family = AF_INET;
		inet_aton(MASTERNODE, &name.sin_addr);
		name.sin_port = htons(TBSERVER_PORT);

		if (connect(sock,
			    (struct sockaddr *) &name, sizeof(name)) == 0) {
			break;
		}
		if (errno == ECONNREFUSED) {
			fprintf(stderr, "Connection to TMCD refused "
				"Sleeping a little while ...\n");
			sleep(10);
		}
		else {
			perror("connecting stream socket");
			exit(1);
		}
		close(sock);
	}

	data = 1;
	if (setsockopt(sock, SOL_SOCKET,
		       SO_KEEPALIVE, &data, sizeof(data)) < 0) {
		perror("setsockopt SO_KEEPALIVE");
		close(sock);
		exit(1);
	}
#ifndef linux
	tv.tv_sec  = 30;
	tv.tv_usec = 0;
	if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
		perror("setsockopt SO_KEEPALIVE");
		close(sock);
		exit(1);
	}
#endif
	if (argc == 2)
		n = snprintf(buf, sizeof(buf) - 1, "%s", argv[1]);
	else
		n = snprintf(buf, sizeof(buf) - 1, "%s %s", argv[1], argv[2]);
	if (n >= sizeof(buf)) {
		fprintf(stderr, "Command to large!\n");
		exit(1);
	}

	/*
	 * Write the command to the socket and wait for the response
	 */
	bp = buf;
	while (n) {
		if ((cc = write(sock, bp, n)) <= 0) {
			if (cc < 0) {
				perror("Writing to socket:");
				exit(1);
			}
			fprintf(stderr, "write aborted");
			exit(1);
		}
		bp += cc;
		n  -= cc;
	}

	while (1) {
		if ((cc = read(sock, buf, sizeof(buf))) <= 0) {
			if (cc < 0) {
				perror("Reading from socket:");
				exit(1);
			}
			break;
		}
		buf[cc] = '\0';
		bp = (char *) malloc(strlen(response) + cc + 1);
		assert(bp);
		strcpy(bp, response);
		strcat(bp, buf);
		response = bp;
	}
	printf("%s", response);

	close(sock);
	exit(0);
}

void
sigcatcher(int foo)
{
}