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

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