1 /* vi: set sw=4 ts=4: */
2 /*
3  * ether-wake.c - Send a magic packet to wake up sleeping machines.
4  *
5  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
6  *
7  * Author:      Donald Becker, http://www.scyld.com/"; http://www.scyld.com/wakeonlan.html
8  * Busybox port: Christian Volkmann <haveaniceday@online.de>
9  *               Used version of ether-wake.c: v1.09 11/12/2003 Donald Becker, http://www.scyld.com/";
10  */
11 
12 /* full usage according Donald Becker
13  * usage: ether-wake [-i <ifname>] [-p aa:bb:cc:dd[:ee:ff]] 00:11:22:33:44:55\n"
14  *
15  *	This program generates and transmits a Wake-On-LAN (WOL)\n"
16  *	\"Magic Packet\", used for restarting machines that have been\n"
17  *	soft-powered-down (ACPI D3-warm state).\n"
18  *	It currently generates the standard AMD Magic Packet format, with\n"
19  *	an optional password appended.\n"
20  *
21  *	The single required parameter is the Ethernet MAC (station) address\n"
22  *	of the machine to wake or a host ID with known NSS 'ethers' entry.\n"
23  *	The MAC address may be found with the 'arp' program while the target\n"
24  *	machine is awake.\n"
25  *
26  *	Options:\n"
27  *		-b	Send wake-up packet to the broadcast address.\n"
28  *		-D	Increase the debug level.\n"
29  *		-i ifname	Use interface IFNAME instead of the default 'eth0'.\n"
30  *		-p <pw>		Append the four or six byte password PW to the packet.\n"
31  *					A password is only required for a few adapter types.\n"
32  *					The password may be specified in ethernet hex format\n"
33  *					or dotted decimal (Internet address)\n"
34  *		-p 00:22:44:66:88:aa\n"
35  *		-p 192.168.1.1\n";
36  *
37  *
38  *	This program generates and transmits a Wake-On-LAN (WOL) "Magic Packet",
39  *	used for restarting machines that have been soft-powered-down
40  *	(ACPI D3-warm state).  It currently generates the standard AMD Magic Packet
41  *	format, with an optional password appended.
42  *
43  *	This software may be used and distributed according to the terms
44  *	of the GNU Public License, incorporated herein by reference.
45  *	Contact the author for use under other terms.
46  *
47  *	This source file was originally part of the network tricks package, and
48  *	is now distributed to support the Scyld Beowulf system.
49  *	Copyright 1999-2003 Donald Becker and Scyld Computing Corporation.
50  *
51  *	The author may be reached as becker@scyld, or C/O
52  *	Scyld Computing Corporation
53  *	914 Bay Ridge Road, Suite 220
54  *	Annapolis MD 21403
55  *
56  *   Notes:
57  *   On some systems dropping root capability allows the process to be
58  *   dumped, traced or debugged.
59  *   If someone traces this program, they get control of a raw socket.
60  *   Linux handles this safely, but beware when porting this program.
61  *
62  *   An alternative to needing 'root' is using a UDP broadcast socket, however
63  *   doing so only works with adapters configured for unicast+broadcast Rx
64  *   filter.  That configuration consumes more power.
65  */
66 //config:config ETHER_WAKE
67 //config:	bool "ether-wake"
68 //config:	default y
69 //config:	select PLATFORM_LINUX
70 //config:	help
71 //config:	  Send a magic packet to wake up sleeping machines.
72 
73 //applet:IF_ETHER_WAKE(APPLET_ODDNAME(ether-wake, ether_wake, BB_DIR_USR_SBIN, BB_SUID_DROP, ether_wake))
74 
75 //kbuild:lib-$(CONFIG_ETHER_WAKE) += ether-wake.o
76 
77 //usage:#define ether_wake_trivial_usage
78 //usage:       "[-b] [-i IFACE] [-p aa:bb:cc:dd[:ee:ff]/a.b.c.d] MAC"
79 //usage:#define ether_wake_full_usage "\n\n"
80 //usage:       "Send a magic packet to wake up sleeping machines.\n"
81 //usage:       "MAC must be a station address (00:11:22:33:44:55) or\n"
82 //usage:       "a hostname with a known 'ethers' entry.\n"
83 //usage:     "\n	-b		Broadcast the packet"
84 //usage:     "\n	-i IFACE	Interface to use (default eth0)"
85 //usage:     "\n	-p PASSWORD	Append four or six byte PASSWORD to the packet"
86 
87 #include "libbb.h"
88 #include <netpacket/packet.h>
89 #include <netinet/ether.h>
90 #include <linux/if.h>
91 
92 /* Note: PF_INET, SOCK_DGRAM, IPPROTO_UDP would allow SIOCGIFHWADDR to
93  * work as non-root, but we need SOCK_PACKET to specify the Ethernet
94  * destination address.
95  */
96 #ifdef PF_PACKET
97 # define whereto_t sockaddr_ll
98 # define make_socket() xsocket(PF_PACKET, SOCK_RAW, 0)
99 #else
100 # define whereto_t sockaddr
101 # define make_socket() xsocket(AF_INET, SOCK_PACKET, SOCK_PACKET)
102 #endif
103 
104 #ifdef DEBUG
105 # define bb_debug_msg(fmt, args...) fprintf(stderr, fmt, ## args)
bb_debug_dump_packet(unsigned char * outpack,int pktsize)106 void bb_debug_dump_packet(unsigned char *outpack, int pktsize)
107 {
108 	int i;
109 	printf("packet dump:\n");
110 	for (i = 0; i < pktsize; ++i) {
111 		printf("%2.2x ", outpack[i]);
112 		if (i % 20 == 19) bb_putchar('\n');
113 	}
114 	printf("\n\n");
115 }
116 #else
117 # define bb_debug_msg(fmt, args...)             ((void)0)
118 # define bb_debug_dump_packet(outpack, pktsize) ((void)0)
119 #endif
120 
121 /* Convert the host ID string to a MAC address.
122  * The string may be a:
123  *    Host name
124  *    IP address string
125  *    MAC address string
126  */
get_dest_addr(const char * hostid,struct ether_addr * eaddr)127 static void get_dest_addr(const char *hostid, struct ether_addr *eaddr)
128 {
129 	struct ether_addr *eap;
130 
131 	eap = ether_aton_r(hostid, eaddr);
132 	if (eap) {
133 		bb_debug_msg("The target station address is %s\n\n", ether_ntoa(eap));
134 #if !defined(__UCLIBC__) || UCLIBC_VERSION >= KERNEL_VERSION(0, 9, 30)
135 	} else if (ether_hostton(hostid, eaddr) == 0) {
136 		bb_debug_msg("Station address for hostname %s is %s\n\n", hostid, ether_ntoa(eaddr));
137 #endif
138 	} else {
139 		bb_show_usage();
140 	}
141 }
142 
143 #define PKT_HEADER_SIZE (20 + 16*6)
fill_pkt_header(unsigned char * pkt,struct ether_addr * eaddr,int broadcast)144 static int fill_pkt_header(unsigned char *pkt, struct ether_addr *eaddr, int broadcast)
145 {
146 	int i;
147 	unsigned char *station_addr = eaddr->ether_addr_octet;
148 
149 	memset(pkt, 0xff, 6);
150 	if (!broadcast)
151 		memcpy(pkt, station_addr, 6);
152 	pkt += 6;
153 
154 	memcpy(pkt, station_addr, 6); /* 6 */
155 	pkt += 6;
156 
157 	*pkt++ = 0x08; /* 12 */ /* Or 0x0806 for ARP, 0x8035 for RARP */
158 	*pkt++ = 0x42; /* 13 */
159 
160 	memset(pkt, 0xff, 6); /* 14 */
161 
162 	for (i = 0; i < 16; ++i) {
163 		pkt += 6;
164 		memcpy(pkt, station_addr, 6); /* 20,26,32,... */
165 	}
166 
167 	return PKT_HEADER_SIZE; /* length of packet */
168 }
169 
get_wol_pw(const char * ethoptarg,unsigned char * wol_passwd)170 static int get_wol_pw(const char *ethoptarg, unsigned char *wol_passwd)
171 {
172 	unsigned passwd[6];
173 	int byte_cnt, i;
174 
175 	/* handle MAC format */
176 	byte_cnt = sscanf(ethoptarg, "%2x:%2x:%2x:%2x:%2x:%2x",
177 	                  &passwd[0], &passwd[1], &passwd[2],
178 	                  &passwd[3], &passwd[4], &passwd[5]);
179 	/* handle IP format */
180 // FIXME: why < 4?? should it be < 6?
181 	if (byte_cnt < 4)
182 		byte_cnt = sscanf(ethoptarg, "%u.%u.%u.%u",
183 		                  &passwd[0], &passwd[1], &passwd[2], &passwd[3]);
184 	if (byte_cnt < 4) {
185 		bb_error_msg("can't read Wake-On-LAN pass");
186 		return 0;
187 	}
188 // TODO: check invalid numbers >255??
189 	for (i = 0; i < byte_cnt; ++i)
190 		wol_passwd[i] = passwd[i];
191 
192 	bb_debug_msg("password: %2.2x %2.2x %2.2x %2.2x (%d)\n\n",
193 	             wol_passwd[0], wol_passwd[1], wol_passwd[2], wol_passwd[3],
194 	             byte_cnt);
195 
196 	return byte_cnt;
197 }
198 
199 int ether_wake_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
ether_wake_main(int argc UNUSED_PARAM,char ** argv)200 int ether_wake_main(int argc UNUSED_PARAM, char **argv)
201 {
202 	const char *ifname = "eth0";
203 	char *pass;
204 	unsigned flags;
205 	unsigned char wol_passwd[6];
206 	int wol_passwd_sz = 0;
207 	int s;  /* Raw socket */
208 	int pktsize;
209 	unsigned char outpack[PKT_HEADER_SIZE + 6 /* max passwd size */ + 16 /* paranoia */];
210 
211 	struct ether_addr eaddr;
212 	struct whereto_t whereto;  /* who to wake up */
213 
214 	/* handle misc user options */
215 	opt_complementary = "=1";
216 	flags = getopt32(argv, "bi:p:", &ifname, &pass);
217 	if (flags & 4) /* -p */
218 		wol_passwd_sz = get_wol_pw(pass, wol_passwd);
219 	flags &= 1; /* we further interested only in -b [bcast] flag */
220 
221 	/* create the raw socket */
222 	s = make_socket();
223 
224 	/* now that we have a raw socket we can drop root */
225 	/* xsetuid(getuid()); - but save on code size... */
226 
227 	/* look up the dest mac address */
228 	get_dest_addr(argv[optind], &eaddr);
229 
230 	/* fill out the header of the packet */
231 	pktsize = fill_pkt_header(outpack, &eaddr, flags /* & 1 OPT_BROADCAST */);
232 
233 	bb_debug_dump_packet(outpack, pktsize);
234 
235 	/* Fill in the source address, if possible. */
236 #ifdef __linux__
237 	{
238 		struct ifreq if_hwaddr;
239 
240 		strncpy_IFNAMSIZ(if_hwaddr.ifr_name, ifname);
241 		ioctl_or_perror_and_die(s, SIOCGIFHWADDR, &if_hwaddr, "SIOCGIFHWADDR on %s failed", ifname);
242 
243 		memcpy(outpack+6, if_hwaddr.ifr_hwaddr.sa_data, 6);
244 
245 # ifdef DEBUG
246 		{
247 			unsigned char *hwaddr = if_hwaddr.ifr_hwaddr.sa_data;
248 			printf("The hardware address (SIOCGIFHWADDR) of %s is type %d  "
249 				"%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n\n", ifname,
250 				if_hwaddr.ifr_hwaddr.sa_family, hwaddr[0], hwaddr[1],
251 				hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5]);
252 		}
253 # endif
254 	}
255 #endif /* __linux__ */
256 
257 	bb_debug_dump_packet(outpack, pktsize);
258 
259 	/* append the password if specified */
260 	if (wol_passwd_sz > 0) {
261 		memcpy(outpack+pktsize, wol_passwd, wol_passwd_sz);
262 		pktsize += wol_passwd_sz;
263 	}
264 
265 	bb_debug_dump_packet(outpack, pktsize);
266 
267 	/* This is necessary for broadcasts to work */
268 	if (flags /* & 1 OPT_BROADCAST */) {
269 		if (setsockopt_broadcast(s) != 0)
270 			bb_perror_msg("SO_BROADCAST");
271 	}
272 
273 #if defined(PF_PACKET)
274 	{
275 		struct ifreq ifr;
276 		strncpy_IFNAMSIZ(ifr.ifr_name, ifname);
277 		xioctl(s, SIOCGIFINDEX, &ifr);
278 		memset(&whereto, 0, sizeof(whereto));
279 		whereto.sll_family = AF_PACKET;
280 		whereto.sll_ifindex = ifr.ifr_ifindex;
281 		/* The manual page incorrectly claims the address must be filled.
282 		   We do so because the code may change to match the docs. */
283 		whereto.sll_halen = ETH_ALEN;
284 		memcpy(whereto.sll_addr, outpack, ETH_ALEN);
285 	}
286 #else
287 	whereto.sa_family = 0;
288 	strcpy(whereto.sa_data, ifname);
289 #endif
290 	xsendto(s, outpack, pktsize, (struct sockaddr *)&whereto, sizeof(whereto));
291 	if (ENABLE_FEATURE_CLEAN_UP)
292 		close(s);
293 	return EXIT_SUCCESS;
294 }
295