User auths and client UI design
[tpg/opendispense2.git] / src / client / main.c
1 /*
2  * OpenDispense 2 
3  * UCC (University [of WA] Computer Club) Electronic Accounting System
4  * - Dispense Client
5  *
6  * main.c - Core and Initialisation
7  *
8  * This file is licenced under the 3-clause BSD Licence. See the file
9  * COPYING for full details.
10  */
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <ctype.h>      // isspace
15 #include <stdarg.h>
16 #include <regex.h>
17
18 #include <unistd.h>     // close
19 #include <netdb.h>      // gethostbyname
20 #include <pwd.h>        // getpwuids
21 #include <sys/socket.h>
22 #include <netinet/in.h>
23 #include <arpa/inet.h>
24
25 // === TYPES ===
26 typedef struct sItem {
27         char    *Ident;
28         char    *Desc;
29          int    Price;
30 }       tItem;
31
32 // === PROTOTYPES ===
33  int    sendf(int Socket, const char *Format, ...);
34  int    OpenConnection(const char *Host, int Port);
35 void    Authenticate(int Socket);
36 char    *trim(char *string);
37  int    RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
38 void    CompileRegex(regex_t *regex, const char *pattern, int flags);
39
40 // === GLOBALS ===
41 char    *gsDispenseServer = "localhost";
42  int    giDispensePort = 11020;
43 tItem   *gaItems;
44  int    giNumItems;
45 regex_t gArrayRegex;
46 regex_t gItemRegex;
47
48 // === CODE ===
49 int main(int argc, char *argv[])
50 {
51          int    sock;
52          int    i, responseCode, len;
53         char    buffer[BUFSIZ];
54         
55         // -- Create regular expressions
56         // > Code Type Count ...
57         CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED);     //
58         // > Code Type Ident Price Desc
59         CompileRegex(&gItemRegex, "^([0-9]{3})\\s+(.+?)\\s+(.+?)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
60         
61         // Connect to server
62         sock = OpenConnection(gsDispenseServer, giDispensePort);
63         if( sock < 0 )  return -1;
64
65         // Determine what to do
66         if( argc > 1 )
67         {
68                 if( strcmp(argv[1], "acct") == 0 )
69                 {
70                         // Alter account
71                         // List accounts
72                         return 0;
73                 }
74         }
75
76         // Ask server for stock list
77         send(sock, "ENUM_ITEMS\n", 11, 0);
78         len = recv(sock, buffer, BUFSIZ-1, 0);
79         buffer[len] = '\0';
80         
81         trim(buffer);
82         
83         printf("Output: %s\n", buffer);
84         
85         responseCode = atoi(buffer);
86         if( responseCode != 201 )
87         {
88                 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
89                 return -1;
90         }
91         
92         // Get item list
93         {
94                 char    *itemType, *itemStart;
95                  int    count;
96                 regmatch_t      matches[4];
97                 
98                 // Expected format: 201 Items <count> <item1> <item2> ...
99                 RunRegex(&gArrayRegex, buffer, 4, matches, "Malformed server response");
100                 
101                 itemType = &buffer[ matches[2].rm_so ]; buffer[ matches[2].rm_eo ] = '\0';
102                 count = atoi( &buffer[ matches[3].rm_so ] );
103                 
104                 // Check array type
105                 if( strcmp(itemType, "Items") != 0 ) {
106                         // What the?!
107                         fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
108                                 itemType);
109                         return -1;
110                 }
111                 
112                 itemStart = &buffer[ matches[3].rm_eo ];
113                 
114                 gaItems = malloc( count * sizeof(tItem) );
115                 
116                 for( giNumItems = 0; giNumItems < count && itemStart; giNumItems ++ )
117                 {
118                         char    *next = strchr( ++itemStart, ' ' );
119                         if( next )      *next = '\0';
120                         gaItems[giNumItems].Ident = strdup(itemStart);
121                         itemStart = next;
122                 }
123         }
124         
125         // Get item information
126         for( i = 0; i < giNumItems; i ++ )
127         {
128                 regmatch_t      matches[6];
129                 
130                 // Print item Ident
131                 printf("%2i %s\t", i, gaItems[i].Ident);
132                 
133                 // Get item info
134                 sendf(sock, "ITEM_INFO %s\n", gaItems[i].Ident);
135                 len = recv(sock, buffer, BUFSIZ-1, 0);
136                 buffer[len] = '\0';
137                 trim(buffer);
138                 
139                 responseCode = atoi(buffer);
140                 if( responseCode != 202 ) {
141                         fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
142                         return -1;
143                 }
144                 
145                 RunRegex(&gItemRegex, buffer, 6, matches, "Malformed server response");
146                 
147                 buffer[ matches[3].rm_eo ] = '\0';
148                 
149                 gaItems[i].Price = atoi( buffer + matches[4].rm_so );
150                 gaItems[i].Desc = strdup( buffer + matches[5].rm_so );
151                 
152                 printf("%3i %s\n", gaItems[i].Price, gaItems[i].Desc);
153         }
154         
155         Authenticate(sock);
156         
157         // and choose what to dispense
158         // TODO: ncurses interface (with separation between item classes)
159         // - Hmm... that would require standardising the item ID to be <class>:<index>
160         // Oh, why not :)
161         
162         for(;;)
163         {
164                 char    *buf;
165                 
166                 fgets(buffer, BUFSIZ, stdin);
167                 
168                 buf = trim(buffer);
169                 
170                 if( buf[0] == 'q' )     break;
171                 
172                 i = atoi(buf);
173                 
174                 printf("buf = '%s', atoi(buf) = %i\n", buf, i);
175                 
176                 if( i != 0 || buf[0] == '0' )
177                 {
178                         printf("i = %i\n", i);
179                         
180                         if( i < 0 || i >= giNumItems ) {
181                                 printf("Bad item (should be between 0 and %i)\n", giNumItems);
182                                 continue;
183                         }
184                         
185                         sendf(sock, "DISPENSE %s\n", gaItems[i].Ident);
186                         
187                         len = recv(sock, buffer, BUFSIZ-1, 0);
188                         buffer[len] = '\0';
189                         trim(buffer);
190                         
191                         responseCode = atoi(buffer);
192                         switch( responseCode )
193                         {
194                         case 200:
195                                 printf("Dispense OK\n");
196                                 break;
197                         case 401:
198                                 printf("Not authenticated\n");
199                                 break;
200                         case 402:
201                                 printf("Insufficient balance\n");
202                                 break;
203                         case 406:
204                                 printf("Bad item name, bug report\n");
205                                 break;
206                         case 500:
207                                 printf("Item failed to dispense, is the slot empty?\n");
208                                 break;
209                         default:
210                                 printf("Unknown response code %i\n", responseCode);
211                                 break;
212                         }
213                         
214                         break;
215                 }
216         }
217
218         close(sock);
219
220         return 0;
221 }
222
223 // === HELPERS ===
224 int sendf(int Socket, const char *Format, ...)
225 {
226         va_list args;
227          int    len;
228         
229         va_start(args, Format);
230         len = vsnprintf(NULL, 0, Format, args);
231         va_end(args);
232         
233         {
234                 char    buf[len+1];
235                 va_start(args, Format);
236                 vsnprintf(buf, len+1, Format, args);
237                 va_end(args);
238                 
239                 return send(Socket, buf, len, 0);
240         }
241 }
242
243 int OpenConnection(const char *Host, int Port)
244 {
245         struct hostent  *host;
246         struct sockaddr_in      serverAddr;
247          int    sock;
248         
249         host = gethostbyname(Host);
250         if( !host ) {
251                 fprintf(stderr, "Unable to look up '%s'\n", Host);
252                 return -1;
253         }
254         
255         memset(&serverAddr, 0, sizeof(serverAddr));
256         
257         serverAddr.sin_family = AF_INET;        // IPv4
258         // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
259         serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
260         serverAddr.sin_port = htons(Port);
261         
262         sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
263         if( sock < 0 ) {
264                 fprintf(stderr, "Failed to create socket\n");
265                 return -1;
266         }
267         
268         #if USE_AUTOAUTH
269         {
270                 struct sockaddr_in      localAddr;
271                 memset(&localAddr, 0, sizeof(localAddr));
272                 localAddr.sin_family = AF_INET; // IPv4
273                 localAddr.sin_port = 1023;      // IPv4
274                 // Attempt to bind to low port for autoauth
275                 bind(sock, &localAddr, sizeof(localAddr));
276         }
277         #endif
278         
279         if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
280                 fprintf(stderr, "Failed to connect to server\n");
281                 return -1;
282         }
283         
284         return sock;
285 }
286
287 void Authenticate(int Socket)
288 {
289         struct passwd   *pwd;
290         char    buf[512];
291          int    responseCode;
292         
293         // Get user name
294         pwd = getpwuid( getuid() );
295         
296         // Attempt automatic authentication
297         sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
298         
299         // Check if it worked
300         recv(Socket, buf, 511, 0);
301         trim(buf);
302         
303         responseCode = atoi(buf);
304         switch( responseCode )
305         {
306         case 200:       // Authenticated, return :)
307                 return ;
308         case 401:       // Untrusted, attempt password authentication
309                 break;
310         case 404:       // Bad Username
311                 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
312                 exit(-1);
313         default:
314                 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
315                 printf("%s\n", buf);
316                 exit(-1);
317         }
318         
319         printf("%s\n", buf);
320 }
321
322 char *trim(char *string)
323 {
324          int    i;
325         
326         while( isspace(*string) )
327                 string ++;
328         
329         for( i = strlen(string); i--; )
330         {
331                 if( isspace(string[i]) )
332                         string[i] = '\0';
333                 else
334                         break;
335         }
336         
337         return string;
338 }
339
340 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
341 {
342          int    ret;
343         
344         ret = regexec(regex, string, nMatches, matches, 0);
345         if( ret ) {
346                 size_t  len = regerror(ret, regex, NULL, 0);
347                 char    errorStr[len];
348                 regerror(ret, regex, errorStr, len);
349                 printf("string = '%s'\n", string);
350                 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
351                 exit(-1);
352         }
353         
354         return ret;
355 }
356
357 void CompileRegex(regex_t *regex, const char *pattern, int flags)
358 {
359          int    ret = regcomp(regex, pattern, flags);
360         if( ret ) {
361                 size_t  len = regerror(ret, regex, NULL, 0);
362                 char    errorStr[len];
363                 regerror(ret, regex, errorStr, len);
364                 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);
365                 exit(-1);
366         }
367 }

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