summaryrefslogtreecommitdiff
path: root/macping.c
blob: 7958055e9b86577808ff221224a0882d66f5fc34 (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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/*
    Mac-Telnet - Connect to RouterOS or mactelnetd devices via MAC address
    Copyright (C) 2010, Håkon Nessjøen <haakon.nessjoen@gmail.com>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <libintl.h>
#include <locale.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/ether.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <float.h>
#include "protocol.h"
#include "interfaces.h"
#include "config.h"

#define MAX_DEVICES 128
#define MT_INTERFACE_LEN 128

#define PROGRAM_NAME "MAC-Ping"

#define _(String) gettext (String)

static int sockfd, insockfd;

static unsigned short ping_size = 38;

struct net_interface interfaces[MAX_INTERFACES];

static struct in_addr sourceip;
static struct in_addr destip;
static unsigned char dstmac[ETH_ALEN];

static int ping_sent = 0;
static int pong_received = 0;
static float min_ms = FLT_MAX;
static float avg_ms = 0;
static float max_ms = 0;

/* Protocol data direction, not used here, but obligatory for protocol.c */
unsigned char mt_direction_fromserver = 0;

static void print_version() {
	fprintf(stderr, PROGRAM_NAME " " PROGRAM_VERSION "\n");
}

static long long int toddiff(struct timeval *tod1, struct timeval *tod2)
{
    long long t1, t2;
    t1 = tod1->tv_sec * 1000000 + tod1->tv_usec;
    t2 = tod2->tv_sec * 1000000 + tod2->tv_usec;
    return t1 - t2;
}

static void display_results() {
	int percent = (int)((100.f/ping_sent) * pong_received);
	if (percent > 100) {
		percent = 0;
	}

	if (percent < 0) {
		percent = 0;
	}

	if (min_ms == FLT_MAX) {
		min_ms = 0;
	}

	printf("\n");
	printf(_("%d packets transmitted, %d packets received, %d%% packet loss\n"), ping_sent, pong_received, 100 - percent);
	printf(_("round-trip min/avg/max = %.2f/%.2f/%.2f ms\n"), min_ms, avg_ms/pong_received, max_ms);

	/* For bash scripting */
	if (pong_received == 0) {
		exit(1);
	}

	exit(0);
}

int main(int argc, char **argv)  {
	int optval = 1;
	int print_help = 0;
	int send_packets = 5;
	int fastmode = 0;
	int c;
	struct sockaddr_in si_me;
	struct mt_packet packet;
	int i;

	setlocale(LC_ALL, "");
	bindtextdomain("mactelnet","/usr/share/locale");
	textdomain("mactelnet");

	while (1) {
		c = getopt(argc, argv, "fs:c:hv?");

		if (c == -1) {
			break;
		}

		switch (c) {
			case 'f':
				fastmode = 1;
				break;

			case 's':
				ping_size = atoi(optarg) - 18;
				break;

			case 'v':
				print_version();
				exit(0);
				break;

			case 'c':
				send_packets = atoi(optarg);
				break;

			case 'h':
			case '?':
				print_help = 1;
				break;

		}
	}

	/* We don't want people to use this for the wrong reasons */
	if (fastmode && (send_packets == 0 || send_packets > 100)) {
		fprintf(stderr, _("Number of packets to send must be more than 0 and less than 100 in fast mode.\n"));
		return 1;
	}

	if (argc - optind < 1 || print_help) {
		print_version();
		fprintf(stderr, _("Usage: %s <MAC> [-h] [-f] [-c <count>] [-s <packet size>]\n"), argv[0]);

		if (print_help) {
			fprintf(stderr, _("\nParameters:\n"
			"  MAC       MAC-Address of the RouterOS/mactelnetd device.\n"
			"  -f        Fast mode, do not wait before sending next ping request.\n"
			"  -s        Specify size of ping packet.\n"
			"  -c        Number of packets to send. (0 = unlimited)\n"
			"  -h        This help.\n"
			"\n"));
		}
		return 1;
	}

	if (ping_size > ETH_FRAME_LEN - 42) {
		fprintf(stderr, _("Packet size must be between 18 and %d\n"), ETH_FRAME_LEN - 42 + 18);
		exit(1);
	}

	/* Mikrotik RouterOS does not answer unless the packet has the correct recipient mac-address in
	 * the ethernet frame. Unlike real MacTelnet connections where the OS is ok with it being a
	 * broadcast mac address.
	 */
	if (geteuid() != 0) {
		fprintf(stderr, _("You need to have root privileges to use %s.\n"), argv[0]);
		return 1;
	}

	/* Get mac-address from string, or check for hostname via mndp */
	if (!query_mndp_or_mac(argv[optind], dstmac, 1)) {
		/* No valid mac address found, abort */
		return 1;
	}

	sockfd = net_init_raw_socket();

	insockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (insockfd < 0) {
		perror("insockfd");
		return 1;
	}

	/* Set initialize address/port */
	memset((char *) &si_me, 0, sizeof(si_me));
	si_me.sin_family = AF_INET;
	si_me.sin_port = htons(MT_MACTELNET_PORT);
	si_me.sin_addr.s_addr = htonl(INADDR_ANY);

	setsockopt(insockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (optval));

	/* Bind to specified address/port */
	if (bind(insockfd, (struct sockaddr *)&si_me, sizeof(si_me))==-1) {
		fprintf(stderr, _("Error binding to %s:%d\n"), inet_ntoa(si_me.sin_addr), MT_MNDP_PORT);
		return 1;
	}

	/* Listen address*/
	inet_pton(AF_INET, (char *)"0.0.0.0", &sourceip);

	/* Set up global info about the connection */
	inet_pton(AF_INET, (char *)"255.255.255.255", &destip);

	srand(time(NULL));

	/* Enumerate available interfaces */
	net_get_interfaces(interfaces, MAX_INTERFACES);

	if (ping_size < sizeof(struct timeval)) {
		ping_size = sizeof(struct timeval);
	}

	signal(SIGINT, display_results);

	for (i = 0; i < send_packets || send_packets == 0; ++i) {
		fd_set read_fds;
		static struct timeval lasttimestamp;
		int reads, result;
		struct timeval timeout;
		int ii;
		int sent = 0;
		int waitforpacket;
		struct timeval timestamp;
		unsigned char pingdata[1500];

		gettimeofday(&timestamp, NULL);
		memcpy(pingdata, &timestamp, sizeof(timestamp));
		for (ii = sizeof(timestamp); ii < ping_size; ++ii) {
			pingdata[ii] = rand() % 256;
		}

		for (ii = 0; ii < MAX_INTERFACES; ++ii) {
			struct net_interface *interface = &interfaces[ii];

			if (!interface->in_use) {
				break;
			}

			if (!interface->has_mac) {
				continue;
			}

			init_pingpacket(&packet, interface->mac_addr, dstmac);
			add_packetdata(&packet, pingdata, ping_size);
			result = net_send_udp(sockfd, interface, interface->mac_addr, dstmac, &sourceip, MT_MACTELNET_PORT, &destip, MT_MACTELNET_PORT, packet.data, packet.size);

			if (result > 0) {
				sent++;
			}

		}
		if (sent == 0) {
			fprintf(stderr, _("Error sending packet.\n"));
			continue;
		}
		ping_sent++;

		FD_ZERO(&read_fds);
		FD_SET(insockfd, &read_fds);

		timeout.tv_sec = 1;
		timeout.tv_usec = 0;

		waitforpacket = 1;

		while (waitforpacket) {
			/* Wait for data or timeout */
			reads = select(insockfd+1, &read_fds, NULL, NULL, &timeout);
			if (reads <= 0) {
				waitforpacket = 0;
				fprintf(stderr, _("%s ping timeout\n"), ether_ntoa((struct ether_addr *)&dstmac));
				break;
			}

			unsigned char buff[1500];
			struct sockaddr_in saddress;
			unsigned int slen = sizeof(saddress);
			struct mt_mactelnet_hdr pkthdr;

			result = recvfrom(insockfd, buff, 1500, 0, (struct sockaddr *)&saddress, &slen);
			parse_packet(buff, &pkthdr);

			/* TODO: Check that we are the receiving host */
			if (pkthdr.ptype != MT_PTYPE_PONG) {
				/* Wait for the correct packet */
				continue;
			}
			
			struct timeval pongtimestamp;
			struct timeval nowtimestamp;

			waitforpacket = 0;
			gettimeofday(&nowtimestamp, NULL);

			memcpy(&pongtimestamp, pkthdr.data - 4, sizeof(pongtimestamp));
			if (memcmp(pkthdr.data - 4, pingdata, ping_size) == 0) {
				float diff = toddiff(&nowtimestamp, &pongtimestamp) / 1000.0f;

				if (diff < min_ms) {
					min_ms = diff;
				}

				if (diff > max_ms) {
					max_ms = diff;
				}

				avg_ms += diff;

				printf(_("%s %d byte, ping time %.2f ms%s\n"), ether_ntoa((struct ether_addr *)&(pkthdr.srcaddr)), result, diff, (char *)(memcmp(&pongtimestamp,&lasttimestamp,sizeof(lasttimestamp)) == 0 ? " DUP" : ""));
			} else {
				printf(_("%s Reply of %d bytes of unequal data\n"), ether_ntoa((struct ether_addr *)&(pkthdr.srcaddr)), result);
			}
			pong_received++;
			memcpy(&lasttimestamp, &pongtimestamp, sizeof(pongtimestamp));
			if (!fastmode) {
				sleep(1);
			}
		}
	}

	/* Display statistics and exit */
	display_results();

	return 0;
}