-
Notifications
You must be signed in to change notification settings - Fork 6
/
wold.c
347 lines (294 loc) · 8.69 KB
/
wold.c
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
339
340
341
342
343
344
345
346
347
/*
* wold is deamon listening for WOL packets and running some action
* on reception.
*
* Copyright (C) 2013 Paulius Zaleckas <[email protected]>
*
* 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 <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <ctype.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/ip.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>
#include <syslog.h>
#include <pwd.h>
#include <grp.h>
#include <netinet/in.h>
#include <string.h>
static char *action = "/etc/wol.action";
static struct passwd action_passwd;
static char *user_env[32];
static gid_t g_gid = -1;
static void err_handler(char *err)
{
syslog(LOG_ERR, "%s: %m", err);
exit(errno);
}
/**
* Obtains the MAC address of the external NIC
* Method is courtesy of http://stackoverflow.com/questions/1779715/how-to-get-mac-address-of-your-machine-using-a-c-program
*/
static void get_mac_address(unsigned char* mac_address)
{
struct ifreq ifr;
struct ifconf ifc;
char buf[1024];
int success = 0;
memset(mac_address, 0, 6);
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock == -1) return;
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) return;
struct ifreq* it = ifc.ifc_req;
const struct ifreq* const end = it + (ifc.ifc_len / sizeof(struct ifreq));
for (; it != end; ++it) {
strcpy(ifr.ifr_name, it->ifr_name);
if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
if (! (ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
success = 1;
break;
}
}
}
else { /* handle error */ }
}
if (success){
memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6);
}
}
static int name_to_passwd(char const *name)
{
const long buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
struct passwd pwbuf, *pwbufp;
char *buf;
if (!name)
return -1;
if (buflen == -1)
return -1;
buf = malloc(buflen);
if (!buf)
return -1;
/* On error always sets pwbufp to NULL */
getpwnam_r(name, &pwbuf, buf, buflen, &pwbufp);
if (!pwbufp)
return -1;
memcpy(&action_passwd, pwbufp, sizeof(*pwbufp));
/* don't free the buffer as it will free data pointed by action_passwd elements */
// free(buf);
return 0;
}
static char *set_env_var(const char *name, const char *value)
{
char buff[256];
int len;
if (!value)
return NULL;
len = snprintf(buff, sizeof(buff), "%s=%s", name, value);
/* fail on error and if output was truncated */
if ((len < 0) || len >= sizeof(buff))
return NULL;
return strdup(buff);
}
static void setup_user_env()
{
int i = 0;
/*
* Setup environment for action user
* Maximum 32 variables (if need more increase at the user_env declaration)
*/
user_env[i++] = set_env_var("PATH", "/bin:/usr/bin");
user_env[i++] = set_env_var("IFS", " \t\n");
user_env[i++] = set_env_var("USER", action_passwd.pw_name);
user_env[i++] = set_env_var("USERNAME", action_passwd.pw_name);
user_env[i++] = set_env_var("LOGNAME", action_passwd.pw_name);
user_env[i++] = set_env_var("HOME", action_passwd.pw_dir);
user_env[i++] = set_env_var("SHELL", action_passwd.pw_shell);
/* Copy DISPLAY (if available) for GUI apps */
if (getenv("DISPLAY"))
user_env[i++] = set_env_var("DISPLAY", getenv("DISPLAY"));
/* check if all variables were set correctly */
while (i--)
if (!user_env[i]) {
fprintf(stderr, "Failed to generate action user environment.\n");
exit(EXIT_FAILURE);
}
}
static int run_action(void)
{
pid_t pid;
gid_t gid = g_gid;
int rv;
int commpipe[2]; /* This holds the fd for the input & output of the pipe */
/* Setup communication pipeline first */
if (pipe(commpipe))
err_handler("Pipe error!");
/* Attempt to fork and check for errors */
pid = fork();
if (pid == -1)
err_handler("Fork failed"); /* something went wrong */
if (pid) {
/* A positive (non-negative) PID indicates the parent process */
dup2(commpipe[1],1); /* Replace stdout with out side of the pipe */
close(commpipe[0]); /* Close unused side of pipe (in side) */
setvbuf(stdout,(char*)NULL,_IONBF,0); /* Set non-buffered output on stdout */
wait(&rv); /* Wait for child process to end */
return rv;
} else {
/* A zero PID indicates that this is the child process */
dup2(commpipe[0], 0); /* Replace stdin with the in side of the pipe */
close(commpipe[1]); /* Close unused side of pipe (out side) */
/* Run action as different user */
if (gid == (gid_t) -1) {
gid = action_passwd.pw_gid;
}
if (setgid(gid) || setuid(action_passwd.pw_uid))
err_handler("Failed to change user");
/* change workinf dir to user HOME */
if (chdir(action_passwd.pw_dir))
err_handler("Failed to change working directory");
/* Replace the child fork with a new process */
if (execle(action, action, NULL, user_env) == -1)
err_handler("Failed to run action");
}
/* to silence compiler warning */
return 0;
}
static void listen_wol(uint16_t port)
{
int sfd;
struct sockaddr_in si;
char buf[256];
const char sync[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
unsigned char mac[6];
get_mac_address(mac);
sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sfd == -1)
err_handler("Failed to open socket");
memset(&si, 0, sizeof(si));
si.sin_family = AF_INET;
si.sin_port = htons(port);
si.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sfd, (struct sockaddr *)&si, sizeof(si)) == -1)
err_handler("Failed open port");
while (1) {
int len;
len = recvfrom(sfd, buf, sizeof(buf), 0, NULL, NULL);
if (len == -1)
err_handler("Error while reading socket");
if (len < 102) {
syslog(LOG_WARNING, "Received packet too short: %u", len);
continue;
}
if (memcmp(sync, buf, 6)) {
syslog(LOG_WARNING, "Received non WOL packet");
continue;
}
if (memcmp(mac, buf+6, 6)) {
syslog(LOG_WARNING, "Received WOL packet for other MAC");
continue;
}
syslog(LOG_INFO, "Received WOL packet");
syslog(LOG_INFO, "%s returned %i", action, run_action());
}
}
static void usage()
{
fprintf(stderr, "Usage: wold -u user [-g group] [-p port] [-a action] [-f]\n");
fprintf(stderr, "\t-u username\trun action as different user (required)\n");
fprintf(stderr, "\t-g group / gid\trun action as different group / gid\n");
fprintf(stderr, "\t-p port\t\tport to listen for WOL packet (default: 9)\n");
fprintf(stderr, "\t-f\t\tstay in foreground\n");
fprintf(stderr, "\t-a action\tapplication to run on WOL (default: /etc/wol.action)\n");
}
int main(int argc, char *argv[])
{
int opt;
int foreground = 0;
int user_set = 0;
unsigned long int port = 9;
while ((opt = getopt(argc, argv, "u:g:p:fa:h")) != -1) {
switch (opt) {
case 'u':
if (name_to_passwd(optarg)) {
fprintf(stderr, "User %s not found\n", optarg);
exit(EXIT_FAILURE);
}
user_set = 1;
break;
case 'g':
if(isdigit(optarg[0])) {
// passed in the group id in number
g_gid = atoi(optarg);
} else {
// passed in the group name
struct group* grp = getgrnam(optarg);
if (grp) {
g_gid = grp->gr_gid;
} else {
fprintf(stderr, "Group %s not found\n", optarg);
exit(EXIT_FAILURE);
}
}
break;
case 'p':
port = strtoul(optarg, NULL, 0);
if (port > USHRT_MAX) {
perror("Invalid port");
exit(errno);
}
break;
case 'f':
foreground = 1;
break;
case 'a':
action = strdup(optarg);
break;
case 'h':
default:
usage();
exit(EXIT_FAILURE);
}
}
if (!user_set) {
fprintf(stderr, "User to run action not provided. It is required.\n");
exit(EXIT_FAILURE);
}
setup_user_env();
if (access(action, X_OK)) {
fprintf(stderr, "%s: %s\n", action, strerror(errno));
exit(errno);
}
if (!foreground) {
if (daemon(0, 0) < 0) {
perror("Failed to daemonize");
exit(errno);
}
openlog("wold", LOG_PID, LOG_DAEMON);
} else
openlog("wold", LOG_PERROR | LOG_PID, LOG_DAEMON);
listen_wol((uint16_t)port);
return 0;
}