#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>


struct my_ip_split{
	int a;
	int b;
	int c;
	int d;
};

int verbosity = 1;
FILE *log;

int  RunScan(int port, char * start);
int CharIPToInt(int which, char * toBreak);
void MyIPSplitToString(struct my_ip_split which, char * newStr);

void ImDead(int sig) {
	exit(0); //dont care
}

void PrintUsage(void) {
	printf("gatescan v1.0 - coded by Kable\n");
	printf("Usage (besides the obvious - scanning for wingates)\n");
	printf("-p [port] sets the port to try - i recommend 23\n");
	printf("-b [ip] sets the ip address to start with\n");
	printf("-e [ip] sets the ip address to end with\n");
	printf("-v [1/2] sets the level of verbosity\n");
	printf("\t 1 prints only successful connections to the screen\n");
	printf("\t 2 prints all messages to the screen\n");
	printf("\t both log all successful connections and found wingates to gatelog.txt\n");
	printf("at this time, all four switches are required\n");
	printf("there is little error checking - do not try to trick the program.  it was designed for serious users\n\n");
	printf("Know issues:\n");
	printf("\t occasionaly the program will report that you entered an ivalid ip.  If the ips were indeed correct, just run it again with the same parameters - it should work.\n");
 }

int main(int argc, char *argv[]) {
	
	//opt:	-p = port
	//	-b = begining address
	//	-e = ending address
	//will try to create a socket and record info
	
	(void) signal(SIGTERM, ImDead);

	int opt;
	char bAddress[36], eAddress[36];
	int port;
	
	if (argc < 9) {
		PrintUsage();
		exit(0);
	}
	while ((opt = getopt(argc, argv, "p:b:e:v:")) != -1) {
		
		switch (opt) {
			
			case 'p':
				port = atoi(optarg);
				break;
			case 'b':
				strcpy(bAddress, optarg);
				break;
			case 'e':
				strcpy(eAddress, optarg);
				break;
			case 'v':
				verbosity = atoi(optarg);
				break;
		}
		
	}
	struct my_ip_split low;
	struct my_ip_split high;	
	
	//the most piece of shit part - breaking up the ips so i can do the scanning
	low.a = CharIPToInt(1, bAddress);
	low.b = CharIPToInt(2, bAddress);
	low.c = CharIPToInt(3, bAddress);
	low.d = CharIPToInt(4, bAddress);
	
	high.a = CharIPToInt(1, eAddress);
	high.b = CharIPToInt(2, eAddress);
	high.c = CharIPToInt(3, eAddress);
	high.d = CharIPToInt(4, eAddress);
	
	//check to make sure all values are 255 or less
	if (low.a > 255 || low.b > 255 || low.c > 255 || low.d > 255 || high.a > 255 || high.b > 255 || high.c > 255 || high.d > 255 ) {
		printf("Invalid IP - all values must be 255 or less\n");
		exit(1);
	}
	
	//check to see that the beginning is lower than the ending
	//fuck this for now.  HA!
	
	printf("Scan is beginning at %d.%d.%d.%d\n", low.a, low.b, low.c, low.d);
	printf("Scan id ending at %d.%d.%d.%d\n", high.a, high.b, high.c, high.d);
	printf("Scan is searching for wingate on port %d\n", port);
	printf("Logging successful connections to gatelog.txt - will
append\n\n");	

	log = fopen("gatelog.txt", "a");	

	//here is where the actuall scanning takes place
	//we have to compile the ips into a string and send them to RunScan
	struct my_ip_split current;
	current.a = low.a;
	current.b = low.b;
	current.c = low.c;
	current.d = low.d;
	
	signal(SIGCHLD, SIG_IGN);

	char IPStr[36] = {};
	
	pid_t pid;
		
	//embeded for loops baby
	for (current.a; ; current.a++) {
		if (current.a > 255)
			break;

		for (current.b; ; current.b++) {
			if (current.b > 255) {
				current.b = 0;
				break;
			}
		
			for (current.c; ; current.c++) {
				if (current.c > 255) {
					current.c = 0;
					break;
				}
			
				for (current.d; ; current.d++) {
					if (current.d > 255) {
						current.d = 0;
						break;
					}
					
				
					//if all goes well
					pid = fork();
					if (pid == 0) {
						MyIPSplitToString(current, IPStr);
						RunScan(port, IPStr);
						exit(0);
					}
					sleep(2); //IF YOU WANT IT TO WAIT LONGER, INCREASE THIS VALUE
					kill(pid, SIGTERM); //dont bug me about this either
					
					if (current.a == high.a && current.b == high.b && current.c == high.c && current.d == high.d)
						goto DONE; //we are done
					
				}
			
			
			}
		
		}
		
	}
	
	DONE:
	fclose(log);
	exit(0);
	
}

int RunScan(int port, char * start) {
	
	if (verbosity == 2)
		printf("trying %s\n", start);
	
	int sockfd;
	int len;
	struct sockaddr_in address;
	int result;
	
	char text[255] = {};
	
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	
	address.sin_family = AF_INET;
	address.sin_addr.s_addr = inet_addr(start);
	address.sin_port = htons(port);
	len = sizeof(struct sockaddr_in);
	
	result = connect(sockfd, (struct sockaddr *)&address, len);
	
	if (result == -1) {
		if (verbosity == 2)
			perror(start);
		return 0;
	}
	
	printf("connection established to %s on port %d\n", start, port);
	fprintf(log, "connection established to %s on port %d\n", start, port);	

	result = read(sockfd, text, sizeof(text));
	if (result == 9) {
		
		result = read(sockfd, text, sizeof(text));
		
		if (strcmp(text, "WinGate>")) {

			printf("bytes read= %d : %s\n", result, text);
			fprintf(log, "bytes read= %d : %s\n", result, text);
		}
	}	

	close(sockfd);
	
	return 0;
}


int CharIPToInt(int which, char * toBreak) {
	
	char newStr[3] = {};
	int i;
	int temp, start, end, a;
	
	//find the fist one
	for( i = 0; i < strlen(toBreak); i++ ) {
		if (toBreak[i] == '.')
			break;
	}
	//and copy into new if...
	start = 0;
	end = i;
	if (which == 1) {
		for (temp = start, a = 0; temp < end; temp++, a++)
			newStr[a] = toBreak[temp];
		return (atoi(newStr));
	}
	//find the second one
	start = ++i;
	for( i; i < strlen(toBreak); i++) {
		if (toBreak[i] == '.')
			break;
	}
	end = i;
	if (which == 2) {
		for (temp = start, a = 0; temp < end; temp++, a++)
			newStr[a] = toBreak[temp];
		return (atoi(newStr));
	}
	//find the third one
	start = ++i;
	for (i; i < strlen(toBreak); i++) {
		if (toBreak[i] == '.')
			break;
	}
	end = i;
	if (which == 3) {
		for (temp = start, a = 0; temp < end; temp++, a++)
			newStr[a] = toBreak[temp];
		return (atoi(newStr));
	}
	//and find the last one
	if (which == 4) {
		for (temp = ++i, a = 0; temp < strlen(toBreak)+1; temp++, a++)
			newStr[a] = toBreak[temp];
		return (atoi(newStr));
	}
}


void MyIPSplitToString(struct my_ip_split which, char * newStr) {

	char ipString[36] = {};
	
	int x, y;
	int numd;
	
	//if there is an easier way to do this, fucking tell me
	
	numd = 3;
	if (which.a <= 99)
		numd = 2;
	if (which.a <= 9)
		numd = 1;
	strcat(ipString, ecvt(which.a, numd, &x, &y));
	strcat(ipString, ".");
	numd = 3;
	if (which.b <= 99)
		numd = 2;
	if (which.b <= 9)
		numd = 1;
	strcat(ipString, ecvt(which.b, numd, &x, &y));
	strcat(ipString, ".");
	numd = 3;
	if (which.c <= 99)
		numd = 2;
	if (which.c <= 9)
		numd = 1;
	strcat(ipString, ecvt(which.c, numd, &x, &y));
	strcat(ipString, ".");
	numd = 3;
	if (which.d <= 99)
		numd = 2;
	if (which.d <= 9)
		numd = 1;
	strcat(ipString, ecvt(which.d, numd, &x, &y));
	
	strcpy(newStr, ipString);
	
}
