Updated ShowUsage for the new commands
[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 #include <ncurses.h>
18 #include <limits.h>
19
20 #include <unistd.h>     // close
21 #include <netdb.h>      // gethostbyname
22 #include <pwd.h>        // getpwuids
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <openssl/sha.h>        // SHA1
27
28 #define USE_NCURSES_INTERFACE   0
29 #define DEBUG_TRACE_SERVER      0
30
31 // === TYPES ===
32 typedef struct sItem {
33         char    *Ident;
34         char    *Desc;
35          int    Price;
36 }       tItem;
37
38 // === PROTOTYPES ===
39  int    main(int argc, char *argv[]);
40 void    ShowUsage(void);
41 // --- GUI ---
42  int    ShowNCursesUI(void);
43 void    ShowItemAt(int Row, int Col, int Width, int Index);
44 void    PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
45 // --- Coke Server Communication ---
46  int    OpenConnection(const char *Host, int Port);
47  int    Authenticate(int Socket);
48 void    PopulateItemList(int Socket);
49  int    DispenseItem(int Socket, int ItemID);
50  int    Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
51  int    Dispense_SetBalance(int Socket, const char *Username, int Ammount, const char *Reason);
52  int    Dispense_EnumUsers(int Socket);
53  int    Dispense_ShowUser(int Socket, const char *Username);
54 void    _PrintUserLine(const char *Line);
55  int    Dispense_AddUser(int Socket, const char *Username);
56  int    Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
57 // --- Helpers ---
58 char    *ReadLine(int Socket);
59  int    sendf(int Socket, const char *Format, ...);
60 char    *trim(char *string);
61  int    RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
62 void    CompileRegex(regex_t *regex, const char *pattern, int flags);
63
64 // === GLOBALS ===
65 char    *gsDispenseServer = "localhost";
66  int    giDispensePort = 11020;
67
68 tItem   *gaItems;
69  int    giNumItems;
70 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex;
71  int    gbIsAuthenticated = 0;
72
73 char    *gsItemPattern; //!< Item pattern
74 char    *gsOverrideUser;        //!< '-u' Dispense as another user
75  int    gbUseNCurses = 0;       //!< '-G' Use the NCurses GUI?
76  int    giMinimumBalance = INT_MIN;     //!< '-m' Minumum balance for `dispense acct`
77  int    giMaximumBalance = INT_MAX;     //!< '-M' Maximum balance for `dispense acct`
78
79 // === CODE ===
80 int main(int argc, char *argv[])
81 {
82          int    sock;
83          int    i;
84         char    buffer[BUFSIZ];
85         
86         // -- Create regular expressions
87         // > Code Type Count ...
88         CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED);     //
89         // > Code Type Ident Price Desc
90         CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z0-9:]+?)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
91         // > Code 'SALT' salt
92         CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
93         // > Code 'User' Username Balance Flags
94         CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
95
96         // Parse Arguments
97         for( i = 1; i < argc; i ++ )
98         {
99                 char    *arg = argv[i];
100                 
101                 if( arg[0] == '-' )
102                 {                       
103                         switch(arg[1])
104                         {
105                         case 'h':
106                         case '?':
107                                 ShowUsage();
108                                 return 0;
109                         
110                         case 'm':       // Minimum balance
111                                 giMinimumBalance = atoi(argv[++i]);
112                                 break;
113                         case 'M':       // Maximum balance
114                                 giMaximumBalance = atoi(argv[++i]);
115                                 break;
116                         
117                         case 'u':       // Override User
118                                 gsOverrideUser = argv[++i];
119                                 break;
120                         
121                         case 'G':       // Use GUI
122                                 gbUseNCurses = 1;
123                                 break;
124                         }
125
126                         continue;
127                 }
128                 
129                 if( strcmp(arg, "acct") == 0 )
130                 {
131                         // Connect to server
132                         sock = OpenConnection(gsDispenseServer, giDispensePort);
133                         if( sock < 0 )  return -1;
134
135                         // List accounts?
136                         if( i + 1 == argc ) {
137                                 Dispense_EnumUsers(sock);
138                                 return 0;
139                         }
140                         
141                         // argv[i+1]: Username
142                         
143                         // Alter account?
144                         if( i + 2 < argc )
145                         {
146                                 if( i + 3 >= argc ) {
147                                         fprintf(stderr, "Error: `dispense acct' needs a reason\n");
148                                         exit(1);
149                                 }
150                                 
151                                 // Authentication required
152                                 if( Authenticate(sock) )
153                                         return -1;
154                                 
155                                 // argv[i+1]: Username
156                                 // argv[i+2]: Ammount
157                                 // argv[i+3]: Reason
158                                 
159                                 if( argv[i+2][0] == '=' ) {
160                                         // Set balance
161                                         Dispense_SetBalance(sock, argv[i+1], atoi(argv[i+2] + 1), argv[i+3]);
162                                 }
163                                 else {
164                                         // Alter balance
165                                         Dispense_AlterBalance(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
166                                 }
167                         }
168                         
169                         Dispense_ShowUser(sock, argv[i+1]);
170                         
171                         close(sock);
172                         return 0;
173                 }
174                 else if( strcmp(arg, "user") == 0 )
175                 {
176                         // Check argument count
177                         if( i + 1 >= argc ) {
178                                 fprintf(stderr, "Error: `dispense user` requires arguments\n");
179                                 ShowUsage();
180                                 exit(1);
181                         }
182                         
183                         // Connect to server
184                         sock = OpenConnection(gsDispenseServer, giDispensePort);
185                         if( sock < 0 )  return -1;
186                         
187                         // Attempt authentication
188                         if( Authenticate(sock) )
189                                 return -1;
190                         
191                         // Add new user?
192                         if( strcmp(argv[i+1], "add") == 0 )
193                         {
194                                 if( i + 2 >= argc ) {
195                                         fprintf(stderr, "Error: `dispense user add` requires an argument\n");
196                                         ShowUsage();
197                                         exit(1);
198                                 }
199                                 
200                                 Dispense_AddUser(sock, argv[i+2]);
201                         }
202                         // Update a user
203                         else if( strcmp(argv[i+1], "type") == 0 )
204                         {
205                                 if( i + 3 >= argc ) {
206                                         fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
207                                         ShowUsage();
208                                         exit(1);
209                                 }
210                                 
211                                 Dispense_SetUserType(sock, argv[i+2], argv[i+3]);
212                         }
213                         else
214                         {
215                                 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
216                                 ShowUsage();
217                                 exit(1);
218                         }
219                         return 0;
220                 }
221                 else {
222                         // Item name / pattern
223                         gsItemPattern = arg;
224                         break;
225                 }
226         }
227         
228         // Connect to server
229         sock = OpenConnection(gsDispenseServer, giDispensePort);
230         if( sock < 0 )  return -1;
231         
232         // Authenticate
233         Authenticate(sock);
234
235         // Get items
236         PopulateItemList(sock);
237         
238         if( gsItemPattern )
239         {
240                 
241         }
242         else if( gbUseNCurses )
243         {
244                 i = ShowNCursesUI();
245         }
246         else
247         {
248                 for( i = 0; i < giNumItems; i ++ ) {            
249                         printf("%2i %s\t%3i %s\n", i, gaItems[i].Ident, gaItems[i].Price, gaItems[i].Desc);
250                 }
251                 printf(" q Quit\n");
252                 for(;;)
253                 {
254                         char    *buf;
255                         
256                         i = -1;
257                         
258                         fgets(buffer, BUFSIZ, stdin);
259                         
260                         buf = trim(buffer);
261                         
262                         if( buf[0] == 'q' )     break;
263                         
264                         i = atoi(buf);
265                         
266                         if( i != 0 || buf[0] == '0' )
267                         {
268                                 if( i < 0 || i >= giNumItems ) {
269                                         printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
270                                         continue;
271                                 }
272                                 break;
273                         }
274                 }
275         }
276         
277         // Check for a valid item ID
278         if( i >= 0 )
279                 DispenseItem(sock, i);
280
281         close(sock);
282
283         return 0;
284 }
285
286 void ShowUsage(void)
287 {
288         printf(
289                 "Usage:\n"
290                 "    dispense\n"
291                 "        Show interactive list\n"
292                 "    dispense <item>\n"
293                 "        Dispense named item\n"
294                 "    dispense give <user> <ammount> \"<reason>\"\n"
295                 "        Give some of your money away\n"
296                 "    dispense acct [<user>]\n"
297                 "        Show user balances\n"
298                 "    dispense acct <user> [+-=]<ammount> \"<reason>\"\n"
299                 "        Alter a account value (Coke members only)\n"
300                 "    dispense user add <user>\n"
301                 "        Create new coke account (Wheel members only)\n"
302                 "    dispense user type <flags>\n"
303                 "        Alter a user's flags\n"
304                 "        <flags> is a comma-separated list of user,coke,wheel,disabled\n"
305                 "        Flags are removed by preceding the name with '-' or '!'\n"
306                 "\n"
307                 "General Options:\n"
308                 "    -u <username>\n"
309                 "        Set a different user (Coke members only)\n"
310                 "    -h / -?\n"
311                 "        Show help text\n"
312                 "    -G\n"
313                 "        Use alternate GUI\n"
314                 "    -m <min balance>\n"
315                 "    -M <max balance>\n"
316                 "        Set the Maximum/Minimum balances shown in `dispense acct`\n"
317                 );
318 }
319
320 // -------------------
321 // --- NCurses GUI ---
322 // -------------------
323 /**
324  * \brief Render the NCurses UI
325  */
326 int ShowNCursesUI(void)
327 {
328         // TODO: ncurses interface (with separation between item classes)
329         // - Hmm... that would require standardising the item ID to be <class>:<index>
330         // Oh, why not :)
331          int    ch;
332          int    i, times;
333          int    xBase, yBase;
334         const int       displayMinWidth = 40;
335         const int       displayMinItems = 8;
336         char    *titleString = "Dispense";
337          int    itemCount = displayMinItems;
338          int    itemBase = 0;
339          int    currentItem = 0;
340          int    ret = -2;       // -2: Used for marking "no return yet"
341          
342          int    height, width;
343          
344         // Enter curses mode
345         initscr();
346         raw(); noecho();
347         
348         // Get item count
349         // - 6: randomly chosen (Need at least 3)
350         itemCount = LINES - 6;
351         if( itemCount > giNumItems )
352                 itemCount = giNumItems;
353         
354         // Get dimensions
355         height = itemCount + 3;
356         width = displayMinWidth;
357         
358         // Get positions
359         xBase = COLS/2 - width/2;
360         yBase = LINES/2 - height/2;
361         
362         for( ;; )
363         {
364                 // Header
365                 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
366                 
367                 // Items
368                 for( i = 0; i < itemCount; i ++ )
369                 {
370                         move( yBase + 1 + i, xBase );
371                         
372                         if( currentItem == itemBase + i ) {
373                                 printw("| -> ");
374                         }
375                         else {
376                                 printw("|    ");
377                         }
378                         
379                         // Check for ... row
380                         // - Oh god, magic numbers!
381                         if( i == 0 && itemBase > 0 ) {
382                                 printw("   ...");
383                                 times = width-1 - 8 - 3;
384                                 while(times--)  addch(' ');
385                         }
386                         else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
387                                 printw("   ...");
388                                 times = width-1 - 8 - 3;
389                                 while(times--)  addch(' ');
390                         }
391                         // Show an item
392                         else {
393                                 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
394                                 addch(' ');
395                         }
396                         
397                         // Scrollbar (if needed)
398                         if( giNumItems > itemCount ) {
399                                 if( i == 0 ) {
400                                         addch('A');
401                                 }
402                                 else if( i == itemCount - 1 ) {
403                                         addch('V');
404                                 }
405                                 else {
406                                          int    percentage = itemBase * 100 / (giNumItems-itemCount);
407                                         if( i-1 == percentage*(itemCount-3)/100 ) {
408                                                 addch('#');
409                                         }
410                                         else {
411                                                 addch('|');
412                                         }
413                                 }
414                         }
415                         else {
416                                 addch('|');
417                         }
418                 }
419                 
420                 // Footer
421                 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
422                 
423                 // Get input
424                 ch = getch();
425                 
426                 if( ch == '\x1B' ) {
427                         ch = getch();
428                         if( ch == '[' ) {
429                                 ch = getch();
430                                 
431                                 switch(ch)
432                                 {
433                                 case 'B':
434                                         //if( itemBase < giNumItems - (itemCount) )
435                                         //      itemBase ++;
436                                         if( currentItem < giNumItems - 1 )
437                                                 currentItem ++;
438                                         if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
439                                                 itemBase ++;
440                                         break;
441                                 case 'A':
442                                         //if( itemBase > 0 )
443                                         //      itemBase --;
444                                         if( currentItem > 0 )
445                                                 currentItem --;
446                                         if( itemBase + 1 > currentItem && itemBase > 0 )
447                                                 itemBase --;
448                                         break;
449                                 }
450                         }
451                         else {
452                                 
453                         }
454                 }
455                 else {
456                         switch(ch)
457                         {
458                         case '\n':
459                                 ret = currentItem;
460                                 break;
461                         case 'q':
462                                 ret = -1;       // -1: Return with no dispense
463                                 break;
464                         }
465                         
466                         // Check if the return value was changed
467                         if( ret != -2 ) break;
468                 }
469                 
470         }
471         
472         
473         // Leave
474         endwin();
475         return ret;
476 }
477
478 /**
479  * \brief Show item \a Index at (\a Col, \a Row)
480  * \note Part of the NCurses UI
481  */
482 void ShowItemAt(int Row, int Col, int Width, int Index)
483 {
484          int    _x, _y, times;
485         char    *name;
486          int    price;
487         
488         move( Row, Col );
489         
490         if( Index < 0 || Index >= giNumItems ) {
491                 name = "OOR";
492                 price = 0;
493         }
494         else {
495                 name = gaItems[Index].Desc;
496                 price = gaItems[Index].Price;
497         }
498
499         printw("%02i %s", Index, name);
500         
501         getyx(stdscr, _y, _x);
502         // Assumes max 4 digit prices
503         times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
504         while(times--)  addch(' ');
505         printw("%4i", price);
506 }
507
508 /**
509  * \brief Print a three-part string at the specified position (formatted)
510  * \note NCurses UI Helper
511  * 
512  * Prints \a Left on the left of the area, \a Right on the righthand side
513  * and \a Mid in the middle of the area. These are padded with \a Pad1
514  * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
515  * 
516  * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
517  * and the arguments to these are read in that order.
518  */
519 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
520         const char *Mid, char Pad2, const char *Right, ...)
521 {
522          int    lLen, mLen, rLen;
523          int    times;
524         
525         va_list args;
526         
527         // Get the length of the strings
528         va_start(args, Right);
529         lLen = vsnprintf(NULL, 0, Left, args);
530         mLen = vsnprintf(NULL, 0, Mid, args);
531         rLen = vsnprintf(NULL, 0, Right, args);
532         va_end(args);
533         
534         // Sanity check
535         if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
536                 return ;        // TODO: What to do?
537         }
538         
539         move(Row, Col);
540         
541         // Render strings
542         va_start(args, Right);
543         // - Left
544         {
545                 char    tmp[lLen+1];
546                 vsnprintf(tmp, lLen+1, Left, args);
547                 addstr(tmp);
548         }
549         // - Left padding
550         times = Width/2 - mLen/2 - lLen;
551         while(times--)  addch(Pad1);
552         // - Middle
553         {
554                 char    tmp[mLen+1];
555                 vsnprintf(tmp, mLen+1, Mid, args);
556                 addstr(tmp);
557         }
558         // - Right Padding
559         times = Width/2 - mLen/2 - rLen;
560         while(times--)  addch(Pad2);
561         // - Right
562         {
563                 char    tmp[rLen+1];
564                 vsnprintf(tmp, rLen+1, Right, args);
565                 addstr(tmp);
566         }
567 }
568
569 // ---------------------
570 // --- Coke Protocol ---
571 // ---------------------
572 int OpenConnection(const char *Host, int Port)
573 {
574         struct hostent  *host;
575         struct sockaddr_in      serverAddr;
576          int    sock;
577         
578         host = gethostbyname(Host);
579         if( !host ) {
580                 fprintf(stderr, "Unable to look up '%s'\n", Host);
581                 return -1;
582         }
583         
584         memset(&serverAddr, 0, sizeof(serverAddr));
585         
586         serverAddr.sin_family = AF_INET;        // IPv4
587         // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
588         serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
589         serverAddr.sin_port = htons(Port);
590         
591         sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
592         if( sock < 0 ) {
593                 fprintf(stderr, "Failed to create socket\n");
594                 return -1;
595         }
596         
597         #if USE_AUTOAUTH
598         {
599                 struct sockaddr_in      localAddr;
600                 memset(&localAddr, 0, sizeof(localAddr));
601                 localAddr.sin_family = AF_INET; // IPv4
602                 localAddr.sin_port = 1023;      // IPv4
603                 // Attempt to bind to low port for autoauth
604                 bind(sock, &localAddr, sizeof(localAddr));
605         }
606         #endif
607         
608         if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
609                 fprintf(stderr, "Failed to connect to server\n");
610                 return -1;
611         }
612         
613         return sock;
614 }
615
616 /**
617  * \brief Authenticate with the server
618  * \return Boolean Failure
619  */
620 int Authenticate(int Socket)
621 {
622         struct passwd   *pwd;
623         char    *buf;
624          int    responseCode;
625         char    salt[32];
626          int    i;
627         regmatch_t      matches[4];
628         
629         if( gbIsAuthenticated ) return 0;
630         
631         // Get user name
632         pwd = getpwuid( getuid() );
633         
634         // Attempt automatic authentication
635         sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
636         
637         // Check if it worked
638         buf = ReadLine(Socket);
639         
640         responseCode = atoi(buf);
641         switch( responseCode )
642         {
643         
644         case 200:       // Authenticated, return :)
645                 gbIsAuthenticated = 1;
646                 free(buf);
647                 return 0;
648         
649         case 401:       // Untrusted, attempt password authentication
650                 free(buf);
651                 
652                 sendf(Socket, "USER %s\n", pwd->pw_name);
653                 printf("Using username %s\n", pwd->pw_name);
654                 
655                 buf = ReadLine(Socket);
656                 
657                 // TODO: Get Salt
658                 // Expected format: 100 SALT <something> ...
659                 // OR             : 100 User Set
660                 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
661                 responseCode = atoi(buf);
662                 if( responseCode != 100 ) {
663                         fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
664                         free(buf);
665                         return -1;      // ERROR
666                 }
667                 
668                 // Check for salt
669                 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
670                         // Store it for later
671                         memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
672                         salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
673                 }
674                 free(buf);
675                 
676                 // Give three attempts
677                 for( i = 0; i < 3; i ++ )
678                 {
679                          int    ofs = strlen(pwd->pw_name)+strlen(salt);
680                         char    tmpBuf[42];
681                         char    tmp[ofs+20];
682                         char    *pass = getpass("Password: ");
683                         uint8_t h[20];
684                         
685                         // Create hash string
686                         // <username><salt><hash>
687                         strcpy(tmp, pwd->pw_name);
688                         strcat(tmp, salt);
689                         SHA1( (unsigned char*)pass, strlen(pass), h );
690                         memcpy(tmp+ofs, h, 20);
691                         
692                         // Hash all that
693                         SHA1( (unsigned char*)tmp, ofs+20, h );
694                         sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
695                                 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
696                                 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
697                                 );
698                 
699                         // Send password
700                         sendf(Socket, "PASS %s\n", tmpBuf);
701                         buf = ReadLine(Socket);
702                 
703                         responseCode = atoi(buf);
704                         // Auth OK?
705                         if( responseCode == 200 )       break;
706                         // Bad username/password
707                         if( responseCode == 401 )       continue;
708                         
709                         fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
710                         free(buf);
711                         return -1;
712                 }
713                 free(buf);
714                 if( i < 3 ) {
715                         gbIsAuthenticated = 1;
716                         return 0;
717                 }
718                 else
719                         return 2;       // 2 = Bad Password
720         
721         case 404:       // Bad Username
722                 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
723                 free(buf);
724                 return 1;
725         
726         default:
727                 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
728                 printf("%s\n", buf);
729                 free(buf);
730                 return -1;
731         }
732 }
733
734
735 /**
736  * \brief Fill the item information structure
737  * \return Boolean Failure
738  */
739 void PopulateItemList(int Socket)
740 {
741         char    *buf;
742          int    responseCode;
743         
744         char    *itemType, *itemStart;
745          int    count, i;
746         regmatch_t      matches[4];
747         
748         // Ask server for stock list
749         send(Socket, "ENUM_ITEMS\n", 11, 0);
750         buf = ReadLine(Socket);
751         
752         //printf("Output: %s\n", buf);
753         
754         responseCode = atoi(buf);
755         if( responseCode != 201 ) {
756                 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
757                 exit(-1);
758         }
759         
760         // - Get item list -
761         
762         // Expected format:
763         //  201 Items <count>
764         //  202 Item <count>
765         RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
766                 
767         itemType = &buf[ matches[2].rm_so ];    buf[ matches[2].rm_eo ] = '\0';
768         count = atoi( &buf[ matches[3].rm_so ] );
769                 
770         // Check array type
771         if( strcmp(itemType, "Items") != 0 ) {
772                 // What the?!
773                 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
774                         itemType);
775                 exit(-1);
776         }
777                 
778         itemStart = &buf[ matches[3].rm_eo ];
779         
780         free(buf);
781         
782         giNumItems = count;
783         gaItems = malloc( giNumItems * sizeof(tItem) );
784         
785         // Fetch item information
786         for( i = 0; i < giNumItems; i ++ )
787         {
788                 regmatch_t      matches[6];
789                 
790                 // Get item info
791                 buf = ReadLine(Socket);
792                 responseCode = atoi(buf);
793                 
794                 if( responseCode != 202 ) {
795                         fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
796                         exit(-1);
797                 }
798                 
799                 RunRegex(&gItemRegex, buf, 6, matches, "Malformed server response");
800                 
801                 buf[ matches[3].rm_eo ] = '\0';
802                 
803                 gaItems[i].Ident = strdup( buf + matches[3].rm_so );
804                 gaItems[i].Price = atoi( buf + matches[4].rm_so );
805                 gaItems[i].Desc = strdup( buf + matches[5].rm_so );
806                 
807                 free(buf);
808         }
809         
810         // Read end of list
811         buf = ReadLine(Socket);
812         responseCode = atoi(buf);
813                 
814         if( responseCode != 200 ) {
815                 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
816                         responseCode, buf
817                         );
818                 exit(-1);
819         }
820         
821         free(buf);
822 }
823
824 /**
825  * \brief Dispense an item
826  * \return Boolean Failure
827  */
828 int DispenseItem(int Socket, int ItemID)
829 {
830          int    ret, responseCode;
831         char    *buf;
832         
833         if( ItemID < 0 || ItemID > giNumItems ) return -1;
834         
835         // Dispense!
836         sendf(Socket, "DISPENSE %s\n", gaItems[ItemID].Ident);
837         buf = ReadLine(Socket);
838         
839         responseCode = atoi(buf);
840         switch( responseCode )
841         {
842         case 200:
843                 printf("Dispense OK\n");
844                 ret = 0;
845                 break;
846         case 401:
847                 printf("Not authenticated\n");
848                 ret = 1;
849                 break;
850         case 402:
851                 printf("Insufficient balance\n");
852                 ret = 1;
853                 break;
854         case 406:
855                 printf("Bad item name, bug report\n");
856                 ret = 1;
857                 break;
858         case 500:
859                 printf("Item failed to dispense, is the slot empty?\n");
860                 ret = 1;
861                 break;
862         case 501:
863                 printf("Dispense not possible (slot empty/permissions)\n");
864                 ret = 1;
865                 break;
866         default:
867                 printf("Unknown response code %i ('%s')\n", responseCode, buf);
868                 ret = -2;
869                 break;
870         }
871         
872         free(buf);
873         return ret;
874 }
875
876 /**
877  * \brief Alter a user's balance
878  */
879 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
880 {
881         char    *buf;
882          int    responseCode;
883         
884         sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
885         buf = ReadLine(Socket);
886         
887         responseCode = atoi(buf);
888         free(buf);
889         
890         switch(responseCode)
891         {
892         case 200:       return 0;       // OK
893         case 403:       // Not in coke
894                 fprintf(stderr, "You are not in coke (sucker)\n");
895                 return 1;
896         case 404:       // Unknown user
897                 fprintf(stderr, "Unknown user '%s'\n", Username);
898                 return 2;
899         default:
900                 fprintf(stderr, "Unknown response code %i\n", responseCode);
901                 return -1;
902         }
903         
904         return -1;
905 }
906
907 /**
908  * \brief Alter a user's balance
909  */
910 int Dispense_SetBalance(int Socket, const char *Username, int Ammount, const char *Reason)
911 {
912         char    *buf;
913          int    responseCode;
914         
915         sendf(Socket, "SET %s %i %s\n", Username, Ammount, Reason);
916         buf = ReadLine(Socket);
917         
918         responseCode = atoi(buf);
919         free(buf);
920         
921         switch(responseCode)
922         {
923         case 200:       return 0;       // OK
924         case 403:       // Not in coke
925                 fprintf(stderr, "You are not in coke (sucker)\n");
926                 return 1;
927         case 404:       // Unknown user
928                 fprintf(stderr, "Unknown user '%s'\n", Username);
929                 return 2;
930         default:
931                 fprintf(stderr, "Unknown response code %i\n", responseCode);
932                 return -1;
933         }
934         
935         return -1;
936 }
937
938 /**
939  * \brief Enumerate users
940  */
941 int Dispense_EnumUsers(int Socket)
942 {
943         char    *buf;
944          int    responseCode;
945          int    nUsers;
946         regmatch_t      matches[4];
947         
948         if( giMinimumBalance != INT_MIN ) {
949                 if( giMaximumBalance != INT_MAX ) {
950                         sendf(Socket, "ENUM_USERS %i %i\n", giMinimumBalance, giMaximumBalance);
951                 }
952                 else {
953                         sendf(Socket, "ENUM_USERS %i\n", giMinimumBalance);
954                 }
955         }
956         else {
957                 if( giMaximumBalance != INT_MAX ) {
958                         sendf(Socket, "ENUM_USERS - %i\n", giMaximumBalance);
959                 }
960                 else {
961                         sendf(Socket, "ENUM_USERS\n");
962                 }
963         }
964         buf = ReadLine(Socket);
965         responseCode = atoi(buf);
966         
967         switch(responseCode)
968         {
969         case 201:       break;  // Ok, length follows
970         
971         default:
972                 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
973                 free(buf);
974                 return -1;
975         }
976         
977         // Get count (not actually used)
978         RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
979         nUsers = atoi( buf + matches[3].rm_so );
980         printf("%i users returned\n", nUsers);
981         
982         // Free string
983         free(buf);
984         
985         // Read returned users
986         do {
987                 buf = ReadLine(Socket);
988                 responseCode = atoi(buf);
989                 
990                 if( responseCode != 202 )       break;
991                 
992                 _PrintUserLine(buf);
993                 free(buf);
994         } while(responseCode == 202);
995         
996         // Check final response
997         if( responseCode != 200 ) {
998                 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
999                 free(buf);
1000                 return -1;
1001         }
1002         
1003         free(buf);
1004         
1005         return 0;
1006 }
1007
1008 int Dispense_ShowUser(int Socket, const char *Username)
1009 {
1010         char    *buf;
1011          int    responseCode, ret;
1012         
1013         sendf(Socket, "USER_INFO %s\n", Username);
1014         buf = ReadLine(Socket);
1015         
1016         responseCode = atoi(buf);
1017         
1018         switch(responseCode)
1019         {
1020         case 202:
1021                 _PrintUserLine(buf);
1022                 ret = 0;
1023                 break;
1024         
1025         case 404:
1026                 printf("Unknown user '%s'\n", Username);
1027                 ret = 1;
1028                 break;
1029         
1030         default:
1031                 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1032                 ret = -1;
1033                 break;
1034         }
1035         
1036         free(buf);
1037         
1038         return ret;
1039 }
1040
1041 void _PrintUserLine(const char *Line)
1042 {
1043         regmatch_t      matches[6];
1044          int    bal;
1045         
1046         RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1047         // 3: Username
1048         // 4: Balance
1049         // 5: Flags
1050         {
1051                  int    usernameLen = matches[3].rm_eo - matches[3].rm_so;
1052                 char    username[usernameLen + 1];
1053                  int    flagsLen = matches[5].rm_eo - matches[5].rm_so;
1054                 char    flags[flagsLen + 1];
1055                 
1056                 memcpy(username, Line + matches[3].rm_so, usernameLen);
1057                 username[usernameLen] = '\0';
1058                 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1059                 flags[flagsLen] = '\0';
1060                 
1061                 bal = atoi(Line + matches[4].rm_so);
1062                 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, bal%100, flags);
1063         }
1064 }
1065
1066 int Dispense_AddUser(int Socket, const char *Username)
1067 {
1068         char    *buf;
1069          int    responseCode, ret;
1070         
1071         sendf(Socket, "USER_ADD %s\n", Username);
1072         
1073         buf = ReadLine(Socket);
1074         responseCode = atoi(buf);
1075         
1076         switch(responseCode)
1077         {
1078         case 200:
1079                 printf("User '%s' added\n", Username);
1080                 ret = 0;
1081                 break;
1082                 
1083         case 403:
1084                 printf("Only wheel can add users\n");
1085                 ret = 1;
1086                 break;
1087                 
1088         case 404:
1089                 printf("User '%s' already exists\n", Username);
1090                 ret = 0;
1091                 break;
1092         
1093         default:
1094                 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1095                 ret = -1;
1096                 break;
1097         }
1098         
1099         free(buf);
1100         
1101         return ret;
1102 }
1103
1104 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1105 {
1106         char    *buf;
1107          int    responseCode, ret;
1108         
1109         // TODO: Pre-validate the string
1110         
1111         sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1112         
1113         buf = ReadLine(Socket);
1114         responseCode = atoi(buf);
1115         
1116         switch(responseCode)
1117         {
1118         case 200:
1119                 printf("User '%s' updated\n", Username);
1120                 ret = 0;
1121                 break;
1122                 
1123         case 403:
1124                 printf("Only wheel can modify users\n");
1125                 ret = 1;
1126                 break;
1127         
1128         case 404:
1129                 printf("User '%s' does not exist\n", Username);
1130                 ret = 0;
1131                 break;
1132         
1133         case 407:
1134                 printf("Flag string is invalid\n");
1135                 ret = 0;
1136                 break;
1137         
1138         default:
1139                 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1140                 ret = -1;
1141                 break;
1142         }
1143         
1144         free(buf);
1145         
1146         return ret;
1147 }
1148
1149 // ---------------
1150 // --- Helpers ---
1151 // ---------------
1152 char *ReadLine(int Socket)
1153 {
1154         static char     buf[BUFSIZ];
1155         static int      bufPos = 0;
1156         static int      bufValid = 0;
1157          int    len;
1158         char    *newline = NULL;
1159          int    retLen = 0;
1160         char    *ret = malloc(10);
1161         
1162         #if DEBUG_TRACE_SERVER
1163         printf("ReadLine: ");
1164         #endif
1165         fflush(stdout);
1166         
1167         ret[0] = '\0';
1168         
1169         while( !newline )
1170         {
1171                 if( bufValid ) {
1172                         len = bufValid;
1173                 }
1174                 else {
1175                         len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1176                         buf[bufPos+len] = '\0';
1177                 }
1178                 
1179                 newline = strchr( buf+bufPos, '\n' );
1180                 if( newline ) {
1181                         *newline = '\0';
1182                 }
1183                 
1184                 retLen += strlen(buf+bufPos);
1185                 ret = realloc(ret, retLen + 1);
1186                 strcat( ret, buf+bufPos );
1187                 
1188                 if( newline ) {
1189                          int    newLen = newline - (buf+bufPos) + 1;
1190                         bufValid = len - newLen;
1191                         bufPos += newLen;
1192                 }
1193                 if( len + bufPos == BUFSIZ - 1 )        bufPos = 0;
1194         }
1195         
1196         #if DEBUG_TRACE_SERVER
1197         printf("%i '%s'\n", retLen, ret);
1198         #endif
1199         
1200         return ret;
1201 }
1202
1203 int sendf(int Socket, const char *Format, ...)
1204 {
1205         va_list args;
1206          int    len;
1207         
1208         va_start(args, Format);
1209         len = vsnprintf(NULL, 0, Format, args);
1210         va_end(args);
1211         
1212         {
1213                 char    buf[len+1];
1214                 va_start(args, Format);
1215                 vsnprintf(buf, len+1, Format, args);
1216                 va_end(args);
1217                 
1218                 #if DEBUG_TRACE_SERVER
1219                 printf("sendf: %s", buf);
1220                 #endif
1221                 
1222                 return send(Socket, buf, len, 0);
1223         }
1224 }
1225
1226 char *trim(char *string)
1227 {
1228          int    i;
1229         
1230         while( isspace(*string) )
1231                 string ++;
1232         
1233         for( i = strlen(string); i--; )
1234         {
1235                 if( isspace(string[i]) )
1236                         string[i] = '\0';
1237                 else
1238                         break;
1239         }
1240         
1241         return string;
1242 }
1243
1244 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1245 {
1246          int    ret;
1247         
1248         ret = regexec(regex, string, nMatches, matches, 0);
1249         if( ret ) {
1250                 size_t  len = regerror(ret, regex, NULL, 0);
1251                 char    errorStr[len];
1252                 regerror(ret, regex, errorStr, len);
1253                 printf("string = '%s'\n", string);
1254                 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1255                 exit(-1);
1256         }
1257         
1258         return ret;
1259 }
1260
1261 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1262 {
1263          int    ret = regcomp(regex, pattern, flags);
1264         if( ret ) {
1265                 size_t  len = regerror(ret, regex, NULL, 0);
1266                 char    errorStr[len];
1267                 regerror(ret, regex, errorStr, len);
1268                 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);
1269                 exit(-1);
1270         }
1271 }

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