Fixed up daemonising implementation (now to test it)
[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 <string.h>
13 #include <signal.h>
14 #include "common.h"
15 #include <termios.h>
16 #include <unistd.h>
17 #include <sys/stat.h>
18 #include <fcntl.h>
19 #include <stdarg.h>
20 #include <syslog.h>
21 #include <pthread.h>
22 #include "../cokebank.h"
23
24 // === IMPORTS ===
25 extern void     Init_Handlers(void);
26 extern void     Load_Itemlist(void);
27 extern void     Server_Start(void);
28 extern int      gbServer_RunInBackground;
29 extern int      giServer_Port;
30 extern char     *gsItemListFile;
31 extern char     *gsCoke_SerialPort;
32 extern char     *gsSnack_SerialPort;
33 extern char     *gsDoor_Password;
34
35 // === PROTOTYPES ===
36 void    *Periodic_Thread(void *Unused);
37
38 // === GLOBALS ===
39  int    giDebugLevel = 0;
40 char    *gsCokebankPath = "cokebank.db";
41 // - Functions called every 20s (or so)
42 #define ciMaxPeriodics  10
43 struct sPeriodicCall {
44         void    (*Function)(void);
45 }       gaPeriodicCalls[ciMaxPeriodics];
46
47 // === CODE ===
48 void sigint_handler()
49 {
50         exit(0);
51 }
52
53 void PrintUsage(const char *progname)
54 {
55         fprintf(stderr, "Usage: %s\n", progname);
56         fprintf(stderr, "  -p    Set server port (default 11020)\n");
57         fprintf(stderr, "  -d    Set debug level (0 - 2, default 0)\n");
58         fprintf(stderr, "  --itemsfile\n");
59         fprintf(stderr, "        Set debug level (0 - 2, default 0)\n");
60         fprintf(stderr, "  --cokeport\n");
61         fprintf(stderr, "        Coke machine serial port (Default \"/dev/ttyS0\")\n");
62         fprintf(stderr, "  --doorpass\n");
63         fprintf(stderr, "        Door LAT password file (Default empty password)\n");
64         fprintf(stderr, "  --cokebank\n");
65         fprintf(stderr, "        Coke bank database file (Default \"cokebank.db\")\n");
66 }
67
68 int main(int argc, char *argv[])
69 {
70          int    i;
71         pthread_t       timer_thread;
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 'p':
82                                 if( i + 1 >= argc )     return -1;
83                                 giServer_Port = atoi(argv[++i]);
84                                 break;
85                         case 'd':
86                                 if( i + 1 >= argc )     return -1;
87                                 giDebugLevel = atoi(argv[++i]);
88                                 break;
89                         case 'D':
90                                 gbServer_RunInBackground = 1;
91                                 return -1;
92                         default:
93                                 // Usage Error?
94                                 PrintUsage(argv[0]);
95                                 return -1;
96                         }
97                 }
98                 else if( arg[0] == '-' && arg[1] == '-' ) {
99                         if( strcmp(arg, "--itemsfile") == 0 ) {
100                                 if( i + 1 >= argc )     return -1;
101                                 gsItemListFile = argv[++i];
102                         }
103                         else if( strcmp(arg, "--cokeport") == 0 ) {
104                                 if( i + 1 >= argc )     return -1;
105                                 gsCoke_SerialPort = argv[++i];
106                         }
107                         else if( strcmp(arg, "--snackport") == 0 ) {
108                                 if( i + 1 >= argc )     return -1;
109                                 gsSnack_SerialPort = argv[++i];
110                         }
111                         else if( strcmp(arg, "--doorpass") == 0 ) {
112                                 FILE    *fp;
113                                 char    buf[30];
114                                 if( i + 1 >= argc )     return -1;
115                                 fp = fopen(argv[++i], "r");
116                                 if( !fp ) {
117                                         fprintf(stderr, "ERROR: Unable to read password file\n");
118                                         perror("reading LAT password");
119                                         return -1;
120                                 }
121                                 fgets(buf, sizeof buf, fp);
122                                 fclose(fp);
123                                 gsDoor_Password = strdup(buf);
124                         }
125                         else if( strcmp(arg, "--cokebank") == 0 ) {
126                                 if( i + 1 >= argc )     return -1;
127                                 gsCokebankPath = argv[++i];
128                         }
129                         else if( strcmp(arg, "--daemonise") == 0 ) {
130                                 gbServer_RunInBackground = 1;
131                         }
132                         else if( strcmp(arg, "--dont-daemonise") == 0 ) {
133                                 gbServer_RunInBackground = 1;
134                         }
135                         else {
136                                 // Usage error?
137                                 PrintUsage(argv[0]);
138                                 return -1;
139                         }
140                 }
141                 else {
142                         // Usage Error?
143                         PrintUsage(argv[0]);
144                         return -1;
145                 }
146         }
147         
148         signal(SIGINT, sigint_handler);
149         signal(SIGTERM, sigint_handler);
150         
151         openlog("odispense2", 0, LOG_LOCAL4);
152         
153         if( Bank_Initialise(gsCokebankPath) )
154                 return -1;
155
156         Init_Handlers();
157
158         Load_Itemlist();
159         
160         pthread_create( &timer_thread, NULL, Periodic_Thread, NULL );
161         
162         Server_Start();
163         
164         pthread_kill(timer_thread, SIGKILL);
165
166         return 0;
167 }
168
169 void *Periodic_Thread(void *Unused)
170 {
171          int    i;
172         Unused = NULL;  // quiet, gcc
173         
174         for( ;; )
175         {
176                 sleep(10);      // Sleep for a while
177 //              printf("Periodic firing\n");
178                 for( i = 0; i < ciMaxPeriodics; i ++ )
179                 {
180                         if( gaPeriodicCalls[i].Function )
181                                 gaPeriodicCalls[i].Function();
182                 }
183         }
184         return NULL;
185 }
186
187 void AddPeriodicFunction(void (*Fcn)(void))
188 {
189         int i;
190         for( i = 0; i < ciMaxPeriodics; i ++ )
191         {
192                 if( gaPeriodicCalls[i].Function )       continue;
193                 gaPeriodicCalls[i].Function = Fcn;
194                 return ;
195         }
196         
197         fprintf(stderr, "Error: No space for %p in periodic list\n", Fcn);
198 }
199
200 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
201 {
202          int    ret;
203         
204         ret = regexec(regex, string, nMatches, matches, 0);
205         if( ret == REG_NOMATCH ) {
206                 return -1;
207         }
208         if( ret ) {
209                 size_t  len = regerror(ret, regex, NULL, 0);
210                 char    errorStr[len];
211                 regerror(ret, regex, errorStr, len);
212                 printf("string = '%s'\n", string);
213                 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
214                 exit(-1);
215         }
216         
217         return ret;
218 }
219
220 void CompileRegex(regex_t *regex, const char *pattern, int flags)
221 {
222          int    ret = regcomp(regex, pattern, flags);
223         if( ret ) {
224                 size_t  len = regerror(ret, regex, NULL, 0);
225                 char    errorStr[len];
226                 regerror(ret, regex, errorStr, len);
227                 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);
228                 exit(-1);
229         }
230 }
231
232 // Serial helper
233 int InitSerial(const char *File, int BaudRate)
234 {
235         struct termios  info;
236          int    baud;
237          int    fd;
238         
239         fd = open(File, O_RDWR | O_NOCTTY | O_NONBLOCK);
240         if( fd == -1 )  return -1;
241         
242         switch(BaudRate)
243         {
244         case 9600:      baud = B9600;   break;
245         default:        close(fd);      return -1;
246         }
247         
248         info.c_lflag = 0;       // Non-Canoical, No Echo
249         info.c_cflag = baud | CS8 | CLOCAL | CREAD;     // baud, 8N1
250         cfsetspeed(&info, baud);
251         info.c_cc[VTIME] = 0;   // No time limit
252         info.c_cc[VMIN] = 1;    // Block until 1 char
253         
254         tcflush(fd, TCIFLUSH);
255         tcsetattr(fd, TCSANOW, &info);
256         
257         return fd;
258 }
259
260
261 /**
262  * \brief Create a formatted heap string
263  */
264 char *mkstr(const char *Format, ...)
265 {
266         va_list args;
267          int    len;
268         char    *ret;
269
270         va_start(args, Format);
271         len = vsnprintf(NULL, 0, Format, args);
272         va_end(args);
273
274         ret = malloc( len + 1 );
275         if(!ret)        return NULL;
276
277         va_start(args, Format);
278         vsprintf(ret, Format, args);
279         va_end(args);
280         
281         return ret;
282 }
283

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