Added lirc.
[irreco.git] / lirc-0.8.4a / daemons / lircd.c
bloba7320104a4575ff4b61f22f3cf0b09f86a01ae87
1 /* $Id: lircd.c,v 5.80 2008/10/04 21:48:43 lirc Exp $ */
3 /****************************************************************************
4 ** lircd.c *****************************************************************
5 ****************************************************************************
7 * lircd - LIRC Decoder Daemon
8 *
9 * Copyright (C) 1996,97 Ralph Metzler <rjkm@thp.uni-koeln.de>
10 * Copyright (C) 1998,99 Christoph Bartelmus <lirc@bartelmus.de>
12 * =======
13 * HISTORY
14 * =======
16 * 0.1: 03/27/96 decode SONY infra-red signals
17 * create mousesystems mouse signals on pipe /dev/lircm
18 * 04/07/96 send ir-codes to clients via socket (see irpty)
19 * 05/16/96 now using ir_remotes for decoding
20 * much easier now to describe new remotes
22 * 0.5: 09/02/98 finished (nearly) complete rewrite (Christoph)
26 #ifdef HAVE_CONFIG_H
27 # include <config.h>
28 #endif
30 /* disable daemonise if maintainer mode SIM_REC / SIM_SEND defined */
31 #if defined(SIM_REC) || defined (SIM_SEND)
32 # undef DAEMONIZE
33 #endif
35 #define _GNU_SOURCE
36 #define _BSD_SOURCE
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <stdarg.h>
41 #include <ctype.h>
42 #include <string.h>
43 #include <signal.h>
44 #include <unistd.h>
45 #include <time.h>
46 #include <getopt.h>
47 #include <sys/time.h>
48 #include <sys/socket.h>
49 #include <sys/un.h>
50 #include <netinet/in.h>
51 #include <netdb.h>
52 #include <arpa/inet.h>
53 #include <sys/types.h>
54 #include <sys/stat.h>
55 #include <errno.h>
56 #include <limits.h>
57 #include <fcntl.h>
58 #include <sys/file.h>
60 #if defined __APPLE__
61 #include <sys/ioccom.h>
62 #endif
64 #ifndef timersub
65 #define timersub(a, b, result) \
66 do { \
67 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
68 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
69 if ((result)->tv_usec < 0) { \
70 --(result)->tv_sec; \
71 (result)->tv_usec += 1000000; \
72 } \
73 } while (0)
74 #endif
76 #include "lircd.h"
77 #include "ir_remote.h"
78 #include "config_file.h"
79 #include "hardware.h"
80 #include "hw-types.h"
81 #include "release.h"
83 struct ir_remote *remotes;
84 struct ir_remote *free_remotes=NULL;
86 extern struct ir_remote *decoding;
87 extern struct ir_remote *last_remote;
88 extern struct ir_remote *repeat_remote;
89 extern struct ir_ncode *repeat_code;
91 static int repeat_fd=-1;
92 static char *repeat_message=NULL;
94 extern struct hardware hw;
96 char *progname="lircd";
97 char *configfile=LIRCDCFGFILE;
98 #ifndef USE_SYSLOG
99 char *logfile=LOGFILE;
100 #else
101 static const char *syslogident = "lircd-" VERSION;
102 #endif
103 FILE *pidf;
104 char *pidfile = PIDFILE;
105 char *lircdfile = LIRCD;
107 struct protocol_directive directives[] =
109 {"LIST",list},
110 {"SEND_ONCE",send_once},
111 {"SEND_START",send_start},
112 {"SEND_STOP",send_stop},
113 {"VERSION",version},
114 {"SET_TRANSMITTERS",set_transmitters},
115 {"SIMULATE",simulate},
116 {NULL,NULL}
118 {"DEBUG",debug},
119 {"DEBUG_LEVEL",debug_level},
123 enum protocol_string_num {
124 P_BEGIN=0,
125 P_DATA,
126 P_END,
127 P_ERROR,
128 P_SUCCESS,
129 P_SIGHUP
132 char *protocol_string[] =
134 "BEGIN\n",
135 "DATA\n",
136 "END\n",
137 "ERROR\n",
138 "SUCCESS\n",
139 "SIGHUP\n"
142 static void log_enable(int enabled);
143 static int log_enabled = 1;
145 #ifndef USE_SYSLOG
146 #define HOSTNAME_LEN 128
147 char hostname[HOSTNAME_LEN+1];
149 FILE *lf=NULL;
150 #endif
152 /* quite arbitrary limits */
153 #define MAX_PEERS 100
154 /* substract one for lirc, sockfd, sockinet, logfile, pidfile */
155 #define MAX_CLIENTS (FD_SETSIZE-5-MAX_PEERS)
157 int sockfd, sockinet;
158 int clis[MAX_CLIENTS];
160 #define CT_LOCAL 1
161 #define CT_REMOTE 2
163 int cli_type[MAX_CLIENTS];
164 int clin=0;
166 int listen_tcpip=0;
167 unsigned short int port=LIRC_INET_PORT;
169 struct peer_connection *peers[MAX_PEERS];
170 int peern = 0;
172 int debug=0;
173 int daemonized=0;
174 int allow_simulate=0;
176 static sig_atomic_t term=0,hup=0,alrm=0;
177 static int termsig;
179 /* set_transmitters only supports 32 bit int */
180 #define MAX_TX (CHAR_BIT*sizeof(unsigned long))
182 inline int max(int a,int b)
184 return(a>b ? a:b);
187 /* cut'n'paste from fileutils-3.16: */
189 #define isodigit(c) ((c) >= '0' && (c) <= '7')
191 /* Return a positive integer containing the value of the ASCII
192 octal number S. If S is not an octal number, return -1. */
194 static int
195 oatoi (s)
196 char *s;
198 register int i;
200 if (*s == 0)
201 return -1;
202 for (i = 0; isodigit (*s); ++s)
203 i = i * 8 + *s - '0';
204 if (*s)
205 return -1;
206 return i;
209 /* A safer write(), since sockets might not write all but only some of the
210 bytes requested */
212 inline int write_socket(int fd, const char *buf, int len)
214 int done,todo=len;
216 while(todo)
218 #ifdef SIM_REC
220 done=write(fd,buf,todo);
222 while(done<0 && errno == EAGAIN);
223 #else
224 done=write(fd,buf,todo);
225 #endif
226 if(done<=0) return(done);
227 buf+=done;
228 todo-=done;
230 return(len);
233 inline int write_socket_len(int fd, const char *buf)
235 int len;
237 len=strlen(buf);
238 if(write_socket(fd,buf,len)<len) return(0);
239 return(1);
242 inline int read_timeout(int fd,char *buf,int len,int timeout)
244 fd_set fds;
245 struct timeval tv;
246 int ret,n;
248 FD_ZERO(&fds);
249 FD_SET(fd,&fds);
250 tv.tv_sec=timeout;
251 tv.tv_usec=0;
253 /* CAVEAT: (from libc documentation)
254 Any signal will cause `select' to return immediately. So if your
255 program uses signals, you can't rely on `select' to keep waiting
256 for the full time specified. If you want to be sure of waiting
257 for a particular amount of time, you must check for `EINTR' and
258 repeat the `select' with a newly calculated timeout based on the
259 current time. See the example below.
261 Obviously the timeout is not recalculated in the example because
262 this is done automatically on Linux systems...
267 ret=select(fd+1,&fds,NULL,NULL,&tv);
269 while(ret==-1 && errno==EINTR);
270 if(ret==-1)
272 logprintf(LOG_ERR,"select() failed");
273 logperror(LOG_ERR,NULL);
274 return(-1);
276 else if(ret==0) return(0); /* timeout */
277 n=read(fd,buf,len);
278 if(n==-1)
280 logprintf(LOG_ERR,"read() failed");
281 logperror(LOG_ERR,NULL);
282 return(-1);
284 return(n);
287 void sigterm(int sig)
289 /* all signals are blocked now */
290 if(term) return;
291 term=1;
292 termsig=sig;
295 void dosigterm(int sig)
297 int i;
299 signal(SIGALRM,SIG_IGN);
301 if(free_remotes!=NULL)
303 free_config(free_remotes);
305 free_config(remotes);
306 logprintf(LOG_NOTICE,"caught signal");
307 for (i=0; i<clin; i++)
309 shutdown(clis[i],2);
310 close(clis[i]);
312 shutdown(sockfd,2);
313 close(sockfd);
314 if(listen_tcpip)
316 shutdown(sockinet,2);
317 close(sockinet);
319 fclose(pidf);
320 (void) unlink(pidfile);
321 if(clin>0 && hw.deinit_func) hw.deinit_func();
322 #ifdef USE_SYSLOG
323 closelog();
324 #else
325 if(lf) fclose(lf);
326 #endif
327 signal(sig,SIG_DFL);
328 raise(sig);
331 void sighup(int sig)
333 hup=1;
336 void dosighup(int sig)
338 #ifndef USE_SYSLOG
339 struct stat s;
340 #endif
341 int i;
343 /* reopen logfile first */
344 #ifdef USE_SYSLOG
345 /* we don't need to do anyting as this is syslogd's task */
346 #else
347 logprintf(LOG_INFO,"closing logfile");
348 if(-1==fstat(fileno(lf),&s))
350 dosigterm(SIGTERM); /* shouldn't ever happen */
352 fclose(lf);
353 lf=fopen(logfile,"a");
354 if(lf==NULL)
356 /* can't print any error messagees */
357 dosigterm(SIGTERM);
359 logprintf(LOG_INFO,"reopened logfile");
360 if(-1==fchmod(fileno(lf),s.st_mode))
362 logprintf(LOG_WARNING,"could not set file permissions");
363 logperror(LOG_WARNING,NULL);
365 #endif
367 config();
369 for (i=0; i<clin; i++)
371 if(!(write_socket_len(clis[i],protocol_string[P_BEGIN]) &&
372 write_socket_len(clis[i],protocol_string[P_SIGHUP]) &&
373 write_socket_len(clis[i],protocol_string[P_END])))
375 remove_client(clis[i]);
376 i--;
379 /* restart all connection timers */
380 for (i=0; i<peern; i++)
382 if (peers[i]->socket == -1)
384 gettimeofday(&peers[i]->reconnect, NULL);
385 peers[i]->connection_failure = 0;
390 void config(void)
392 FILE *fd;
393 struct ir_remote *config_remotes;
395 if(free_remotes!=NULL)
397 logprintf(LOG_ERR,"cannot read config file");
398 logprintf(LOG_ERR,"old config is still in use");
399 return;
401 fd=fopen(configfile,"r");
402 if(fd==NULL)
404 logprintf(LOG_ERR,"could not open config file '%s'",
405 configfile);
406 logperror(LOG_ERR,NULL);
407 return;
409 config_remotes=read_config(fd, configfile);
410 fclose(fd);
411 if(config_remotes==(void *) -1)
413 logprintf(LOG_ERR,"reading of config file failed");
415 else
417 LOGPRINTF(1,"config file read");
418 if(config_remotes==NULL)
420 logprintf(LOG_WARNING,"config file contains no "
421 "valid remote control definition");
423 /* I cannot free the data structure
424 as they could still be in use */
425 free_remotes=remotes;
426 remotes=config_remotes;
427 if(hw.config_func) (void) hw.config_func(remotes);
431 void nolinger(int sock)
433 static struct linger linger = {0, 0};
434 int lsize = sizeof(struct linger);
435 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, lsize);
438 void remove_client(int fd)
440 int i;
442 for(i=0;i<clin;i++)
444 if(clis[i]==fd)
446 shutdown(clis[i],2);
447 close(clis[i]);
448 logprintf(LOG_INFO,"removed client");
450 clin--;
451 if(clin==0 &&
452 repeat_remote==NULL &&
453 hw.deinit_func)
455 hw.deinit_func();
457 for(;i<clin;i++)
459 clis[i]=clis[i+1];
461 return;
464 LOGPRINTF(1,"internal error in remove_client: no such fd");
467 void add_client(int sock)
469 int fd;
470 socklen_t clilen;
471 struct sockaddr client_addr;
472 int flags;
474 clilen=sizeof(client_addr);
475 fd=accept(sock,(struct sockaddr *)&client_addr,&clilen);
476 if(fd==-1)
478 logprintf(LOG_ERR,"accept() failed for new client");
479 logperror(LOG_ERR,NULL);
480 dosigterm(SIGTERM);
483 if(fd>=FD_SETSIZE || clin>=MAX_CLIENTS)
485 logprintf(LOG_ERR,"connection rejected");
486 shutdown(fd,2);
487 close(fd);
488 return;
490 nolinger(fd);
491 flags=fcntl(fd,F_GETFL,0);
492 if(flags!=-1)
494 fcntl(fd,F_SETFL,flags|O_NONBLOCK);
496 if(client_addr.sa_family==AF_UNIX)
498 cli_type[clin]=CT_LOCAL;
499 logprintf(LOG_NOTICE,"accepted new client on %s",lircdfile);
501 else if(client_addr.sa_family==AF_INET)
503 cli_type[clin]=CT_REMOTE;
504 logprintf(LOG_NOTICE,"accepted new client from %s",
505 inet_ntoa(((struct sockaddr_in *)&client_addr)->sin_addr));
507 else
509 cli_type[clin]=0; /* what? */
511 clis[clin++]=fd;
512 if(clin==1 && repeat_remote==NULL)
514 if(hw.init_func)
516 if(!hw.init_func())
518 logprintf(LOG_WARNING,
519 "Failed to initialize hardware");
520 /* Don't exit here, otherwise lirc
521 * bails out, and lircd exits, making
522 * it impossible to connect to when we
523 * have a device actually plugged
524 * in. */
530 int add_peer_connection(char *server)
532 char *sep;
533 struct servent *service;
535 if(peern<MAX_PEERS)
537 peers[peern]=malloc(sizeof(struct peer_connection));
538 if(peers[peern]!=NULL)
540 gettimeofday(&peers[peern]->reconnect,NULL);
541 peers[peern]->connection_failure = 0;
542 sep=strchr(server,':');
543 if(sep!=NULL)
545 *sep=0;sep++;
546 peers[peern]->host=strdup(server);
547 service=getservbyname(sep,"tcp");
548 if(service)
550 peers[peern]->port=
551 ntohs(service->s_port);
553 else
555 long p;
556 char *endptr;
558 p=strtol(sep,&endptr,10);
559 if(!*sep || *endptr ||
560 p<1 || p>USHRT_MAX)
562 fprintf(stderr,
563 "%s: bad port number \"%s\"\n",
564 progname,sep);
565 return(0);
568 peers[peern]->port=
569 (unsigned short int) p;
572 else
574 peers[peern]->host=strdup(server);
575 peers[peern]->port=LIRC_INET_PORT;
577 if(peers[peern]->host==NULL)
579 fprintf(stderr, "%s: out of memory\n",progname);
582 else
584 fprintf(stderr, "%s: out of memory\n",progname);
585 return(0);
587 peers[peern]->socket=-1;
588 peern++;
589 return(1);
591 else
593 fprintf(stderr,"%s: too many client connections\n",
594 progname);
596 return(0);
599 void connect_to_peers()
601 int i;
602 struct hostent *host;
603 struct sockaddr_in addr;
604 struct timeval now;
605 int enable=1;
607 gettimeofday(&now,NULL);
608 for(i=0;i<peern;i++)
610 if(peers[i]->socket!=-1)
611 continue;
612 /* some timercmp() definitions don't work with <= */
613 if(timercmp(&peers[i]->reconnect,&now,<))
615 peers[i]->socket=socket(AF_INET, SOCK_STREAM,0);
616 host=gethostbyname(peers[i]->host);
617 if(host==NULL)
619 logprintf(LOG_ERR,"name lookup failure "
620 "connecting to %s",peers[i]->host);
621 peers[i]->connection_failure++;
622 gettimeofday(&peers[i]->reconnect,NULL);
623 peers[i]->reconnect.tv_sec+=
624 5*peers[i]->connection_failure;
625 close(peers[i]->socket);
626 peers[i]->socket=-1;
627 continue;
630 (void) setsockopt(peers[i]->socket,SOL_SOCKET,
631 SO_KEEPALIVE,&enable,sizeof(enable));
633 addr.sin_family=host->h_addrtype;;
634 addr.sin_addr=*((struct in_addr *)host->h_addr);
635 addr.sin_port=htons(peers[i]->port);
636 if(connect(peers[i]->socket,(struct sockaddr *) &addr,
637 sizeof(addr))==-1)
639 logprintf(LOG_ERR, "failure connecting to %s",
640 peers[i]->host);
641 logperror(LOG_ERR, NULL);
642 peers[i]->connection_failure++;
643 gettimeofday(&peers[i]->reconnect,NULL);
644 peers[i]->reconnect.tv_sec+=
645 5*peers[i]->connection_failure;
646 close(peers[i]->socket);
647 peers[i]->socket=-1;
648 continue;
650 logprintf(LOG_NOTICE, "connected to %s",
651 peers[i]->host);
652 peers[i]->connection_failure=0;
657 int get_peer_message(struct peer_connection *peer)
659 int length;
660 char buffer[PACKET_SIZE+1];
661 char *end;
662 int i;
664 length=read_timeout(peer->socket,buffer,PACKET_SIZE,0);
665 if(length)
667 buffer[length]=0;
668 end=strchr(buffer,'\n');
669 if(end==NULL)
671 logprintf(LOG_ERR,"bad send packet: \"%s\"",buffer);
672 /* remove clients that behave badly */
673 return(0);
675 end++; /* include the \n */
676 end[0]=0;
677 LOGPRINTF(1,"received peer message: \"%s\"",buffer);
678 for(i=0;i<clin;i++)
680 /* don't relay messages to remote clients */
681 if(cli_type[i]==CT_REMOTE)
682 continue;
683 LOGPRINTF(1,"writing to client %d",i);
684 if(write_socket(clis[i],buffer,length)<length)
686 remove_client(clis[i]);
687 i--;
692 if(length==0) /* EOF: connection closed by client */
694 return(0);
696 return(1);
699 void start_server(mode_t permission,int nodaemon)
701 struct sockaddr_un serv_addr;
702 struct sockaddr_in serv_addr_in;
703 struct stat s;
704 int ret;
705 int new=1;
706 int fd;
708 /* create pid lockfile in /var/run */
709 if((fd=open(pidfile,O_RDWR|O_CREAT,0644))==-1 ||
710 (pidf=fdopen(fd,"r+"))==NULL)
712 fprintf(stderr,"%s: can't open or create %s\n",
713 progname,pidfile);
714 perror(progname);
715 exit(EXIT_FAILURE);
717 if(flock(fd,LOCK_EX|LOCK_NB)==-1)
719 pid_t otherpid;
721 if(fscanf(pidf,"%d\n",&otherpid)>0)
723 fprintf(stderr,"%s: there seems to already be "
724 "a lircd process with pid %d\n",
725 progname,otherpid);
726 fprintf(stderr,"%s: otherwise delete stale "
727 "lockfile %s\n",progname,pidfile);
729 else
731 fprintf(stderr,"%s: invalid %s encountered\n",
732 progname,pidfile);
734 exit(EXIT_FAILURE);
736 (void) fcntl(fd,F_SETFD,FD_CLOEXEC);
737 rewind(pidf);
738 (void) fprintf(pidf,"%d\n",getpid());
739 (void) fflush(pidf);
740 (void) ftruncate(fileno(pidf),ftell(pidf));
742 /* create socket*/
743 sockfd=socket(AF_UNIX,SOCK_STREAM,0);
744 if(sockfd==-1)
746 fprintf(stderr,"%s: could not create socket\n",progname);
747 perror(progname);
748 goto start_server_failed0;
752 get owner, permissions, etc.
753 so new socket can be the same since we
754 have to delete the old socket.
756 ret=stat(lircdfile,&s);
757 if(ret==-1 && errno!=ENOENT)
759 fprintf(stderr,"%s: could not get file information for %s\n",
760 progname,lircdfile);
761 perror(progname);
762 goto start_server_failed1;
764 if(ret!=-1)
766 new=0;
767 ret=unlink(lircdfile);
768 if(ret==-1)
770 fprintf(stderr,"%s: could not delete %s\n",
771 progname,lircdfile);
772 perror(NULL);
773 goto start_server_failed1;
777 serv_addr.sun_family=AF_UNIX;
778 strcpy(serv_addr.sun_path,lircdfile);
779 if(bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))==-1)
781 fprintf(stderr,"%s: could not assign address to socket\n",
782 progname);
783 perror(progname);
784 goto start_server_failed1;
787 if(new ?
788 chmod(lircdfile,permission):
789 (chmod(lircdfile,s.st_mode)==-1 ||
790 chown(lircdfile,s.st_uid,s.st_gid)==-1)
793 fprintf(stderr,"%s: could not set file permissions\n",
794 progname);
795 perror(progname);
796 goto start_server_failed1;
799 listen(sockfd,3);
800 nolinger(sockfd);
802 if(listen_tcpip)
804 int enable=1;
806 /* create socket*/
807 sockinet=socket(PF_INET,SOCK_STREAM,IPPROTO_IP);
808 if(sockinet==-1)
810 fprintf(stderr,"%s: could not create TCP/IP socket\n",
811 progname);
812 perror(progname);
813 goto start_server_failed1;
815 (void) setsockopt(sockinet,SOL_SOCKET,SO_REUSEADDR,
816 &enable,sizeof(enable));
817 serv_addr_in.sin_family=AF_INET;
818 serv_addr_in.sin_addr.s_addr=htonl(INADDR_ANY);
819 serv_addr_in.sin_port=htons(port);
821 if(bind(sockinet,(struct sockaddr *) &serv_addr_in,
822 sizeof(serv_addr_in))==-1)
824 fprintf(stderr,
825 "%s: could not assign address to socket\n",
826 progname);
827 perror(progname);
828 goto start_server_failed2;
831 listen(sockinet,3);
832 nolinger(sockinet);
835 #ifdef USE_SYSLOG
836 #ifdef DAEMONIZE
837 if(nodaemon)
839 openlog(syslogident,LOG_CONS|LOG_PID|LOG_PERROR,LIRC_SYSLOG);
841 else
843 openlog(syslogident,LOG_CONS|LOG_PID,LIRC_SYSLOG);
845 #else
846 openlog(syslogident,LOG_CONS|LOG_PID|LOG_PERROR,LIRC_SYSLOG);
847 #endif
848 #else
849 lf=fopen(logfile,"a");
850 if(lf==NULL)
852 fprintf(stderr,"%s: could not open logfile\n",progname);
853 perror(progname);
854 goto start_server_failed2;
856 gethostname(hostname,HOSTNAME_LEN);
857 #endif
858 LOGPRINTF(1,"started server socket");
859 return;
861 start_server_failed2:
862 if(listen_tcpip)
864 close(sockinet);
866 start_server_failed1:
867 close(sockfd);
868 start_server_failed0:
869 fclose(pidf);
870 (void) unlink(pidfile);
871 exit(EXIT_FAILURE);
874 void log_enable(int enabled)
876 log_enabled = enabled;
879 #ifdef USE_SYSLOG
880 void logprintf(int prio,char *format_str, ...)
882 int save_errno = errno;
883 va_list ap;
885 if(!log_enabled) return;
887 va_start(ap,format_str);
888 vsyslog(prio, format_str, ap);
889 va_end(ap);
891 errno = save_errno;
894 void logperror(int prio,const char *s)
896 if(!log_enabled) return;
898 if((s)!=NULL) syslog(prio,"%s: %m\n",(char *) s);
899 else syslog(prio,"%m\n");
901 #else
902 void logprintf(int prio,char *format_str, ...)
904 int save_errno = errno;
905 va_list ap;
907 if(!log_enabled) return;
909 if(lf)
911 time_t current;
912 char *currents;
914 current=time(&current);
915 currents=ctime(&current);
917 fprintf(lf,"%15.15s %s %s: ",currents+4,hostname,progname);
918 va_start(ap,format_str);
919 if(prio==LOG_WARNING) fprintf(lf,"WARNING: ");
920 vfprintf(lf,format_str,ap);
921 fputc('\n',lf);fflush(lf);
922 va_end(ap);
924 if(!daemonized)
926 fprintf(stderr,"%s: ",progname);
927 va_start(ap,format_str);
928 if(prio==LOG_WARNING) fprintf(stderr,"WARNING: ");
929 vfprintf(stderr,format_str,ap);
930 fputc('\n',stderr);fflush(stderr);
931 va_end(ap);
933 errno = save_errno;
936 void logperror(int prio,const char *s)
938 if(!log_enabled) return;
940 if(s!=NULL)
942 logprintf(prio,"%s: %s",s,strerror(errno));
944 else
946 logprintf(prio,"%s",strerror(errno));
949 #endif
951 #ifdef DAEMONIZE
953 void daemonize(void)
955 if(daemon(0,0)==-1)
957 logprintf(LOG_ERR,"daemon() failed");
958 logperror(LOG_ERR,NULL);
959 dosigterm(SIGTERM);
961 umask(0);
962 rewind(pidf);
963 (void) fprintf(pidf,"%d\n",getpid());
964 (void) fflush(pidf);
965 (void) ftruncate(fileno(pidf),ftell(pidf));
966 daemonized=1;
969 #endif /* DAEMONIZE */
971 void sigalrm(int sig)
973 alrm=1;
976 void dosigalrm(int sig)
978 struct itimerval repeat_timer;
980 if(repeat_remote->last_code!=repeat_code)
982 /* we received a different code from the original
983 remote control we could repeat the wrong code so
984 better stop repeating */
985 if(repeat_fd != -1)
987 send_error(repeat_fd, repeat_message, "repeating interrupted\n");
990 repeat_remote=NULL;
991 repeat_code=NULL;
992 repeat_fd=-1;
993 if(repeat_message!=NULL)
995 free(repeat_message);
996 repeat_message=NULL;
998 if(clin==0 && repeat_remote==NULL && hw.deinit_func)
1000 hw.deinit_func();
1002 return;
1004 if(repeat_code->next == NULL || (repeat_code->transmit_state != NULL && repeat_code->transmit_state->next == NULL))
1006 repeat_remote->repeat_countdown--;
1008 if(send_ir_ncode(repeat_remote,repeat_code) &&
1009 repeat_remote->repeat_countdown>0)
1011 repeat_timer.it_value.tv_sec=0;
1012 repeat_timer.it_value.tv_usec=repeat_remote->min_remaining_gap;
1013 repeat_timer.it_interval.tv_sec=0;
1014 repeat_timer.it_interval.tv_usec=0;
1016 setitimer(ITIMER_REAL,&repeat_timer,NULL);
1017 return;
1019 repeat_remote=NULL;
1020 repeat_code=NULL;
1021 if(repeat_fd!=-1)
1023 send_success(repeat_fd,repeat_message);
1024 free(repeat_message);
1025 repeat_message=NULL;
1026 repeat_fd=-1;
1028 if(clin==0 && repeat_remote==NULL && hw.deinit_func)
1030 hw.deinit_func();
1034 int parse_rc(int fd,char *message,char *arguments,struct ir_remote **remote,
1035 struct ir_ncode **code,int *reps,int n)
1037 char *name=NULL,*command=NULL,*repeats,*end_ptr=NULL;
1039 *remote=NULL;
1040 *code=NULL;
1041 if(arguments==NULL) return(1);
1043 name=strtok(arguments,WHITE_SPACE);
1044 if(name==NULL) return(1);
1045 *remote=get_ir_remote(remotes,name);
1046 if(*remote==NULL)
1048 return(send_error(fd,message,"unknown remote: \"%s\"\n",
1049 name));
1051 command=strtok(NULL,WHITE_SPACE);
1052 if(command==NULL) return(1);
1053 *code=get_code_by_name(*remote,command);
1054 if(*code==NULL)
1056 return(send_error(fd,message,"unknown command: \"%s\"\n",
1057 command));
1059 if(reps!=NULL)
1061 repeats=strtok(NULL,WHITE_SPACE);
1062 if (repeats!=NULL)
1064 *reps=strtol(repeats,&end_ptr,10);
1065 if (*end_ptr || *reps<0 )
1067 return(send_error(fd,message,
1068 "bad send packet\n"));
1070 if (*reps>REPEAT_MAX)
1072 return(send_error
1073 (fd,message,
1074 "too many repeats: \"%d\"\n",*reps));
1077 else
1079 *reps=-1;
1082 if(strtok(NULL,WHITE_SPACE)!=NULL)
1084 return(send_error(fd,message,"bad send packet\n"));
1086 if(n>0 && *remote==NULL)
1088 return(send_error(fd,message,"remote missing\n"));
1090 if(n>1 && *code==NULL)
1092 return(send_error(fd,message,"code missing\n"));
1094 return(1);
1097 int send_success(int fd,char *message)
1099 if(!(write_socket_len(fd,protocol_string[P_BEGIN]) &&
1100 write_socket_len(fd,message) &&
1101 write_socket_len(fd,protocol_string[P_SUCCESS]) &&
1102 write_socket_len(fd,protocol_string[P_END]))) return(0);
1103 return(1);
1106 int send_error(int fd,char *message,char *format_str, ...)
1108 char lines[4],buffer[PACKET_SIZE+1];
1109 int i,n,len;
1110 va_list ap;
1111 char *s1,*s2;
1113 va_start(ap,format_str);
1114 vsprintf(buffer,format_str,ap);
1115 va_end(ap);
1117 s1=strrchr(message,'\n');
1118 s2=strrchr(buffer,'\n');
1119 if(s1!=NULL) s1[0]=0;
1120 if(s2!=NULL) s2[0]=0;
1121 logprintf(LOG_ERR,"error processing command: %s",message);
1122 logprintf(LOG_ERR,"%s",buffer);
1123 if(s1!=NULL) s1[0]='\n';
1124 if(s2!=NULL) s2[0]='\n';
1126 n=0;
1127 len=strlen(buffer);
1128 for(i=0;i<len;i++) if(buffer[i]=='\n') n++;
1129 sprintf(lines,"%d\n",n);
1131 if(!(write_socket_len(fd,protocol_string[P_BEGIN]) &&
1132 write_socket_len(fd,message) &&
1133 write_socket_len(fd,protocol_string[P_ERROR]) &&
1134 write_socket_len(fd,protocol_string[P_DATA]) &&
1135 write_socket_len(fd,lines) &&
1136 write_socket_len(fd,buffer) &&
1137 write_socket_len(fd,protocol_string[P_END]))) return(0);
1138 return(1);
1141 int send_remote_list(int fd,char *message)
1143 char buffer[PACKET_SIZE+1];
1144 struct ir_remote *all;
1145 int n,len;
1147 n=0;
1148 all=remotes;
1149 while(all)
1151 n++;
1152 all=all->next;
1155 if(!(write_socket_len(fd,protocol_string[P_BEGIN]) &&
1156 write_socket_len(fd,message) &&
1157 write_socket_len(fd,protocol_string[P_SUCCESS]))) return(0);
1159 if(n==0)
1161 return(write_socket_len(fd,protocol_string[P_END]));
1163 sprintf(buffer,"%d\n",n);
1164 len=strlen(buffer);
1165 if(!(write_socket_len(fd,protocol_string[P_DATA]) &&
1166 write_socket_len(fd,buffer))) return(0);
1168 all=remotes;
1169 while(all)
1171 len=snprintf(buffer,PACKET_SIZE+1,"%s\n",all->name);
1172 if(len>=PACKET_SIZE+1)
1174 len=sprintf(buffer,"name_too_long\n");
1176 if(write_socket(fd,buffer,len)<len) return(0);
1177 all=all->next;
1179 return(write_socket_len(fd,protocol_string[P_END]));
1182 int send_remote(int fd,char *message,struct ir_remote *remote)
1184 struct ir_ncode *codes;
1185 char buffer[PACKET_SIZE+1];
1186 int n,len;
1188 n=0;
1189 codes=remote->codes;
1190 if(codes!=NULL)
1192 while(codes->name!=NULL)
1194 n++;
1195 codes++;
1199 if(!(write_socket_len(fd,protocol_string[P_BEGIN]) &&
1200 write_socket_len(fd,message) &&
1201 write_socket_len(fd,protocol_string[P_SUCCESS]))) return(0);
1202 if(n==0)
1204 return(write_socket_len(fd,protocol_string[P_END]));
1206 sprintf(buffer,"%d\n",n);
1207 if(!(write_socket_len(fd,protocol_string[P_DATA]) &&
1208 write_socket_len(fd,buffer))) return(0);
1210 codes=remote->codes;
1211 while(codes->name!=NULL)
1213 #ifdef __GLIBC__
1214 /* It seems you can't print 64-bit longs on glibc */
1216 len=snprintf(buffer,PACKET_SIZE+1,"%08lx%08lx %s\n",
1217 (unsigned long) (codes->code>>32),
1218 (unsigned long) (codes->code&0xFFFFFFFF),
1219 codes->name);
1220 #else
1221 len=snprintf(buffer,PACKET_SIZE,"%016llx %s\n",
1222 codes->code,
1223 codes->name);
1224 #endif
1225 if(len>=PACKET_SIZE+1)
1227 len=sprintf(buffer,"code_too_long\n");
1229 if(write_socket(fd,buffer,len)<len) return(0);
1230 codes++;
1232 return(write_socket_len(fd,protocol_string[P_END]));
1235 int send_name(int fd,char *message,struct ir_ncode *code)
1237 char buffer[PACKET_SIZE+1];
1238 int len;
1240 if(!(write_socket_len(fd,protocol_string[P_BEGIN]) &&
1241 write_socket_len(fd,message) &&
1242 write_socket_len(fd,protocol_string[P_SUCCESS]) &&
1243 write_socket_len(fd,protocol_string[P_DATA]))) return(0);
1244 #ifdef __GLIBC__
1245 /* It seems you can't print 64-bit longs on glibc */
1247 len=snprintf(buffer,PACKET_SIZE+1,"1\n%08lx%08lx %s\n",
1248 (unsigned long) (code->code>>32),
1249 (unsigned long) (code->code&0xFFFFFFFF),
1250 code->name);
1251 #else
1252 len=snprintf(buffer,PACKET_SIZE,"1\n%016llx %s\n",
1253 code->code,
1254 code->name);
1255 #endif
1256 if(len>=PACKET_SIZE+1)
1258 len=sprintf(buffer,"1\ncode_too_long\n");
1260 if(write_socket(fd,buffer,len)<len) return(0);
1261 return(write_socket_len(fd,protocol_string[P_END]));
1264 int list(int fd,char *message,char *arguments)
1266 struct ir_remote *remote;
1267 struct ir_ncode *code;
1269 if(parse_rc(fd,message,arguments,&remote,&code,NULL,0)==0) return(0);
1271 if(remote==NULL)
1273 return(send_remote_list(fd,message));
1275 if(code==NULL)
1277 return(send_remote(fd,message,remote));
1279 return(send_name(fd,message,code));
1282 int set_transmitters(int fd,char *message,char *arguments)
1284 char *next_arg=NULL,*end_ptr;
1285 unsigned long next_tx_int;
1286 unsigned long next_tx_hex;
1287 unsigned int channels=0;
1288 int retval=0;
1289 int i;
1291 if(arguments==NULL) goto string_error;
1292 if(hw.send_mode==0) return(send_error(fd,message,"hardware does not "
1293 "support sending\n"));
1294 if(hw.ioctl_func == NULL ||
1295 !(hw.features & LIRC_CAN_SET_TRANSMITTER_MASK))
1297 return(send_error(fd,message,"hardware does not support "
1298 "multiple transmitters\n"));
1301 next_arg=strtok(arguments,WHITE_SPACE);
1302 if (next_arg==NULL) goto string_error;
1305 next_tx_int=-1;
1306 next_tx_int = strtoul(next_arg,&end_ptr,10);
1307 if(*end_ptr || next_tx_int == 0 || (next_tx_int == ULONG_MAX && errno == ERANGE))
1309 return(send_error(fd,message, "invalid argument\n"));
1311 if(next_tx_int > MAX_TX)
1313 return(send_error(fd, message, "cannot support more "
1314 "than %d transmitters\n", MAX_TX));
1316 next_tx_hex=1;
1317 for(i=1; i<next_tx_int; i++) next_tx_hex = next_tx_hex << 1;
1318 channels |= next_tx_hex;
1319 }while ((next_arg=strtok(NULL,WHITE_SPACE))!=NULL);
1321 retval = hw.ioctl_func(LIRC_SET_TRANSMITTER_MASK, &channels);
1322 if(retval<0)
1324 return(send_error(fd, message, "error - could not set "
1325 "transmitters\n"));
1327 if (retval>0)
1329 return(send_error(fd, message, "error - maximum of %d "
1330 "transmitters\n", retval));
1332 return(send_success(fd,message));
1334 string_error:
1335 return(send_error(fd,message,"no arguments given\n"));
1338 int simulate(int fd,char *message,char *arguments)
1340 int i;
1341 char *sim, *s, *space;
1343 if(!allow_simulate)
1345 return send_error(fd, message,
1346 "SIMULATE command is disabled\n");
1348 if(arguments==NULL)
1350 return send_error(fd, message, "no arguments given\n");
1353 s=arguments;
1354 for(i=0; i<16; i++, s++)
1356 if(!isxdigit(*s)) goto simulate_invalid_event;
1358 if(*s != ' ')
1360 goto simulate_invalid_event;
1362 s++;
1363 if(*s == ' ')
1365 goto simulate_invalid_event;
1367 for(; *s != ' '; s++)
1369 if(!isxdigit(*s)) goto simulate_invalid_event;
1371 s++;
1372 space = strchr(s, ' ');
1373 if(space == NULL || space == s)
1375 goto simulate_invalid_event;
1377 s = space + 1;
1378 space = strchr(s, ' ');
1379 if(strlen(s) == 0 || space != NULL)
1381 goto simulate_invalid_event;
1384 sim = malloc(strlen(arguments) + 1 + 1);
1385 if(sim == NULL)
1387 return send_error(fd, message, "out of memory\n");
1389 strcpy(sim, arguments);
1390 strcat(sim, "\n");
1391 broadcast_message(sim);
1392 free(sim);
1394 return(send_success(fd,message));
1395 simulate_invalid_event:
1396 return send_error(fd, message, "invalid event\n");
1400 int send_once(int fd,char *message,char *arguments)
1402 return(send_core(fd,message,arguments,1));
1405 int send_start(int fd,char *message,char *arguments)
1407 return(send_core(fd,message,arguments,0));
1410 int send_core(int fd,char *message,char *arguments,int once)
1412 struct ir_remote *remote;
1413 struct ir_ncode *code;
1414 struct itimerval repeat_timer;
1415 int reps;
1417 if(hw.send_mode==0) return(send_error(fd,message,"hardware does not "
1418 "support sending\n"));
1420 if(parse_rc(fd,message,arguments,&remote,&code,
1421 once ? &reps:NULL,2)==0) return(0);
1423 if(remote==NULL || code==NULL) return(1);
1424 if(once)
1426 if(repeat_remote!=NULL)
1428 return(send_error(fd,message,"busy: repeating\n"));
1431 else
1433 if(repeat_remote!=NULL)
1435 return(send_error(fd,message,"already repeating\n"));
1438 if(has_toggle_mask(remote))
1440 remote->toggle_mask_state=0;
1442 if(has_toggle_bit_mask(remote))
1444 remote->toggle_bit_mask_state =
1445 (remote->toggle_bit_mask_state^remote->toggle_bit_mask);
1447 code->transmit_state = NULL;
1448 if(!send_ir_ncode(remote,code))
1450 return(send_error(fd,message,"transmission failed\n"));
1452 gettimeofday(&remote->last_send,NULL);
1453 remote->last_code = code;
1454 if(once)
1456 remote->repeat_countdown=max(remote->repeat_countdown,reps);
1458 else
1460 /* you've been warned, now we have a limit */
1461 remote->repeat_countdown=REPEAT_MAX;
1463 if(remote->repeat_countdown>0 || code->next != NULL)
1465 repeat_remote=remote;
1466 repeat_code=code;
1467 repeat_timer.it_value.tv_sec=0;
1468 repeat_timer.it_value.tv_usec=
1469 remote->min_remaining_gap;
1470 repeat_timer.it_interval.tv_sec=0;
1471 repeat_timer.it_interval.tv_usec=0;
1472 if(once)
1474 repeat_message=strdup(message);
1475 if(repeat_message==NULL)
1477 repeat_remote=NULL;
1478 repeat_code=NULL;
1479 return(send_error(fd,message,
1480 "out of memory\n"));
1482 repeat_fd=fd;
1484 else if(!send_success(fd,message))
1486 repeat_remote=NULL;
1487 repeat_code=NULL;
1488 return(0);
1490 setitimer(ITIMER_REAL,&repeat_timer,NULL);
1491 return(1);
1493 else
1495 return(send_success(fd,message));
1499 int send_stop(int fd,char *message,char *arguments)
1501 struct ir_remote *remote;
1502 struct ir_ncode *code;
1503 struct itimerval repeat_timer;
1505 if(parse_rc(fd,message,arguments,&remote,&code,NULL,2)==0) return(0);
1507 if(remote==NULL || code==NULL) return(1);
1508 if(repeat_remote && repeat_code &&
1509 strcasecmp(remote->name,repeat_remote->name)==0 &&
1510 strcasecmp(code->name,repeat_code->name)==0)
1512 int done;
1514 done=REPEAT_MAX-remote->repeat_countdown;
1515 if(done<remote->min_repeat)
1517 /* we still have some repeats to do */
1518 remote->repeat_countdown=remote->min_repeat-done;
1519 return(send_success(fd,message));
1521 repeat_timer.it_value.tv_sec=0;
1522 repeat_timer.it_value.tv_usec=0;
1523 repeat_timer.it_interval.tv_sec=0;
1524 repeat_timer.it_interval.tv_usec=0;
1526 setitimer(ITIMER_REAL,&repeat_timer,NULL);
1528 repeat_remote->toggle_mask_state=0;
1529 repeat_remote=NULL;
1530 repeat_code=NULL;
1531 /* clin!=0, so we don't have to deinit hardware */
1532 alrm=0;
1533 return(send_success(fd,message));
1535 else
1537 return(send_error(fd,message,"not repeating\n"));
1541 int version(int fd,char *message,char *arguments)
1543 char buffer[PACKET_SIZE+1];
1545 if(arguments!=NULL)
1547 return(send_error(fd,message,"bad send packet\n"));
1549 sprintf(buffer,"1\n%s\n",VERSION);
1550 if(!(write_socket_len(fd,protocol_string[P_BEGIN]) &&
1551 write_socket_len(fd,message) &&
1552 write_socket_len(fd,protocol_string[P_SUCCESS]) &&
1553 write_socket_len(fd,protocol_string[P_DATA]) &&
1554 write_socket_len(fd,buffer) &&
1555 write_socket_len(fd,protocol_string[P_END]))) return(0);
1556 return(1);
1559 int get_command(int fd)
1561 int length;
1562 char buffer[PACKET_SIZE+1],backup[PACKET_SIZE+1];
1563 char *end;
1564 int packet_length,i;
1565 char *directive;
1567 length=read_timeout(fd,buffer,PACKET_SIZE,0);
1568 packet_length=0;
1569 while(length>packet_length)
1571 buffer[length]=0;
1572 end=strchr(buffer,'\n');
1573 if(end==NULL)
1575 logprintf(LOG_ERR,"bad send packet: \"%s\"",buffer);
1576 /* remove clients that behave badly */
1577 return(0);
1579 end[0]=0;
1580 LOGPRINTF(1,"received command: \"%s\"",buffer);
1581 packet_length=strlen(buffer)+1;
1583 strcpy(backup,buffer);strcat(backup,"\n");
1584 directive=strtok(buffer,WHITE_SPACE);
1585 if(directive==NULL)
1587 if(!send_error(fd,backup,"bad send packet\n"))
1588 return(0);
1589 goto skip;
1591 for(i=0;directives[i].name!=NULL;i++)
1593 if(strcasecmp(directive,directives[i].name)==0)
1595 if(!directives[i].
1596 function(fd,backup,strtok(NULL,"")))
1597 return(0);
1598 goto skip;
1602 if(!send_error(fd,backup,"unknown directive: \"%s\"\n",
1603 directive))
1604 return(0);
1605 skip:
1606 if(length>packet_length)
1608 int new_length;
1610 memmove(buffer,buffer+packet_length,
1611 length-packet_length+1);
1612 if(strchr(buffer,'\n')==NULL)
1614 new_length=read_timeout(fd,buffer+length-
1615 packet_length,
1616 PACKET_SIZE-
1617 (length-
1618 packet_length),5);
1619 if(new_length>0)
1621 length=length-packet_length+new_length;
1623 else
1625 length=new_length;
1628 else
1630 length-=packet_length;
1632 packet_length=0;
1636 if(length==0) /* EOF: connection closed by client */
1638 return(0);
1640 return(1);
1643 void free_old_remotes()
1645 struct ir_remote *scan_remotes,*found;
1646 struct ir_ncode *code;
1647 const char *release_event;
1649 if(decoding ==free_remotes) return;
1651 release_event = release_map_remotes(free_remotes, remotes);
1652 if(release_event != NULL)
1654 broadcast_message(release_event);
1656 if(last_remote!=NULL)
1658 if(is_in_remotes(free_remotes, last_remote))
1660 logprintf(LOG_INFO, "last_remote found");
1661 found=get_ir_remote(remotes,last_remote->name);
1662 if(found!=NULL)
1664 code=get_code_by_name(found,last_remote->last_code->name);
1665 if(code!=NULL)
1667 found->reps=last_remote->reps;
1668 found->toggle_bit_mask_state=last_remote->toggle_bit_mask_state;
1669 found->min_remaining_gap=last_remote->min_remaining_gap;
1670 found->max_remaining_gap=last_remote->max_remaining_gap;
1671 found->last_send=last_remote->last_send;
1672 last_remote=found;
1673 last_remote->last_code=code;
1674 logprintf(LOG_INFO, "mapped last_remote");
1678 else
1680 last_remote=NULL;
1683 /* check if last config is still needed */
1684 found=NULL;
1685 if(repeat_remote!=NULL)
1687 scan_remotes=free_remotes;
1688 while(scan_remotes!=NULL)
1690 if(repeat_remote==scan_remotes)
1692 found=repeat_remote;
1693 break;
1695 scan_remotes=scan_remotes->next;
1697 if(found!=NULL)
1699 found=get_ir_remote(remotes,repeat_remote->name);
1700 if(found!=NULL)
1702 code=get_code_by_name(found,repeat_code->name);
1703 if(code!=NULL)
1705 struct itimerval repeat_timer;
1707 repeat_timer.it_value.tv_sec=0;
1708 repeat_timer.it_value.tv_usec=0;
1709 repeat_timer.it_interval.tv_sec=0;
1710 repeat_timer.it_interval.tv_usec=0;
1712 found->last_code=code;
1713 found->last_send=repeat_remote->last_send;
1714 found->toggle_bit_mask_state=repeat_remote->toggle_bit_mask_state;
1715 found->min_remaining_gap=repeat_remote->min_remaining_gap;
1716 found->max_remaining_gap=repeat_remote->max_remaining_gap;
1718 setitimer(ITIMER_REAL,&repeat_timer,&repeat_timer);
1719 /* "atomic" (shouldn't be necessary any more) */
1720 repeat_remote=found;
1721 repeat_code=code;
1722 /* end "atomic" */
1723 setitimer(ITIMER_REAL,&repeat_timer,NULL);
1724 found=NULL;
1727 else
1729 found=repeat_remote;
1733 if(found==NULL && decoding!=free_remotes)
1735 free_config(free_remotes);
1736 free_remotes=NULL;
1738 else
1740 LOGPRINTF(1,"free_remotes still in use");
1744 void broadcast_message(const char *message)
1746 int len,i;
1747 const char *release_message;
1749 release_message = check_release_event();
1750 if(release_message)
1752 broadcast_message(release_message);
1755 len=strlen(message);
1757 for (i=0; i<clin; i++)
1759 LOGPRINTF(1,"writing to client %d",i);
1760 if(write_socket(clis[i],message,len)<len)
1762 remove_client(clis[i]);
1763 i--;
1768 int waitfordata(long maxusec)
1770 fd_set fds;
1771 int maxfd,i,ret,reconnect;
1772 struct timeval tv,start,now,timeout,release_time;
1774 while(1)
1777 /* handle signals */
1778 if(term)
1780 dosigterm(termsig);
1781 /* never reached */
1783 if(hup)
1785 dosighup(SIGHUP);
1786 hup=0;
1788 if(alrm)
1790 dosigalrm(SIGALRM);
1791 alrm=0;
1793 FD_ZERO(&fds);
1794 FD_SET(sockfd,&fds);
1796 maxfd=sockfd;
1797 if(listen_tcpip)
1799 FD_SET(sockinet,&fds);
1800 maxfd=max(maxfd,sockinet);
1802 if(clin>0 && hw.rec_mode!=0 && hw.fd!=-1)
1804 FD_SET(hw.fd,&fds);
1805 maxfd=max(maxfd,hw.fd);
1808 for(i=0;i<clin;i++)
1810 /* Ignore this client until codes have been
1811 sent and it will get an answer. Otherwise
1812 we could mix up answer packets and send
1813 them back in the wrong order.*/
1814 if(clis[i]!=repeat_fd)
1816 FD_SET(clis[i],&fds);
1817 maxfd=max(maxfd,clis[i]);
1820 timerclear(&tv);
1821 reconnect=0;
1822 for(i=0;i<peern;i++)
1824 if(peers[i]->socket!=-1)
1826 FD_SET(peers[i]->socket,&fds);
1827 maxfd=max(maxfd,peers[i]->socket);
1829 else if(timerisset(&tv))
1831 if(timercmp
1832 (&tv,&peers[i]->reconnect,>))
1834 tv=peers[i]->reconnect;
1837 else
1839 tv=peers[i]->reconnect;
1842 if(timerisset(&tv))
1844 gettimeofday(&now,NULL);
1845 if(timercmp(&now,&tv,>))
1847 timerclear(&tv);
1849 else
1851 timersub(&tv,&now,&start);
1852 tv=start;
1854 reconnect=1;
1856 gettimeofday(&start,NULL);
1857 if(maxusec>0)
1859 tv.tv_sec= maxusec / 1000000;
1860 tv.tv_usec=maxusec % 1000000;
1862 if(hw.fd == -1)
1864 /* try to reconnect */
1865 timerclear(&timeout);
1866 timeout.tv_sec = 1;
1868 if(timercmp(&tv, &timeout, >) ||
1869 (!reconnect && !timerisset(&tv)))
1871 tv = timeout;
1874 get_release_time(&release_time);
1875 if(timerisset(&release_time))
1877 gettimeofday(&now,NULL);
1878 if(timercmp(&now,&release_time,>))
1880 timerclear(&tv);
1882 else
1884 struct timeval gap;
1886 timersub(&release_time, &now, &gap);
1887 if(timercmp(&tv, &gap, >))
1889 tv = gap;
1893 #ifdef SIM_REC
1894 ret=select(maxfd+1,&fds,NULL,NULL,NULL);
1895 #else
1896 if(timerisset(&tv) || timerisset(&release_time) ||
1897 reconnect)
1899 ret=select(maxfd+1,&fds,NULL,NULL,&tv);
1901 else
1903 ret=select(maxfd+1,&fds,NULL,NULL,NULL);
1905 #endif
1906 if(ret==-1 && errno!=EINTR)
1908 logprintf(LOG_ERR,"select() failed");
1909 logperror(LOG_ERR,NULL);
1910 raise(SIGTERM);
1911 continue;
1913 gettimeofday(&now,NULL);
1914 if(timerisset(&release_time) &&
1915 timercmp(&now, &release_time, >))
1917 const char *release_message;
1918 release_message = trigger_release_event();
1919 if(release_message)
1921 broadcast_message(release_message);
1924 if(free_remotes!=NULL)
1926 free_old_remotes();
1928 if(maxusec>0)
1930 if(ret==0)
1932 return(0);
1934 if(time_elapsed(&start,&now)>=maxusec)
1936 return(0);
1938 else
1940 maxusec-=time_elapsed(&start,&now);
1944 if(reconnect)
1946 connect_to_peers();
1949 while(ret==-1 && errno==EINTR);
1951 if(hw.fd == -1 && clin > 0 && hw.init_func)
1953 log_enable(0);
1954 hw.init_func();
1955 log_enable(1);
1957 for(i=0;i<clin;i++)
1959 if(FD_ISSET(clis[i],&fds))
1961 FD_CLR(clis[i],&fds);
1962 if(get_command(clis[i])==0)
1964 remove_client(clis[i]);
1965 i--;
1969 for(i=0;i<peern;i++)
1971 if(peers[i]->socket!=-1 &&
1972 FD_ISSET(peers[i]->socket,&fds))
1974 if(get_peer_message(peers[i])==0)
1976 shutdown(peers[i]->socket,2);
1977 close(peers[i]->socket);
1978 peers[i]->socket=-1;
1979 peers[i]->connection_failure = 1;
1980 gettimeofday(&peers[i]->reconnect,NULL);
1981 peers[i]->reconnect.tv_sec+=5;
1986 if(FD_ISSET(sockfd,&fds))
1988 LOGPRINTF(1,"registering local client");
1989 add_client(sockfd);
1991 if(listen_tcpip && FD_ISSET(sockinet,&fds))
1993 LOGPRINTF(1,"registering inet client");
1994 add_client(sockinet);
1996 if(clin>0 && hw.rec_mode!=0 && hw.fd!=-1 &&
1997 FD_ISSET(hw.fd,&fds))
1999 register_input();
2000 /* we will read later */
2001 return(1);
2006 void loop()
2008 char *message;
2010 logprintf(LOG_NOTICE,"lircd(%s) ready", hw.name);
2011 while(1)
2013 (void) waitfordata(0);
2014 if(!hw.rec_func) continue;
2015 message=hw.rec_func(remotes);
2017 if(message!=NULL)
2019 if(hw.ioctl_func &&
2020 (hw.features&LIRC_CAN_NOTIFY_DECODE))
2022 hw.ioctl_func(LIRC_NOTIFY_DECODE, NULL);
2025 broadcast_message(message);
2030 int main(int argc,char **argv)
2032 struct sigaction act;
2033 int nodaemon=0;
2034 mode_t permission=S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH;
2035 char *device=NULL;
2037 hw_choose_driver(NULL);
2038 while(1)
2040 int c;
2041 static struct option long_options[] =
2043 {"help",no_argument,NULL,'h'},
2044 {"version",no_argument,NULL,'v'},
2045 {"nodaemon",no_argument,NULL,'n'},
2046 {"permission",required_argument,NULL,'p'},
2047 {"driver",required_argument,NULL,'H'},
2048 {"device",required_argument,NULL,'d'},
2049 {"listen",optional_argument,NULL,'l'},
2050 {"connect",required_argument,NULL,'c'},
2051 {"output",required_argument,NULL,'o'},
2052 {"pidfile",required_argument,NULL,'P'},
2053 # ifndef USE_SYSLOG
2054 {"logfile",required_argument,NULL,'L'},
2055 # endif
2056 # ifdef DEBUG
2057 {"debug",optional_argument,NULL,'D'},
2058 # endif
2059 {"release",optional_argument,NULL,'r'},
2060 {"allow-simulate",no_argument,NULL,'a'},
2061 {0, 0, 0, 0}
2063 c = getopt_long(argc,argv,"hvnp:H:d:o:P:l::c:r::a"
2064 # ifndef USE_SYSLOG
2065 "L:"
2066 # endif
2067 # ifdef DEBUG
2068 "D::"
2069 # endif
2070 ,long_options,NULL);
2071 if(c==-1)
2072 break;
2073 switch (c)
2075 case 'h':
2076 printf("Usage: %s [options] [config-file]\n",progname);
2077 printf("\t -h --help\t\t\tdisplay this message\n");
2078 printf("\t -v --version\t\t\tdisplay version\n");
2079 printf("\t -n --nodaemon\t\t\tdon't fork to background\n");
2080 printf("\t -p --permission=mode\t\tfile permissions for " LIRCD "\n");
2081 printf("\t -H --driver=driver\t\tuse given driver\n");
2082 printf("\t -d --device=device\t\tread from given device\n");
2083 printf("\t -l --listen[=port]\t\tlisten for network connections on port\n");
2084 printf("\t -c --connect=host[:port]\tconnect to remote lircd server\n");
2085 printf("\t -o --output=socket\t\toutput socket filename\n");
2086 printf("\t -P --pidfile=file\t\tdaemon pid file\n");
2087 # ifndef USE_SYSLOG
2088 printf("\t -L --logfile=file\t\tdaemon log file\n");
2089 # endif
2090 # ifdef DEBUG
2091 printf("\t -D[debug_level] --debug[=debug_level]\n");
2092 # endif
2093 printf("\t -r --release[=suffix]\t\tauto-generate release events\n");
2094 printf("\t -a --allow-simulate\t\taccept SIMULATE command\n");
2095 return(EXIT_SUCCESS);
2096 case 'v':
2097 printf("%s %s\n",progname,VERSION);
2098 return(EXIT_SUCCESS);
2099 case 'n':
2100 nodaemon=1;
2101 break;
2102 case 'p':
2103 if(oatoi(optarg)==-1)
2105 fprintf(stderr,"%s: invalid mode\n",progname);
2106 return(EXIT_FAILURE);
2108 permission=oatoi(optarg);
2109 break;
2110 case 'H':
2111 if(hw_choose_driver(optarg) != 0){
2112 fprintf(stderr, "Driver `%s' not supported.\n",
2113 optarg);
2114 hw_print_drivers(stderr);
2115 exit (EXIT_FAILURE);
2117 break;
2118 case 'd':
2119 device=optarg;
2120 break;
2121 case 'P':
2122 pidfile=optarg;
2123 break;
2124 # ifndef USE_SYSLOG
2125 case 'L':
2126 logfile=optarg;
2127 break;
2128 # endif
2129 case 'o':
2130 lircdfile=optarg;
2131 break;
2132 case 'l':
2133 listen_tcpip=1;
2134 if(optarg)
2136 long p;
2137 char *endptr;
2139 p=strtol(optarg,&endptr,10);
2140 if(!*optarg || *endptr || p<1 || p>USHRT_MAX)
2142 fprintf(stderr,
2143 "%s: bad port number \"%s\"\n",
2144 progname,optarg);
2145 return(EXIT_FAILURE);
2147 port=(unsigned short int) p;
2149 else
2151 port=LIRC_INET_PORT;
2153 break;
2154 case 'c':
2155 if(!add_peer_connection(optarg))
2156 return(EXIT_FAILURE);
2157 break;
2158 # ifdef DEBUG
2159 case 'D':
2160 if(optarg==NULL) debug=1;
2161 else
2163 /* don't check for errors */
2164 debug=atoi(optarg);
2166 break;
2167 # endif
2168 case 'r':
2169 if(optarg)
2171 set_release_suffix(optarg);
2173 else
2175 set_release_suffix(LIRC_RELEASE_SUFFIX);
2177 break;
2178 case 'a':
2179 allow_simulate=1;
2180 break;
2181 default:
2182 printf("Usage: %s [options] [config-file]\n",progname);
2183 return(EXIT_FAILURE);
2186 if(optind==argc-1)
2188 configfile=argv[optind];
2190 else if(optind!=argc)
2192 fprintf(stderr,"%s: invalid argument count\n",progname);
2193 return(EXIT_FAILURE);
2196 if(device!=NULL)
2198 hw.device=device;
2200 if(strcmp(hw.name, "null")==0 && peern==0)
2202 fprintf(stderr,"%s: there's no hardware I can use and "
2203 "no peers are specified\n",progname);
2204 return(EXIT_FAILURE);
2206 if(hw.device!=NULL && strcmp(hw.device, lircdfile)==0)
2208 fprintf(stderr, "%s: refusing to connect to myself\n",
2209 progname);
2210 fprintf(stderr, "%s: device and output must not be the "
2211 "same file: %s\n", progname, lircdfile);
2212 return(EXIT_FAILURE);
2215 signal(SIGPIPE,SIG_IGN);
2217 start_server(permission,nodaemon);
2219 act.sa_handler=sigterm;
2220 sigfillset(&act.sa_mask);
2221 act.sa_flags=SA_RESTART; /* don't fiddle with EINTR */
2222 sigaction(SIGTERM,&act,NULL);
2223 sigaction(SIGINT,&act,NULL);
2225 act.sa_handler=sigalrm;
2226 sigemptyset(&act.sa_mask);
2227 act.sa_flags=SA_RESTART; /* don't fiddle with EINTR */
2228 sigaction(SIGALRM,&act,NULL);
2230 remotes=NULL;
2231 config(); /* read config file */
2233 act.sa_handler=sighup;
2234 sigemptyset(&act.sa_mask);
2235 act.sa_flags=SA_RESTART; /* don't fiddle with EINTR */
2236 sigaction(SIGHUP,&act,NULL);
2238 #ifdef DAEMONIZE
2239 /* ready to accept connections */
2240 if(!nodaemon) daemonize();
2241 #endif
2243 #if defined(SIM_SEND) && !defined(DAEMONIZE)
2245 struct ir_remote *r;
2246 struct ir_ncode *c;
2248 if(hw.init_func)
2250 if(!hw.init_func()) dosigterm(SIGTERM);
2253 printf("space 1000000\n");
2254 r=remotes;
2255 while(r!=NULL)
2257 c=r->codes;
2258 while(c->name!=NULL)
2260 repeat_remote=NULL;
2261 repeat_code=NULL;
2262 c->transmit_state = NULL;
2263 send_ir_ncode(r,c);
2264 repeat_remote=r;
2265 repeat_code=c;
2266 send_ir_ncode(r,c);
2267 send_ir_ncode(r,c);
2268 send_ir_ncode(r,c);
2269 send_ir_ncode(r,c);
2270 c++;
2272 r=r->next;
2274 fflush(stdout);
2275 if(hw.deinit_func) hw.deinit_func();
2277 fprintf(stderr,"Ready.\n");
2278 dosigterm(SIGTERM);
2279 #endif
2280 loop();
2282 /* never reached */
2283 return(EXIT_SUCCESS);