File: lircrcd.cpp

package info (click to toggle)
lirc 0.10.2-0.10
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,268 kB
  • sloc: ansic: 26,981; cpp: 9,187; sh: 5,875; python: 4,507; makefile: 1,049; xml: 63
file content (748 lines) | stat: -rw-r--r-- 17,729 bytes parent folder | download | duplicates (4)
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
/****************************************************************************
** lircrcd.c ***************************************************************
****************************************************************************
*
* lircrcd - daemon that manages current mode for all applications
*
* Copyright (C) 2004 Christoph Bartelmus <lirc@bartelmus.de>
*
*/

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <getopt.h>

#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <limits.h>
#include <signal.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <syslog.h>

#include <string>
#include <deque>

#include "lirc_client.h"
#include "lirc/lirc_log.h"

#define MAX_CLIENTS 100
#define WHITE_SPACE " \t"

static const logchannel_t logchannel = LOG_APP;

struct config_info {
	char*			config_string;
	struct config_info*	next;
};

struct event_info {
	char*			code;
	struct config_info*	first;
	struct event_info*	next;
};

struct client_data {
	int			fd;
	char*			ident_string;
	std::deque<std::string> pending_codes;
	std::deque<std::string> pending_strings;
	std::string             last_code;
};

struct protocol_directive {
	const char* name;
	int (*function)(int fd, char* message, char* arguments);
};

struct pfd_byname{
	struct pollfd sockfd;
	struct pollfd clis[MAX_CLIENTS];
};


static int code_func(int fd, char* message, char* arguments);
static int ident_func(int fd, char* message, char* arguments);
static int getmode_func(int fd, char* message, char* arguments);
static int setmode_func(int fd, char* message, char* arguments);
static int send_result(int fd, char* message, const char* result);
static int send_success(int fd, char* message);

const struct protocol_directive directives[] = {
	{ "CODE",    code_func	  },
	{ "IDENT",   ident_func	  },
	{ "GETMODE", getmode_func },
	{ "SETMODE", setmode_func },
	{ NULL,	     NULL	  }
	/*
	 * {"DEBUG",debug},
	 * {"DEBUG_LEVEL",debug_level},
	 */
};

enum protocol_string_num {
	P_BEGIN = 0,
	P_DATA,
	P_END,
	P_ERROR,
	P_SUCCESS,
	P_SIGHUP
};

const char* const protocol_string[] = {
	"BEGIN\n",
	"DATA\n",
	"END\n",
	"ERROR\n",
	"SUCCESS\n",
	"SIGHUP\n"
};


static sig_atomic_t term = 0;
static int termsig;
static int clin = 0;
static struct client_data clis[MAX_CLIENTS];

static int daemonized = 0;

static struct lirc_config* config;

static int send_error(int fd, char* message, const char* format_str, ...);


static int get_client_index(int fd)
{
	int i;

	for (i = 0; i < clin; i++)
		if (fd == clis[i].fd)
			return i;
	/* shouldn't ever happen */
	return -1;
}

/* cut'n'paste from fileutils-3.16: */

#define isodigit(c) ((c) >= '0' && (c) <= '7')

/* Return a positive integer containing the value of the ASCII
* octal number S.  If S is not an octal number, return -1.  */

static int oatoi(const char* s)
{
	register int i;

	if (*s == 0)
		return -1;
	for (i = 0; isodigit(*s); ++s)
		i = i * 8 + *s - '0';
	if (*s)
		return -1;
	return i;
}

/* A safer write(), since sockets might not write all but only some of the
 * bytes requested */
inline int write_socket(int fd, const char* buf, int len)
{
	int done, todo = len;

	while (todo) {
		done = write(fd, buf, todo);
		if (done <= 0)
			return done;
		buf += done;
		todo -= done;
	}
	return len;
}

inline int write_socket_len(int fd, const char* buf)
{
	int len;

	len = strlen(buf);
	if (write_socket(fd, buf, len) < len)
		return 0;
	return 1;
}

inline int read_timeout(int fd, char* buf, int len, int timeout_us)
{
	int ret, n;
	struct pollfd  pfd = {fd, POLLIN, 0}; // fd, events, revents
	int timeout = timeout_us > 0 ? timeout_us/1000 : -1;

	/* CAVEAT: (from libc documentation)
	 * Any signal will cause `select' to return immediately.  So if your
	 * program uses signals, you can't rely on `select' to keep waiting
	 * for the full time specified.  If you want to be sure of waiting
	 * for a particular amount of time, you must check for `EINTR' and
	 * repeat the `select' with a newly calculated timeout based on the
	 * current time.  See the example below.
	 *
	 * The timeout is not recalculated here although it should, we keep
	 * waiting as long as there are EINTR.
	 */

	do
		ret = curl_poll(&pfd, 1, timeout * 1000);
	while (ret == -1 && errno == EINTR);
	if (ret == -1) {
		log_perror_err("read_timeout, curl_poll() failed");
		return -1;
	};
	if (ret == 0)
		return 0;       /* timeout */
	n = read(fd, buf, len);
	if (n == -1) {
		log_perror_err("read_timeout: read() failed");
		return -1;
	}
	return n;
}

static void sigterm(int sig)
{
	/* all signals are blocked now */
	if (term)
		return;
	term = 1;
	termsig = sig;
}

static void nolinger(int sock)
{
	static struct linger linger = { 0, 0 };
	int lsize = sizeof(struct linger);

	setsockopt(sock, SOL_SOCKET, SO_LINGER, (void*)&linger, lsize);
}

static void remove_client(int i)
{
	shutdown(clis[i].fd, 2);
	close(clis[i].fd);
	if (clis[i].ident_string)
		free(clis[i].ident_string);

	log_trace("removed client");

	clin--;
	for (; i < clin; i++)
		clis[i] = clis[i + 1];
}

void add_client(int sock)
{
	int fd;
	socklen_t clilen;
	struct sockaddr client_addr;
	int flags;

	clilen = sizeof(client_addr);
	fd = accept(sock, (struct sockaddr*)&client_addr, &clilen);
	if (fd == -1) {
		log_perror_err("accept() failed for new client");
		return;
	}
	;

	if (clin >= MAX_CLIENTS) {
		log_error("connection rejected");
		shutdown(fd, 2);
		close(fd);
		return;
	}
	nolinger(fd);
	flags = fcntl(fd, F_GETFL, 0);
	if (flags != -1)
		fcntl(fd, F_SETFL, flags | O_NONBLOCK);
        log_trace2( "accepted new client");
	clis[clin].fd = fd;
	clis[clin].ident_string = NULL;
	clin++;
}


static int opensocket(const char* socket_id, const char* socketname, mode_t permission, struct sockaddr_un* addr)
{
	int sockfd;
	struct stat s;
	int new_socket = 1;
	int ret;

	/* get socket name */
	if ((socketname == NULL &&
	     lirc_getsocketname(socket_id,
				addr->sun_path, sizeof(addr->sun_path)) >
	     sizeof(addr->sun_path)) || (socketname != NULL && strlen(socketname) >= sizeof(addr->sun_path))) {
		fprintf(stderr, "%s: filename too long", progname);
		return -1;
	}
	if (socketname != NULL)
		strcpy(addr->sun_path, socketname);

	/* create socket */
	sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
	if (sockfd == -1) {
		perror("could not create socket");
		return -1;
	}

	/*
	 * get owner, permissions, etc.
	 * so new socket can be the same since we
	 * have to delete the old socket.
	 */
	ret = stat(addr->sun_path, &s);
	if (ret == -1 && errno != ENOENT) {
		perrorf("could not get file information for %s",
			addr->sun_path);
		goto opensocket_failed;
	}

	if (ret != -1) {
		new_socket = 0;
		ret = unlink(addr->sun_path);
		if (ret == -1) {
			perrorf("could not delete %s", addr->sun_path);
			goto opensocket_failed;
		}
	}

	addr->sun_family = AF_UNIX;
	if (bind(sockfd, (struct sockaddr*)addr, sizeof(*addr)) == -1) {
		perror("could not assign address to socket");
		goto opensocket_failed;
	}

	if (new_socket ?
	    chmod(addr->sun_path, permission) :
	    (chmod(addr->sun_path, s.st_mode) == -1 || chown(addr->sun_path, s.st_uid, s.st_gid) == -1)
	    ) {
		perrorf("could not set file permissions on %s", addr->sun_path);
		goto opensocket_failed;
	}

	listen(sockfd, 3);
	nolinger(sockfd);

	return sockfd;

opensocket_failed:
	close(sockfd);
	return -1;
}


static int code_func(int fd, char* message, char* arguments)
{
	int index;

	if (arguments == NULL)
		return send_error(fd, message, "protocol error\n");
	index = get_client_index(fd);
	if (index == -1)
		return send_error(fd, message, "identify yourself first!\n");
	log_trace2("%s asking for code -%s-", clis[index].ident_string, arguments);

	if (clis[index].last_code == arguments) {
		// client checking for more strings
		if (!clis[index].pending_strings.empty()) {
			std::string s = clis[index].pending_strings.front();
			clis[index].pending_strings.pop_front();
			return send_result(fd, message, s.c_str());
		} else {
			clis[index].last_code = "A never used code";
			return send_success(fd, message);
		}
	}
	clis[index].last_code = arguments;
	clis[index].pending_codes.push_back(arguments);

	const char* const_code = clis[index].pending_codes.front().c_str();
	char* var_code = strdup(const_code);
	char* prog = clis[index].ident_string;
	char* s;
	int r;

	clis[index].pending_codes.pop_front();
	while (true) {
		r = lirc_code2charprog(config, var_code, &s, &prog);
		if ( r != 0 || s == NULL || *s == '\0')
			break;
		clis[index].pending_strings.push_back(s);
	}
	free(var_code);
	if ( r != 0 ) {
		return send_error(fd, message, "Cannor decode: %s", arguments);
	} else if (clis[index].pending_strings.size() == 0) {
		return send_success(fd, message);
	} else {
		std::string s = clis[index].pending_strings.front();
		clis[index].pending_strings.pop_front();
		return send_result(fd, message, s.c_str());
	}
}


static int ident_func(int fd, char* message, char* arguments)
{
	int index;

	if (arguments == NULL)
		return send_error(fd, message, "protocol error\n");
	log_trace1("IDENT %s", arguments);
	index = get_client_index(fd);
	if (clis[index].ident_string != NULL)
		return send_error(fd, message, "protocol error\n");
	clis[index].ident_string = strdup(arguments);
	if (clis[index].ident_string == NULL)
		return send_error(fd, message, "out of memory\n");

	log_trace("%s connected", clis[index].ident_string);
	return send_success(fd, message);
}


static int getmode_func(int fd, char* message, char* arguments)
{
	if (arguments != NULL)
		return send_error(fd, message, "protocol error\n");
	log_trace1("GETMODE");
	if (lirc_getmode(config))
		return send_result(fd, message, lirc_getmode(config));
	return send_success(fd, message);
}


static int setmode_func(int fd, char* message, char* arguments)
{
	const char* mode = NULL;

	log_trace1(arguments != NULL ? "SETMODE %s" : "SETMODE", arguments);
	mode = lirc_setmode(config, arguments);
	if (mode)
		return send_result(fd, message, mode);
	return arguments == NULL ? send_success(fd, message) : send_error(fd, message, "out of memory\n");
}


static int send_result(int fd, char* message, const char* result)
{
	const char* count = "1\n";
	char buffer[strlen(result) + 1 + 1];

	sprintf(buffer, "%s\n", result);

	if (!(write_socket_len(fd, protocol_string[P_BEGIN]) &&
	      write_socket_len(fd, message) &&
	      write_socket_len(fd, protocol_string[P_SUCCESS]) &&
	      write_socket_len(fd, protocol_string[P_DATA]) &&
	      write_socket_len(fd, count) &&
	      write_socket_len(fd, buffer) && write_socket_len(fd, protocol_string[P_END])))
		return 0;
	return 1;
}


static int send_success(int fd, char* message)
{
	if (!(write_socket_len(fd, protocol_string[P_BEGIN]) &&
	      write_socket_len(fd, message) &&
	      write_socket_len(fd, protocol_string[P_SUCCESS]) && write_socket_len(fd, protocol_string[P_END])))
		return 0;
	return 1;
}

static int send_error(int fd, char* message, const char* format_str, ...)
{
	char lines[12], buffer[PACKET_SIZE + 1];
	int i, n, len;
	va_list ap;
	char* s1;
	char* s2;

	va_start(ap, format_str);
	vsprintf(buffer, format_str, ap);
	va_end(ap);

	s1 = strrchr(message, '\n');
	s2 = strrchr(buffer, '\n');
	if (s1 != NULL)
		s1[0] = 0;
	if (s2 != NULL)
		s2[0] = 0;
	log_error("error processing command: %s", message);
	log_error("%s", buffer);
	if (s1 != NULL)
		s1[0] = '\n';
	if (s2 != NULL)
		s2[0] = '\n';

	n = 0;
	len = strlen(buffer);
	for (i = 0; i < len; i++)
		if (buffer[i] == '\n')
			n++;
	sprintf(lines, "%d\n", n);

	if (!(write_socket_len(fd, protocol_string[P_BEGIN]) &&
	      write_socket_len(fd, message) &&
	      write_socket_len(fd, protocol_string[P_ERROR]) &&
	      write_socket_len(fd, protocol_string[P_DATA]) &&
	      write_socket_len(fd, lines) &&
	      write_socket_len(fd, buffer) && write_socket_len(fd, protocol_string[P_END])))
		return 0;
	return 1;
}


static int get_command(int fd)
{
	int length;
	char buffer[PACKET_SIZE + 1], backup[PACKET_SIZE + 1];
	char* end;
	int packet_length, i;
	char* directive;

	length = read_timeout(fd, buffer, PACKET_SIZE, 0);
	packet_length = 0;
	while (length > packet_length) {
		buffer[length] = 0;
		end = strchr(buffer, '\n');
		if (end == NULL) {
			log_error("bad send packet: \"%s\"", buffer);
			/* remove clients that behave badly */
			return 0;
		}
		end[0] = 0;
		log_trace("received command: \"%s\"", buffer);
		packet_length = strlen(buffer) + 1;

		strcpy(backup, buffer);
		strcat(backup, "\n");
		directive = strtok(buffer, WHITE_SPACE);
		if (directive == NULL) {
			if (!send_error(fd, backup, "bad send packet\n"))
				return 0;
			goto skip;
		}
		for (i = 0; directives[i].name != NULL; i++) {
			if (strcasecmp(directive, directives[i].name) == 0) {
				if (!directives[i].function(fd, backup, strtok(NULL, "")))
					return 0;
				goto skip;
			}
		}

		if (!send_error(fd, backup, "unknown directive: \"%s\"\n", directive))
			return 0;
skip:
		if (length > packet_length) {
			int new_length;

			memmove(buffer, buffer + packet_length, length - packet_length + 1);
			if (strchr(buffer, '\n') == NULL) {
				new_length = read_timeout(fd, buffer + length -
							  packet_length, PACKET_SIZE - (length - packet_length), 5);
				if (new_length > 0)
					length = length - packet_length + new_length;
				else
					length = new_length;
			} else {
				length -= packet_length;
			}
			packet_length = 0;
		}
	}

	if (length == 0)        /* EOF: connection closed by client */
		return 0;
	return 1;
}



static void loop(int sockfd)
{
	static const int POLLFDS_SIZE =
		sizeof(struct pfd_byname) / sizeof(struct pollfd);
	union {
		struct pfd_byname byname;
		struct pollfd byindex[POLLFDS_SIZE];
	} poll_fds;
	int i;
	int ret;

	while (1) {
		do {
			/* handle signals */
			if (term) {
				log_notice("caught signal");
				return;
			}
			memset(&poll_fds, 0, sizeof(poll_fds));
			for (i = 0; i < POLLFDS_SIZE; i += 1)
				poll_fds.byindex[i].fd = -1;
			poll_fds.byname.sockfd.fd = sockfd;
			poll_fds.byname.sockfd.events = POLLIN;

			for (i = 0; i < clin; i++) {
				poll_fds.byname.clis[i].fd = clis[i].fd;
				poll_fds.byname.clis[i].events = POLLIN;
			}
			log_trace2("poll");
			ret = curl_poll((struct pollfd*) &poll_fds.byindex,
				         POLLFDS_SIZE,
				         0);
			if (ret == -1 && errno != EINTR) {
				log_perror_err("loop: curl_poll() failed");
				raise(SIGTERM);
				continue;
			}
		} while (ret == -1 && errno == EINTR);

		for (i = 0; i < clin; i++) {
			if (poll_fds.byname.clis[i].revents & POLLIN) {
				poll_fds.byname.clis[i].revents	= 0;
				if (get_command(clis[i].fd) == 0) {
					remove_client(i);
					i--;
					if (clin == 0) {
						log_info("last client disconnected, shutting down");
						return;
					}
				}
			}
		}
		if (poll_fds.byname.sockfd.revents & POLLIN) {
			log_trace("registering local client");
			add_client(sockfd);
		}
	}
}

int main(int argc, char** argv)
{
	char* configfile;
	const char* socketfile = NULL;
	mode_t permission = S_IRUSR | S_IWUSR;
	int socket;
	struct sigaction act;
	struct sockaddr_un addr;
	char dir[FILENAME_MAX + 1] = { 0 };

	lirc_log_open("lircrcd", 0, LIRC_NOLOG);
	while (1) {
		int c;
		static struct option long_options[] = {
			{ "help",	no_argument,	   NULL, 'h' },
			{ "version",	no_argument,	   NULL, 'v' },
			{ "permission", required_argument, NULL, 'p' },
			{ "output",	required_argument, NULL, 'o' },
			{ 0,		0,		   0,	 0   }
		};
		c = getopt_long(argc, argv, "hvp:o:", long_options, NULL);
		if (c == -1)
			break;
		switch (c) {
		case 'h':
			printf("Usage: %s [options] config-file\n", progname);
			printf("\t -h --help\t\t\tdisplay this message\n");
			printf("\t -v --version\t\t\tdisplay version\n");
			printf("\t -p --permission=mode\t\tfile permissions for socket\n");
			printf("\t -o --output=socket\t\toutput socket filename\n");
			return EXIT_SUCCESS;
		case 'v':
			printf("%s %s\n", progname, VERSION);
			return EXIT_SUCCESS;
		case 'p':
			if (oatoi(optarg) == -1) {
				fprintf(stderr, "%s: invalid mode\n", progname);
				return EXIT_FAILURE;
			}
			permission = oatoi(optarg);
			break;
		case 'o':
			socketfile = optarg;
			break;
		default:
			printf("Usage: %s [options] config-file\n", progname);
			return EXIT_FAILURE;
		}
	}
	if (optind == argc - 1) {
		configfile = argv[optind];
	} else {
		fprintf(stderr, "%s: invalid argument count\n", progname);
		return EXIT_FAILURE;
	}

	/* read config file */
	if (lirc_readconfig_only(configfile, &config, NULL) != 0) {
		lirc_deinit();
		return EXIT_FAILURE;
	}

	/* open socket */
	socket = opensocket(config->lircrc_class, socketfile, permission, &addr);
	if (socket == -1) {
		lirc_freeconfig(config);
		lirc_deinit();
		return EXIT_FAILURE;
	}

	/* fork */
	if (getcwd(dir, sizeof(dir)) == NULL) {
		lirc_freeconfig(config);
		lirc_deinit();
		perror("getcwd()");
		return EXIT_FAILURE;
	}
	if (daemon(0, 0) == -1) {
		perror("daemon() failed");
		shutdown(socket, 2);
		close(socket);
		lirc_deinit();
		lirc_freeconfig(config);
		return EXIT_FAILURE;
	}
	daemonized = 1;

	openlog(progname, LOG_CONS | LOG_PID, LOG_USER);
	umask(0);
	signal(SIGPIPE, SIG_IGN);

	act.sa_handler = sigterm;
	sigfillset(&act.sa_mask);
	act.sa_flags = SA_RESTART;      /* don't fiddle with EINTR */
	sigaction(SIGTERM, &act, NULL);
	sigaction(SIGINT, &act, NULL);
	sigaction(SIGHUP, &act, NULL);

	log_notice("%s started", progname);
	loop(socket);

	closelog();
	shutdown(socket, 2);
	close(socket);
	if (chdir(dir) == 0)
		unlink(addr.sun_path);
	lirc_freeconfig(config);
	lirc_deinit();
	return EXIT_SUCCESS;
}