summaryrefslogtreecommitdiff
path: root/send/send.c
blob: aae33c20587b8ff7505355e3435a782f0fa5de8d (plain)
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
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <time.h>

#include "util.h"
#include "arg.h"
#include "users.h"

FILE *fout;
char *argv0;

static int 
init_client(char *host, int port) {
	int s = socket(AF_INET, SOCK_STREAM, 0);

	struct sockaddr_in addr = {AF_INET, htons(port)};
	if (!inet_pton(AF_INET, host, &addr.sin_addr))
		error("couldn't resolve host");

	if (connect(s, (struct sockaddr *)&addr, sizeof(addr))) 
		error("Failed to connect");

	return s;
}

static void
stop_client(int s) {
	close(s);
}

static void
connect_client(int s, char *nick) {
	char *msg;
	int len = asprintf(&msg, "connect %s", nick);
	send(s, msg, len, 0);
	free(msg);
}

static void
send_msg(int s, char *contents) {
	char *msg;
	time_t t = time(NULL);

	int len = asprintf(&msg, "msg %.5d %s", strlen(contents), contents);

	send(s, msg, len, 0);
	send(s, &t, sizeof(time_t), 0);
	free(msg);
}

static void
resend_msg(int s, char *contents) {
	char *msg;
	time_t t = time(NULL);

	int len = asprintf(&msg, "remsg %.5d %s", strlen(contents), contents);

	send(s, msg, len, 0);
	send(s, &t, sizeof(time_t), 0);
	free(msg);
}

static void
usage() {
	fprintf(stderr, "send [-h host] [-p port] [-P password] [-n nick] -m msg\n");
	exit(1);
}

static int 
recv_response(int s) {
	int i;
	recv(s, &i, sizeof(int), 0);	
	return i;
}

int
main(int argc, char **argv) {
	char *host = "127.0.0.1";
	int port = 1543;
	char *nick = getenv("SENDUSER");
	char *pass = getenv("SENDPASS");
	char *msg = NULL;

	ARGBEGIN {
		case 'h':
			host = EARGF(usage());
			break;
		case 'p':
			port = atoi(EARGF(usage()));
			break;
		case 'P':
			pass = EARGF(usage());
			break;
		case 'n':
			nick = EARGF(usage());
			break;
		case 'm':
			msg = EARGF(usage());
			break;
	} ARGEND;
	
	if (!msg)	
		usage();
	if (!nick)
		error("failed to get nickname, use -n!");
	if (!pass)
		error("failed to get password, use -p!");

	int s = init_client(host, port);
	connect_client(s, nick);
	
	int msg_hash = make_mhash(msg);

	send_msg(s, msg);

	while (recv_response(s) != msg_hash)
		resend_msg(s, msg);
	
	printf("valid msg sent\n");

	stop_client(s);
}