Server - Ignore SIGPIPE (just let it return a read error)
[tpg/opendispense2.git] / src / server / main.c
1 /*
2  * OpenDispense 2 
3  * UCC (University [of WA] Computer Club) Electronic Accounting System
4  *
5  * main.c - Initialisation Code
6  *
7  * This file is licenced under the 3-clause BSD Licence. See the file
8  * COPYING for full details.
9  */
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <stdbool.h>
13 #include <string.h>
14 #include <signal.h>
15 #include "common.h"
16 #include <termios.h>
17 #include <unistd.h>
18 #include <sys/stat.h>
19 #include <fcntl.h>
20 #include <stdarg.h>
21 #include <syslog.h>
22 #include <pthread.h>
23 #include "../cokebank.h"
24 #include "../common/config.h"
25
26 // === IMPORTS ===
27 extern void     Init_Handlers(void);
28 extern void     Load_Itemlist(void);
29 extern void     Server_Start(void);
30 extern int      gbServer_RunInBackground;
31 extern int      giServer_Port;
32 extern const char       *gsItemListFile;
33 extern const char       *gsCoke_ModbusAddress;
34 extern int      giCoke_ModbusPort;
35 extern const char       *gsDoor_SerialPort;
36 extern bool     gbSyslogEnabled;
37
38 // === PROTOTYPES ===
39 void    *Periodic_Thread(void *Unused);
40
41 // === GLOBALS ===
42  int    giDebugLevel = 0;
43  int    gbNoCostMode = 0;
44 const char      *gsCokebankPath = "cokebank.db";
45 // - Functions called every 20s (or so)
46 #define ciMaxPeriodics  10
47 struct sPeriodicCall {
48         void    (*Function)(void);
49 }       gaPeriodicCalls[ciMaxPeriodics];
50 pthread_t       gTimerThread;
51
52 // === CODE ===
53 void sigint_handler()
54 {
55         exit(0);
56 }
57
58 void PrintUsage(const char *progname)
59 {
60         fprintf(stderr, "Usage: %s\n", progname);
61         fprintf(stderr, "  -f,--configfile\n");
62         fprintf(stderr, "        Set the config file path (default `dispsrv.conf')\n");
63         fprintf(stderr, "  -d    Set debug level (0 - 2, default 0)\n");
64         fprintf(stderr, "  --[dont-]daemonise\n");
65         fprintf(stderr, "        Run (or explicitly don't run) the server disconnected from the terminal\n");
66 }
67
68 int main(int argc, char *argv[])
69 {
70          int    i;
71         const char      *config_file = "dispsrv.conf";
72
73         // Parse Arguments
74         for( i = 1; i < argc; i++ )
75         {
76                 char    *arg = argv[i];
77                 if( arg[0] == '-' && arg[1] != '-')
78                 {
79                         switch(arg[1])
80                         {
81                         case 'f':
82                                 if( i + 1 >= argc )     return -1;
83                                 config_file = argv[++i];
84                                 break;
85                         case 'd':
86                                 if( i + 1 >= argc )     return -1;
87                                 Config_AddValue("debug_level", argv[++i]);
88                                 giDebugLevel = atoi(argv[i]);
89                                 break;
90                         default:
91                                 // Usage Error
92                                 fprintf(stderr, "Unknown option '-%c'\n", arg[1]);
93                                 PrintUsage(argv[0]);
94                                 return -1;
95                         }
96                 }
97                 else if( arg[0] == '-' && arg[1] == '-' )
98                 {
99                         if( strcmp(arg, "--configfile") == 0 ) {
100                                 if( i + 1 >= argc )     return -1;
101                                 config_file = argv[++i];
102                         }
103                         else if( strcmp(arg, "--daemonise") == 0 ) {
104                                 Config_AddValue("daemonise", "true");
105                         }
106                         else if( strcmp(arg, "--dont-daemonise") == 0 ) {
107                                 Config_AddValue("daemonise", "false");
108                         }
109                         else {
110                                 // Usage error
111                                 fprintf(stderr, "Unknown option '%s'\n", arg);
112                                 PrintUsage(argv[0]);
113                                 return -1;
114                         }
115                 }
116                 else
117                 {
118                         // Usage Error
119                         PrintUsage(argv[0]);
120                         return -1;
121                 }
122         }
123
124         Config_ParseFile( config_file );
125
126         // Parse config values
127         gbServer_RunInBackground = Config_GetValue_Bool("daemonise", 0);
128         gsCokebankPath       = Config_GetValue("cokebank_database", 0);
129         gsDoor_SerialPort    = Config_GetValue("door_serial_port", 0);
130         giServer_Port        = Config_GetValue_Int("server_port", 0);
131         gsItemListFile       = Config_GetValue("items_file", 0);
132
133         gbNoCostMode         = (Config_GetValue_Bool("test_mode", 0) == 1);
134         gbSyslogEnabled      = (Config_GetValue_Bool("disable_syslog", 0) == 0);
135
136         gsCoke_ModbusAddress = Config_GetValue("coke_modbus_address", 0);
137         giCoke_ModbusPort    = Config_GetValue_Int("coke_modbus_port", 0);
138
139         // - Cleanly tear down the server on SIGINT/SIGTERM
140         signal(SIGINT, sigint_handler);
141         signal(SIGTERM, sigint_handler);
142         // - ignore SIGPIPE to prevent a crashing client from bringing the server down too
143         signal(SIGPIPE, SIG_IGN);
144         
145         openlog("odispense2", 0, LOG_LOCAL4);
146         
147         if( Bank_Initialise(gsCokebankPath) )
148                 return -1;
149
150         Init_Handlers();
151
152         Load_Itemlist();
153         
154         Server_Start();
155         
156         if(gTimerThread)
157                 pthread_kill(gTimerThread, SIGKILL);
158
159         return 0;
160 }
161
162 void *Periodic_Thread(void *Unused __attribute__((unused)))
163 {
164          int    i;
165         
166         for( ;; )
167         {
168                 sleep(10);      // Sleep for a while
169 //              printf("Periodic firing\n");
170                 for( i = 0; i < ciMaxPeriodics; i ++ )
171                 {
172                         if( gaPeriodicCalls[i].Function )
173                                 gaPeriodicCalls[i].Function();
174                 }
175         }
176         return NULL;
177 }
178
179 void StartPeriodicThread(void)
180 {
181         pthread_create( &gTimerThread, NULL, Periodic_Thread, NULL );
182 }
183
184 void AddPeriodicFunction(void (*Fcn)(void))
185 {
186         int i;
187         for( i = 0; i < ciMaxPeriodics; i ++ )
188         {
189                 if( gaPeriodicCalls[i].Function )       continue;
190                 gaPeriodicCalls[i].Function = Fcn;
191                 return ;
192         }
193         
194         fprintf(stderr, "Error: No space for %p in periodic list\n", Fcn);
195 }
196
197 // Serial helper
198 int InitSerial(const char *File, int BaudRate)
199 {
200         struct termios  info;
201          int    baud;
202          int    fd;
203         
204         fd = open(File, O_RDWR | O_NOCTTY | O_NONBLOCK);
205         if( fd == -1 )  return -1;
206         
207         switch(BaudRate)
208         {
209         case 1200:      baud = B1200;   break;
210         case 9600:      baud = B9600;   break;
211         case 115200:    baud = B115200; break;
212         default:
213                 fprintf(stderr, "ERROR: Invalid baud rate to InitSerial (%i)\n", BaudRate);
214                 exit(1);
215         }
216         
217         info.c_lflag = 0;       // Non-Canoical, No Echo
218         info.c_cflag = baud | CS8 | CLOCAL | CREAD;     // baud, 8N1
219         info.c_iflag = IGNCR;   // Ignore \r
220         info.c_oflag = 0;       // ???
221         cfsetspeed(&info, baud);
222         info.c_cc[VTIME] = 0;   // No time limit
223         info.c_cc[VMIN] = 1;    // Block until 1 char
224         
225         tcflush(fd, TCIFLUSH);
226         tcsetattr(fd, TCSANOW, &info);
227         
228         return fd;
229 }
230
231
232 /**
233  * \brief Create a formatted heap string
234  */
235 char *mkstr(const char *Format, ...)
236 {
237         va_list args;
238          int    len;
239         char    *ret;
240
241         va_start(args, Format);
242         len = vsnprintf(NULL, 0, Format, args);
243         va_end(args);
244
245         ret = malloc( len + 1 );
246         if(!ret)        return NULL;
247
248         va_start(args, Format);
249         vsprintf(ret, Format, args);
250         va_end(args);
251         
252         return ret;
253 }
254

UCC git Repository :: git.ucc.asn.au