Added finger support
[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 #define USE_AUTOAUTH    1
31
32 #define MAX_TXT_ARGS    5       // Maximum number of textual arguments (including command)
33 #define DISPENSE_MULTIPLE_MAX   20      // Maximum argument to -c
34
35 enum eUI_Modes
36 {
37         UI_MODE_BASIC,  // Non-NCurses
38         UI_MODE_STANDARD,
39         UI_MODE_DRINKSONLY,
40         UI_MODE_ALL,
41         NUM_UI_MODES
42 };
43
44 enum eReturnValues
45 {
46         RV_SUCCESS,
47         RV_BAD_ITEM,
48         RV_INVALID_USER,
49         RV_PERMISSIONS,
50         RV_ARGUMENTS,
51         RV_BALANCE,
52         RV_SERVER_ERROR,        // Generic for 5xx codes
53         RV_UNKNOWN_ERROR = -1,
54         RV_SOCKET_ERROR = -2,
55         RV_UNKNOWN_RESPONSE = -3,
56 };
57
58 // === TYPES ===
59 typedef struct sItem {
60         char    *Type;
61          int    ID;
62          int    Status; // 0: Availiable, 1: Sold out, -1: Error
63         char    *Desc;
64          int    Price;
65 }       tItem;
66
67 // === PROTOTYPES ===
68 void    ShowUsage(void);
69  int    main(int argc, char *argv[]);
70 // --- GUI ---
71  int    ShowNCursesUI(void);
72  int    ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted);
73 void    PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
74 // --- Coke Server Communication ---
75  int    OpenConnection(const char *Host, int Port);
76  int    Authenticate(int Socket);
77  int    GetUserBalance(int Socket);
78 void    PopulateItemList(int Socket);
79  int    Dispense_ItemInfo(int Socket, const char *Type, int ID);
80  int    DispenseItem(int Socket, const char *Type, int ID);
81  int    Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
82  int    Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason);
83  int    Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
84  int    Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride);
85  int    Dispense_Donate(int Socket, int Ammount, const char *Reason);
86  int    Dispense_EnumUsers(int Socket);
87  int    Dispense_ShowUser(int Socket, const char *Username);
88 void    _PrintUserLine(const char *Line);
89  int    Dispense_AddUser(int Socket, const char *Username);
90  int    Dispense_SetUserType(int Socket, const char *Username, const char *TypeString, const char *Reason);
91  int    Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName);
92 // --- Helpers ---
93 char    *ReadLine(int Socket);
94  int    sendf(int Socket, const char *Format, ...);
95 char    *trim(char *string);
96  int    RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
97 void    CompileRegex(regex_t *regex, const char *pattern, int flags);
98
99 // === GLOBALS ===
100 char    *gsDispenseServer = "merlo.ucc.gu.uwa.edu.au";
101  int    giDispensePort = 11020;
102
103 tItem   *gaItems;
104  int    giNumItems;
105 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex, gUserItemIdentRegex;
106  int    gbIsAuthenticated = 0;
107
108 char    *gsItemPattern; //!< Item pattern
109 char    *gsEffectiveUser;       //!< '-u' Dispense as another user
110
111  int    giUIMode = UI_MODE_STANDARD;
112  int    gbDryRun = 0;   //!< '-n' Read-only
113  int    gbDisallowSelectWithoutBalance = 1;     //!< Don't allow items to be hilighted if not affordable
114
115  int    giMinimumBalance = INT_MIN;     //!< '-m' Minumum balance for `dispense acct`
116  int    giMaximumBalance = INT_MAX;     //!< '-M' Maximum balance for `dispense acct`
117
118  char   *gsUserName;    //!< User that dispense will happen as
119 char    *gsUserFlags;   //!< User's flag set
120  int    giUserBalance = -1;     //!< User balance (set by Authenticate)
121  int    giDispenseCount = 1;    //!< Number of dispenses to do
122
123 char    *gsTextArgs[MAX_TXT_ARGS];
124  int    giTextArgc;
125
126 // === CODE ===
127 void ShowUsage(void)
128 {
129         printf( "Usage:\n" );
130         if( giTextArgc == 0 )
131                 printf(
132                         "  == Everyone ==\n"
133                         "    dispense\n"
134                         "        Show interactive list\n"
135                         "    dispense <name>|<index>|<itemid>\n"
136                         "        Dispense named item (<name> matches if it is a unique prefix)\n"
137                         "    dispense finger\n"
138                         "        Show the finger output\n"
139                         );
140         if( giTextArgc == 0 || strcmp(gsTextArgs[0], "give") == 0 )
141                 printf(
142                         "    dispense give <user> <amount> \"<reason>\"\n"
143                         "        Give money to another user\n"
144                         );
145         
146         if( giTextArgc == 0 || strcmp(gsTextArgs[0], "donate") == 0 )
147                 printf(
148                         "    dispense donate <amount> \"<reason>\"\n"
149                         "        Donate to the club\n"
150                         );
151         if( giTextArgc == 0 || strcmp(gsTextArgs[0], "iteminfo") == 0 )
152                 printf(
153                         "    dispense iteminfo <itemid>\n"
154                         "        Get the name and price for an item\n"
155                         );
156 //      if( giTextArgc == 0 || strcmp(gsTextArgs[0], "enumitems") == 0 )
157 //              printf(
158 //                      "    dispense enumitems\n"
159 //                      "        List avaliable items\n"
160 //                      );
161         if( giTextArgc == 0 )
162                 printf("  == Coke members == \n");
163         if( giTextArgc == 0 || strcmp(gsTextArgs[0], "acct") == 0 )
164                 printf(
165                         "    dispense acct [<user>]\n"
166                         "        Show user balances\n"
167                         "    dispense acct <user> [+-]<amount> \"<reason>\"\n"
168                         "        Alter a account value\n"
169                         "    dispense acct <user> =<amount> \"<reason>\"\n"
170                         "        Set an account balance\n"
171                         );
172         if( giTextArgc == 0 || strcmp(gsTextArgs[0], "refund") == 0 )
173                 printf(
174                         "    dispense refund <user> <itemid> [<price>]\n"
175                         "        Refund an item to a user (with optional price override)\n"
176                         "        Item IDs can be seen in the cokelog (in the brackets after the item name)\n"
177                         "        e.g. coke:6 for a coke, snack:33 for slot 33 of the snack machine\n"
178                         );
179         if( giTextArgc == 0 || strcmp(gsTextArgs[0], "slot") == 0 )
180                 printf(
181                         "    dispense slot <itemid> <price> <name>\n"
182                         "        Rename/Re-price a slot\n"
183                         );
184         if( giTextArgc == 0 )
185                 printf("  == Dispense administrators ==\n");
186         if( giTextArgc == 0 || strcmp(gsTextArgs[0], "user") == 0 )
187                 printf(
188                         "    dispense user add <user>\n"
189                         "        Create new account\n"
190                         "    dispense user type <user> <flags> <reason>\n"
191                         "        Alter a user's flags\n"
192                         "        <flags> is a comma-separated list of user, coke, admin, internal or disabled\n"
193                         "        Flags are removed by preceding the name with '-' or '!'\n"
194                         );
195         if( giTextArgc == 0 )
196                 printf( "\n"
197                         "General Options:\n"
198                         "    -c <count>\n"
199                         "        Dispense multiple times\n"
200                         "    -u <username>\n"
201                         "        Set a different user (Coke members only)\n"
202                         "    -h / -?\n"
203                         "        Show help text\n"
204                         "    -G\n"
205                         "        Use simple textual interface (instead of ncurses)\n"
206                         "    -n\n"
207                         "        Dry run - Do not actually do dispenses\n"
208                         "    -m <min balance>\n"
209                         "    -M <max balance>\n"
210                         "        Set the Maximum/Minimum balances shown in `dispense acct`\n"
211                         "Definitions:\n"
212                         "    <itemid>\n"
213                         "        Item ID of the form <type>:<num> where <type> is a non-empty string of alpha-numeric characters, and <num> is a non-negative integer\n"
214 //                      "    <user>\n"
215 //                      "        Account name\n"
216                         );
217 }
218
219 int main(int argc, char *argv[])
220 {
221          int    sock;
222          int    i, ret = 0;
223         char    buffer[BUFSIZ];
224         
225         gsTextArgs[0] = "";
226
227         // -- Create regular expressions
228         // > Code Type Count ...
229         CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED);     //
230         // > Code Type Ident Status Price Desc
231         CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z]+):([0-9]+)\\s+(avail|sold|error)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
232         // > Code 'SALT' salt
233         CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
234         // > Code 'User' Username Balance Flags
235         CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
236         // > Item Ident
237         CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
238
239         // Parse Arguments
240         for( i = 1; i < argc; i ++ )
241         {
242                 char    *arg = argv[i];
243                 
244                 if( arg[0] == '-' )
245                 {                       
246                         switch(arg[1])
247                         {
248                         case 'h':
249                         case '?':
250                                 ShowUsage();
251                                 return 0;
252                                         
253                         case 'c':
254                                 if( i + 1 >= argc ) {
255                                         fprintf(stderr, "%s: -c takes an argument\n", argv[0]);
256                                         ShowUsage();
257                                         return -1;
258                                 }
259                                 giDispenseCount = atoi(argv[++i]);
260                                 if( giDispenseCount < 1 || giDispenseCount > DISPENSE_MULTIPLE_MAX ) {
261                                         fprintf(stderr, "Sorry, only 1-20 can be passed to -c (safety)\n");
262                                         return -1;
263                                 }
264                                 
265                                 break ;
266         
267                         case 'm':       // Minimum balance
268                                 if( i + 1 >= argc ) {
269                                         fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
270                                         ShowUsage();
271                                         return RV_ARGUMENTS;
272                                 }
273                                 giMinimumBalance = atoi(argv[++i]);
274                                 break;
275                         case 'M':       // Maximum balance
276                                 if( i + 1 >= argc ) {
277                                         fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
278                                         ShowUsage();
279                                         return RV_ARGUMENTS;
280                                 }
281                                 giMaximumBalance = atoi(argv[++i]);
282                                 break;
283                         
284                         case 'u':       // Override User
285                                 if( i + 1 >= argc ) {
286                                         fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
287                                         ShowUsage();
288                                         return RV_ARGUMENTS;
289                                 }
290                                 gsEffectiveUser = argv[++i];
291                                 break;
292                         
293                         case 'H':       // Override remote host
294                                 if( i + 1 >= argc ) {
295                                         fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
296                                         ShowUsage();
297                                         return RV_ARGUMENTS;
298                                 }
299                                 gsDispenseServer = argv[++i];
300                                 break;
301                         case 'P':       // Override remote port
302                                 if( i + 1 >= argc ) {
303                                         fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
304                                         ShowUsage();
305                                         return RV_ARGUMENTS;
306                                 }
307                                 giDispensePort = atoi(argv[++i]);
308                                 break;
309                         
310                         // Set slot name/price
311                         case 's':
312                                 if( giTextArgc != 0 ) {
313                                         fprintf(stderr, "%s: -s must appear before other arguments\n", argv[0]);
314                                         ShowUsage();
315                                         return RV_ARGUMENTS;
316                                 }
317                                 gsTextArgs[0] = "slot"; // HACK!!
318                                 giTextArgc ++;
319                                 break;
320                         
321                         case 'G':       // Don't use GUI
322                                 giUIMode = UI_MODE_BASIC;
323                                 break;
324                         case 'D':       // Drinks only
325                                 giUIMode = UI_MODE_DRINKSONLY;
326                                 break;
327                         case 'n':       // Dry Run / read-only
328                                 gbDryRun = 1;
329                                 break;
330                         case '-':
331                                 if( strcmp(argv[i], "--help") == 0 ) {
332                                         ShowUsage();
333                                         return 0;
334                                 }
335                                 else if( strcmp(argv[i], "--dry-run") == 0 ) {
336                                         gbDryRun = 1;
337                                 }
338                                 else if( strcmp(argv[i], "--drinks-only") == 0 ) {
339                                         giUIMode = UI_MODE_DRINKSONLY;
340                                 }
341                                 else if( strcmp(argv[i], "--can-select-all") == 0 ) {
342                                         gbDisallowSelectWithoutBalance = 0;
343                                 }
344                                 else {
345                                         fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
346                                         ShowUsage();
347                                         return RV_ARGUMENTS;
348                                 }
349                                 break;
350                         default:
351                                 // The first argument is not allowed to begin with 'i'
352                                 // (catches most bad flags)
353                                 if( giTextArgc == 0 ) {
354                                         fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
355                                         ShowUsage();
356                                         return RV_ARGUMENTS;
357                                 }
358                                 if( giTextArgc == MAX_TXT_ARGS )
359                                 {
360                                         fprintf(stderr, "ERROR: Too many arguments\n");
361                                         return RV_ARGUMENTS;
362                                 }
363                                 gsTextArgs[giTextArgc++] = argv[i];
364                                 break;
365                         }
366
367                         continue;
368                 }
369
370                 if( giTextArgc == MAX_TXT_ARGS )
371                 {
372                         fprintf(stderr, "ERROR: Too many arguments\n");
373                         return RV_ARGUMENTS;
374                 }
375         
376                 gsTextArgs[giTextArgc++] = argv[i];
377         
378         }
379
380         //
381         // `dispense finger`
382         // -
383         if( strcmp(gsTextArgs[0], "finger") == 0 )
384         {
385                 // Connect to server
386                 sock = OpenConnection(gsDispenseServer, giDispensePort);
387                 if( sock < 0 )  return RV_SOCKET_ERROR;
388
389                 // Get items
390                 PopulateItemList(sock);
391
392                 // Only get coke slot statuses
393                 for( i = 0; i <= 6; i ++ )
394                 {
395                         const char *status;
396                         switch(gaItems[i].Status)
397                         {
398                         case 0: status = "Avail";       break;
399                         case 1: status = "Sold ";       break;
400                         default:
401                                 status = "Error";
402                                 break;
403                         }
404                         printf("%i - %s %3i %s\n", gaItems[i].ID, status, gaItems[i].Price, gaItems[i].Desc);
405                         
406                 }
407
408                 return 0;
409         }
410
411         //
412         // `dispense acct`
413         // - 
414         if( strcmp(gsTextArgs[0], "acct") == 0 )
415         {
416                 // Connect to server
417                 sock = OpenConnection(gsDispenseServer, giDispensePort);
418                 if( sock < 0 )  return RV_SOCKET_ERROR;
419                 // List accounts?
420                 if( giTextArgc == 1 ) {
421                         ret = Dispense_EnumUsers(sock);
422                         close(sock);
423                         return ret;
424                 }
425                         
426                 // gsTextArgs[1]: Username
427                 
428                 // Alter account?
429                 if( giTextArgc != 2 )
430                 {
431                         if( giTextArgc != 4 ) {
432                                 fprintf(stderr, "`dispense acct` requires a reason\n");
433                                 ShowUsage();
434                                 return RV_ARGUMENTS;
435                         }
436                         
437                         // Authentication required
438                         ret = Authenticate(sock);
439                         if(ret) return ret;
440                         
441                         // gsTextArgs[1]: Username
442                         // gsTextArgs[2]: Ammount
443                         // gsTextArgs[3]: Reason
444                         
445                         if( gsTextArgs[2][0] == '=' ) {
446                                 // Set balance
447                                 if( gsTextArgs[2][1] != '0' && atoi(gsTextArgs[2]+1) == 0 ) {
448                                         fprintf(stderr, "Error: Invalid balance to be set\n");
449                                         exit(1);
450                                 }
451                                 
452                                 ret = Dispense_SetBalance(sock, gsTextArgs[1], atoi(gsTextArgs[2]+1), gsTextArgs[3]);
453                         }
454                         else {
455                                 // Alter balance
456                                 ret = Dispense_AlterBalance(sock, gsTextArgs[1], atoi(gsTextArgs[2]), gsTextArgs[3]);
457                         }
458                 }
459                 // On error, quit
460                 if( ret ) {
461                         close(sock);
462                         return ret;
463                 }
464                 
465                 // Show user information
466                 ret = Dispense_ShowUser(sock, gsTextArgs[1]);
467                 
468                 close(sock);
469                 return ret;
470         }
471         //
472         // `dispense give`
473         // - "Here, have some money."
474         else if( strcmp(gsTextArgs[0], "give") == 0 )
475         {
476                 if( giTextArgc != 4 ) {
477                         fprintf(stderr, "`dispense give` takes three arguments\n");
478                         ShowUsage();
479                         return RV_ARGUMENTS;
480                 }
481                 
482                 // gsTextArgs[1]: Destination
483                 // gsTextArgs[2]: Ammount
484                 // gsTextArgs[3]: Reason
485                 
486                 // Connect to server
487                 sock = OpenConnection(gsDispenseServer, giDispensePort);
488                 if( sock < 0 )  return RV_SOCKET_ERROR;
489                 
490                 // Authenticate
491                 ret = Authenticate(sock);
492                 if(ret) return ret;
493                 
494                 ret = Dispense_Give(sock, gsTextArgs[1], atoi(gsTextArgs[2]), gsTextArgs[3]);
495
496                 close(sock);
497         
498                 return ret;
499         }
500         // 
501         // `dispense user`
502         // - User administration (Admin Only)
503         if( strcmp(gsTextArgs[0], "user") == 0 )
504         {
505                 // Check argument count
506                 if( giTextArgc == 1 ) {
507                         fprintf(stderr, "Error: `dispense user` requires arguments\n");
508                         ShowUsage();
509                         return RV_ARGUMENTS;
510                 }
511                 
512                 // Connect to server
513                 sock = OpenConnection(gsDispenseServer, giDispensePort);
514                 if( sock < 0 )  return RV_SOCKET_ERROR;
515                 
516                 // Attempt authentication
517                 ret = Authenticate(sock);
518                 if(ret) return ret;
519                 
520                 // Add new user?
521                 if( strcmp(gsTextArgs[1], "add") == 0 )
522                 {
523                         if( giTextArgc != 3 ) {
524                                 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
525                                 ShowUsage();
526                                 return RV_ARGUMENTS;
527                         }
528                         
529                         ret = Dispense_AddUser(sock, gsTextArgs[2]);
530                 }
531                 // Update a user
532                 else if( strcmp(gsTextArgs[1], "type") == 0 || strcmp(gsTextArgs[1], "flags") == 0 )
533                 {
534                         if( giTextArgc < 4 || giTextArgc > 5 ) {
535                                 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
536                                 ShowUsage();
537                                 return RV_ARGUMENTS;
538                         }
539                         
540                         if( giTextArgc == 4 )
541                                 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], "");
542                         else
543                                 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], gsTextArgs[4]);
544                 }
545                 else
546                 {
547                         fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
548                         ShowUsage();
549                         return RV_ARGUMENTS;
550                 }
551                 close(sock);
552                 return ret;
553         }
554         // Donation!
555         else if( strcmp(gsTextArgs[0], "donate") == 0 )
556         {
557                 // Check argument count
558                 if( giTextArgc != 3 ) {
559                         fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
560                         ShowUsage();
561                         return RV_ARGUMENTS;
562                 }
563                 
564                 // Connect to server
565                 sock = OpenConnection(gsDispenseServer, giDispensePort);
566                 if( sock < 0 )  return RV_SOCKET_ERROR;
567                 
568                 // Attempt authentication
569                 ret = Authenticate(sock);
570                 if(ret) return ret;
571                 
572                 // Do donation
573                 ret = Dispense_Donate(sock, atoi(gsTextArgs[1]), gsTextArgs[2]);
574                                 
575                 close(sock);
576
577                 return ret;
578         }
579         // Refund an item
580         else if( strcmp(gsTextArgs[0], "refund") == 0 )
581         {
582                  int     price = 0;
583                 // Check argument count
584                 if( giTextArgc != 3 && giTextArgc != 4 ) {
585                         fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
586                         ShowUsage();
587                         return RV_ARGUMENTS;
588                 }
589         
590                 // Connect to server
591                 sock = OpenConnection(gsDispenseServer, giDispensePort);
592                 if(sock < 0)    return RV_SOCKET_ERROR; 
593
594                 // Attempt authentication
595                 ret = Authenticate(sock);
596                 if(ret) return ret;
597
598                 if( giTextArgc == 4 ) {
599                         price = atoi(gsTextArgs[3]);
600                         if( price <= 0 ) {
601                                 fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
602                                 return RV_ARGUMENTS;
603                         }
604                 }
605
606                 // Username, Item, cost
607                 ret = Dispense_Refund(sock, gsTextArgs[1], gsTextArgs[2], price);
608
609                 // TODO: More
610                 close(sock);
611                 return ret;
612         }
613         // Query an item price
614         else if( strcmp(gsTextArgs[0], "iteminfo") == 0 )
615         {
616                 regmatch_t matches[3];
617                 char    *type;
618                  int    id;
619                 // Check argument count
620                 if( giTextArgc != 2 ) {
621                         fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
622                         ShowUsage();
623                         return RV_ARGUMENTS;
624                 }
625                 // Parse item ID
626                 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
627                         fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
628                         return RV_ARGUMENTS;
629                 }
630                 type = gsTextArgs[1] + matches[1].rm_so;
631                 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
632                 id = atoi( gsTextArgs[1] + matches[2].rm_so );
633
634                 sock = OpenConnection(gsDispenseServer, giDispensePort);
635                 if( sock < 0 )  return RV_SOCKET_ERROR;
636                 
637                 ret = Dispense_ItemInfo(sock, type, id);
638                 close(sock);
639                 return ret;
640         }
641         // Set slot
642         else if( strcmp(gsTextArgs[0], "slot") == 0 )
643         {
644                 regmatch_t matches[3];
645                 char    *item_type, *newname;
646                  int    item_id, price;
647                 
648                 // Check arguments
649                 if( giTextArgc != 4 ) {
650                         fprintf(stderr, "Error: `dispense slot` takes three arguments\n");
651                         ShowUsage();
652                         return RV_ARGUMENTS;
653                 }
654                 
655                 // Parse arguments
656                 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
657                         fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
658                         return RV_ARGUMENTS;
659                 }
660                 item_type = gsTextArgs[1] + matches[1].rm_so;
661                 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
662                 item_id = atoi( gsTextArgs[1] + matches[2].rm_so );
663
664                 // - Price
665                 price = atoi( gsTextArgs[2] );
666                 if( price <= 0 && gsTextArgs[2][0] != '0' ) {
667                         fprintf(stderr, "Error: Invalid price passed (must be >= 0)\n");
668                         return RV_ARGUMENTS;
669                 }
670                 
671                 // - New name
672                 newname = gsTextArgs[3];
673                 // -- Sanity
674                 {
675                         char *pos;
676                         for( pos = newname; *pos; pos ++ )
677                         {
678                                 if( !isalnum(*pos) && *pos != ' ' ) {
679                                         fprintf(stderr, "Error: You should only have letters, numbers and spaces in an item name\n");
680                                         return RV_ARGUMENTS;
681                                 }
682                         }
683                 }
684                 
685                 // Connect & Authenticate
686                 sock = OpenConnection(gsDispenseServer, giDispensePort);
687                 if( sock < 0 )  return RV_SOCKET_ERROR;
688                 ret = Authenticate(sock);
689                 if(ret) return ret;
690                 // Update the slot
691                 ret = Dispense_SetItem(sock, item_type, item_id, price, newname);
692                 
693                 close(sock);
694                 return ret;
695         }
696         // Item name / pattern
697         else
698         {
699                 gsItemPattern = gsTextArgs[0];
700         }
701         
702         // Connect to server
703         sock = OpenConnection(gsDispenseServer, giDispensePort);
704         if( sock < 0 )  return RV_SOCKET_ERROR;
705
706         // Get the user's balance
707         ret = GetUserBalance(sock);
708         if(ret) return ret;
709
710         // Get items
711         PopulateItemList(sock);
712         
713         // Disconnect from server
714         close(sock);
715         
716         if( gsItemPattern && gsItemPattern[0] )
717         {
718                 regmatch_t matches[3];
719                 // Door (hard coded)
720                 if( strcmp(gsItemPattern, "door") == 0 )
721                 {
722                         // Connect, Authenticate, dispense and close
723                         sock = OpenConnection(gsDispenseServer, giDispensePort);
724                         if( sock < 0 )  return RV_SOCKET_ERROR;
725                         ret = Authenticate(sock);
726                         if(ret) return ret;
727                         ret = DispenseItem(sock, "door", 0);
728                         close(sock);
729                         return ret;
730                 }
731                 // Item id (<type>:<num>)
732                 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
733                 {
734                         char    *ident;
735                          int    id;
736                         
737                         // Get and finish ident
738                         ident = gsItemPattern + matches[1].rm_so;
739                         gsItemPattern[matches[1].rm_eo] = '\0';
740                         // Get ID
741                         id = atoi( gsItemPattern + matches[2].rm_so );
742                         
743                         // Connect, Authenticate, dispense and close
744                         sock = OpenConnection(gsDispenseServer, giDispensePort);
745                         if( sock < 0 )  return RV_SOCKET_ERROR;
746                         
747                         Dispense_ItemInfo(sock, ident, id);
748                         
749                         ret = Authenticate(sock);
750                         if(ret) return ret;
751                         ret = DispenseItem(sock, ident, id);
752                         close(sock);
753                         return ret;
754                 }
755                 // Item number (6 = coke)
756                 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
757                 {
758                         i = atoi(gsItemPattern);
759                 }
760                 // Item prefix
761                 else
762                 {
763                          int    j;
764                          int    best = -1;
765                         for( i = 0; i < giNumItems; i ++ )
766                         {
767                                 // Prefix match (with case-insensitive match)
768                                 for( j = 0; gsItemPattern[j]; j ++ )
769                                 {
770                                         if( gaItems[i].Desc[j] == gsItemPattern[j] )
771                                                 continue;
772                                         if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
773                                                 continue;
774                                         break;
775                                 }
776                                 // Check if the prefix matched
777                                 if( gsItemPattern[j] != '\0' )
778                                         continue;
779                                 
780                                 // Prefect match
781                                 if( gaItems[i].Desc[j] == '\0' ) {
782                                         best = i;
783                                         break;
784                                 }
785                                 
786                                 // Only one match allowed
787                                 if( best == -1 ) {
788                                         best = i;
789                                 }
790                                 else {
791                                         // TODO: Allow ambiguous matches?
792                                         // or just print a wanrning
793                                         printf("Warning - Ambiguous pattern, stopping\n");
794                                         return RV_BAD_ITEM;
795                                 }
796                         }
797                         
798                         // Was a match found?
799                         if( best == -1 )
800                         {
801                                 fprintf(stderr, "No item matches the passed string\n");
802                                 return RV_BAD_ITEM;
803                         }
804                         
805                         i = best;
806                 }
807         }
808         else if( giUIMode != UI_MODE_BASIC )
809         {
810                 i = ShowNCursesUI();
811         }
812         else
813         {
814                 // Very basic dispense interface
815                 for( i = 0; i < giNumItems; i ++ ) {
816                         // Add a separator
817                         if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
818                                 printf("   ---\n");
819                         
820                         printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
821                                 gaItems[i].Price, gaItems[i].Desc);
822                 }
823                 printf(" q Quit\n");
824                 for(;;)
825                 {
826                         char    *buf;
827                         
828                         i = -1;
829                         
830                         fgets(buffer, BUFSIZ, stdin);
831                         
832                         buf = trim(buffer);
833                         
834                         if( buf[0] == 'q' )     break;
835                         
836                         i = atoi(buf);
837                         
838                         if( i != 0 || buf[0] == '0' )
839                         {
840                                 if( i < 0 || i >= giNumItems ) {
841                                         printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
842                                         continue;
843                                 }
844                                 break;
845                         }
846                 }
847         }
848         
849         
850         // Check for a valid item ID
851         if( i >= 0 )
852         {
853                  int j;
854                 // Connect, Authenticate, dispense and close
855                 sock = OpenConnection(gsDispenseServer, giDispensePort);
856                 if( sock < 0 )  return RV_SOCKET_ERROR;
857                         
858                 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
859                 if(ret) return ret;
860                 
861                 ret = Authenticate(sock);
862                 if(ret) return ret;
863                 
864                 for( j = 0; j < giDispenseCount; j ++ ) {
865                         ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
866                         if( ret )       break;
867                 }
868                 if( j > 1 ) {
869                         printf("%i items dispensed\n", j);
870                 }
871                 Dispense_ShowUser(sock, gsUserName);
872                 close(sock);
873
874         }
875
876         return ret;
877 }
878
879 // -------------------
880 // --- NCurses GUI ---
881 // -------------------
882 /**
883  * \brief Render the NCurses UI
884  */
885 int ShowNCursesUI(void)
886 {
887          int    ch;
888          int    i, times;
889          int    xBase, yBase;
890         const int       displayMinWidth = 50;
891         char    *titleString = "Dispense";
892          int    items_in_view;
893          int    maxItemIndex;
894          int    itemBase = 0;
895          int    currentItem;
896          int    ret = -2;       // -2: Used for marking "no return yet"
897         
898         char    balance_str[5+1+2+1];   // If $9999.99 is too little, something's wrong
899         char    *username;
900         struct passwd *pwd;
901          
902          int    height, width;
903          
904         // Get Username
905         if( gsEffectiveUser )
906                 username = gsEffectiveUser;
907         else {
908                 pwd = getpwuid( getuid() );
909                 username = pwd->pw_name;
910         }
911         // Get balance
912         snprintf(balance_str, sizeof(balance_str), "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
913         
914         // Enter curses mode
915         initscr();
916         cbreak(); noecho();
917         
918         // Get max index
919         maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
920         // Get item count per screen
921         // - 6: randomly chosen (Need at least 3)
922         items_in_view = LINES - 6;
923         if( items_in_view > maxItemIndex )
924                 items_in_view = maxItemIndex;
925         // Get first index
926         currentItem = 0;
927         while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
928                 currentItem ++;
929         
930         
931         // Get dimensions
932         height = items_in_view + 3;
933         width = displayMinWidth;
934         
935         // Get positions
936         xBase = COLS/2 - width/2;
937         yBase = LINES/2 - height/2;
938         
939         for( ;; )
940         {
941                 // Header
942                 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
943                 
944                 // Items
945                 for( i = 0; i < items_in_view; i ++ )
946                 {
947                          int    pos = 0;
948                         
949                         move( yBase + 1 + i, xBase );
950                         printw("| ");
951                         
952                         pos += 2;
953                         
954                         // Check for the '...' row
955                         // - Oh god, magic numbers!
956                         if( (i == 0 && itemBase > 0)
957                          || (i == items_in_view - 1 && itemBase < maxItemIndex - items_in_view) )
958                         {
959                                 printw("     ...");     pos += 8;
960                                 times = (width - pos) - 1;
961                                 while(times--)  addch(' ');
962                         }
963                         // Show an item
964                         else {
965                                 ShowItemAt(
966                                         yBase + 1 + i, xBase + pos,     // Position
967                                         (width - pos) - 3,      // Width
968                                         itemBase + i,   // Index
969                                         !!(currentItem == itemBase + i) // Hilighted
970                                         );
971                                 printw("  ");
972                         }
973                         
974                         // Scrollbar (if needed)
975                         if( maxItemIndex > items_in_view ) {
976                                 if( i == 0 ) {
977                                         addch('A');
978                                 }
979                                 else if( i == items_in_view - 1 ) {
980                                         addch('V');
981                                 }
982                                 else {
983                                          int    percentage = itemBase * 100 / (maxItemIndex-items_in_view);
984                                         if( i-1 == percentage*(items_in_view-3)/100 ) {
985                                                 addch('#');
986                                         }
987                                         else {
988                                                 addch('|');
989                                         }
990                                 }
991                         }
992                         else {
993                                 addch('|');
994                         }
995                 }
996                 
997                 // Footer
998                 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
999                 
1000                 // User line
1001                 // - Username, balance, flags
1002                 PrintAlign(yBase+height-1, xBase+1, width-2,
1003                         username, ' ', balance_str, ' ', gsUserFlags);
1004                 
1005                 
1006                 // Get input
1007                 ch = getch();
1008                 
1009                 if( ch == '\x1B' ) {
1010                         ch = getch();
1011                         if( ch == '[' ) {
1012                                 ch = getch();
1013                                 
1014                                 switch(ch)
1015                                 {
1016                                 case 'B':
1017                                         currentItem ++;
1018                                         // Skip over spacers
1019                                         while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
1020                                                 currentItem ++;
1021                                         
1022                                         if( currentItem >= maxItemIndex ) {
1023                                                 currentItem = 0;
1024                                                 // Skip over spacers
1025                                                 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
1026                                                         currentItem ++;
1027                                         }
1028                                         break;
1029                                 case 'A':
1030                                         currentItem --;
1031                                         // Skip over spacers
1032                                         while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
1033                                                 currentItem --;
1034                                         
1035                                         if( currentItem < 0 ) {
1036                                                 currentItem = maxItemIndex - 1;
1037                                                 // Skip over spacers
1038                                                 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
1039                                                         currentItem --;
1040                                         }
1041                                         break;
1042                                 }
1043                         }
1044                         else {
1045                                 
1046                         }
1047                 
1048                         // Scroll only if needed
1049                         if( items_in_view < maxItemIndex )
1050                         {
1051                                 // - If the current item is above the second item shown, and we're not at the top
1052                                 if( currentItem < itemBase + 2 && itemBase > 0 ) {
1053                                         itemBase = currentItem - 2;
1054                                         if(itemBase < 0)        itemBase = 0;
1055                                 }
1056                                 // - If the current item is below the second item show, and we're not at the bottom
1057                                 if( currentItem > itemBase + items_in_view - 2 && itemBase + items_in_view < maxItemIndex ) {
1058                                         itemBase = currentItem - items_in_view + 2;
1059                                         if( itemBase > maxItemIndex - items_in_view )
1060                                                 itemBase = maxItemIndex - items_in_view;
1061                                 }
1062                         }
1063                 }
1064                 else {
1065                         switch(ch)
1066                         {
1067                         case '\n':
1068                                 ret = ShowItemAt(0, 0, 0, currentItem, 0);
1069                                 break;
1070                         case 0x1b:      // Escape
1071                         case 'q':
1072                                 ret = -1;       // -1: Return with no dispense
1073                                 break;
1074                         }
1075                         
1076                         // Check if the return value was changed
1077                         if( ret != -2 ) break;
1078                 }
1079                 
1080         }
1081         
1082         
1083         // Leave
1084         endwin();
1085         return ret;
1086 }
1087
1088 /**
1089  * \brief Show item \a Index at (\a Col, \a Row)
1090  * \return Dispense index of item
1091  * \note Part of the NCurses UI
1092  */
1093 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
1094 {
1095         char    *name = NULL;
1096          int    price = 0;
1097          int    status = -1;
1098         
1099         switch(giUIMode)
1100         {
1101         // Standard UI
1102         // - This assumes that 
1103         case UI_MODE_STANDARD:
1104                 // Bounds check
1105                 // Index = -1, request limit
1106                 if( Index < 0 || Index >= giNumItems+2 )
1107                         return giNumItems+2;
1108                 // Drink label
1109                 if( Index == 0 )
1110                 {
1111                         price = 0;
1112                         name = "Coke Machine";
1113                         Index = -1;     // -1 indicates a label
1114                         break;
1115                 }
1116                 Index --;
1117                 // Drinks 0 - 6
1118                 if( Index <= 6 )
1119                 {
1120                         name = gaItems[Index].Desc;
1121                         price = gaItems[Index].Price;
1122                         status = gaItems[Index].Status;
1123                         break;
1124                 }
1125                 Index -= 7;
1126                 // EPS label
1127                 if( Index == 0 )
1128                 {
1129                         price = 0;
1130                         name = "Electronic Payment System";
1131                         Index = -1;     // -1 indicates a label
1132                         break;
1133                 }
1134                 Index --;
1135                 Index += 7;
1136                 name = gaItems[Index].Desc;
1137                 price = gaItems[Index].Price;
1138                 status = gaItems[Index].Status;
1139                 break;
1140         default:
1141                 return -1;
1142         }
1143         
1144         // Width = 0, don't print
1145         if( Width > 0 )
1146         {
1147                 // 4 preceding, 5 price
1148                 int nameWidth = Width - 4 - snprintf(NULL, 0, " %4i", price);
1149                 move( Row, Col );
1150                 
1151                 if( Index >= 0 )
1152                 {
1153                         // Show hilight and status
1154                         switch( status )
1155                         {
1156                         case 0:
1157                                 if( bHilighted )
1158                                         printw("->  ");
1159                                 else
1160                                         printw("    ");
1161                                 break;
1162                         case 1:
1163                                 printw("SLD ");
1164                                 break;
1165                         
1166                         default:
1167                         case -1:
1168                                 printw("ERR ");
1169                                 break;
1170                         }
1171                         
1172                         printw("%-*.*s", nameWidth, nameWidth, name);
1173                 
1174                         printw(" %4i", price);
1175                 }
1176                 else
1177                 {
1178                         printw("-- %-*.*s ", Width-4, Width-4, name);
1179                 }
1180         }
1181         
1182         // If the item isn't availiable for sale, return -1 (so it's skipped)
1183         if( status || (price > giUserBalance && gbDisallowSelectWithoutBalance) )
1184                 Index = -1;
1185         
1186         return Index;
1187 }
1188
1189 /**
1190  * \brief Print a three-part string at the specified position (formatted)
1191  * \note NCurses UI Helper
1192  * 
1193  * Prints \a Left on the left of the area, \a Right on the righthand side
1194  * and \a Mid in the middle of the area. These are padded with \a Pad1
1195  * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
1196  * 
1197  * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
1198  * and the arguments to these are read in that order.
1199  */
1200 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
1201         const char *Mid, char Pad2, const char *Right, ...)
1202 {
1203          int    lLen, mLen, rLen;
1204          int    times;
1205         
1206         va_list args;
1207         
1208         // Get the length of the strings
1209         va_start(args, Right);
1210         lLen = vsnprintf(NULL, 0, Left, args);
1211         mLen = vsnprintf(NULL, 0, Mid, args);
1212         rLen = vsnprintf(NULL, 0, Right, args);
1213         va_end(args);
1214         
1215         // Sanity check
1216         if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1217                 return ;        // TODO: What to do?
1218         }
1219         
1220         move(Row, Col);
1221         
1222         // Render strings
1223         va_start(args, Right);
1224         // - Left
1225         {
1226                 char    tmp[lLen+1];
1227                 vsnprintf(tmp, lLen+1, Left, args);
1228                 addstr(tmp);
1229         }
1230         // - Left padding
1231         times = (Width - mLen)/2 - lLen;
1232         while(times--)  addch(Pad1);
1233         // - Middle
1234         {
1235                 char    tmp[mLen+1];
1236                 vsnprintf(tmp, mLen+1, Mid, args);
1237                 addstr(tmp);
1238         }
1239         // - Right Padding
1240         times = (Width - mLen)/2 - rLen;
1241         if( (Width - mLen) % 2 )        times ++;
1242         while(times--)  addch(Pad2);
1243         // - Right
1244         {
1245                 char    tmp[rLen+1];
1246                 vsnprintf(tmp, rLen+1, Right, args);
1247                 addstr(tmp);
1248         }
1249 }
1250
1251 // ---------------------
1252 // --- Coke Protocol ---
1253 // ---------------------
1254 int OpenConnection(const char *Host, int Port)
1255 {
1256         struct hostent  *host;
1257         struct sockaddr_in      serverAddr;
1258          int    sock;
1259         
1260         host = gethostbyname(Host);
1261         if( !host ) {
1262                 fprintf(stderr, "Unable to look up '%s'\n", Host);
1263                 return -1;
1264         }
1265         
1266         memset(&serverAddr, 0, sizeof(serverAddr));
1267         
1268         serverAddr.sin_family = AF_INET;        // IPv4
1269         // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1270         serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1271         serverAddr.sin_port = htons(Port);
1272         
1273         sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1274         if( sock < 0 ) {
1275                 fprintf(stderr, "Failed to create socket\n");
1276                 return -1;
1277         }
1278
1279 //      printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1280         
1281         if( geteuid() == 0 || getuid() == 0 )
1282         {
1283                  int    i;
1284                 struct sockaddr_in      localAddr;
1285                 memset(&localAddr, 0, sizeof(localAddr));
1286                 localAddr.sin_family = AF_INET; // IPv4
1287                 
1288                 // Loop through all the top ports until one is avaliable
1289                 for( i = 512; i < 1024; i ++)
1290                 {
1291                         localAddr.sin_port = htons(i);  // IPv4
1292                         // Attempt to bind to low port for autoauth
1293                         if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1294                                 break;
1295                 }
1296                 if( i == 1024 )
1297                         printf("Warning: AUTOAUTH unavaliable\n");
1298 //              else
1299 //                      printf("Bound to 0.0.0.0:%i\n", i);
1300         }
1301         
1302         if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1303                 fprintf(stderr, "Failed to connect to server\n");
1304                 return -1;
1305         }
1306
1307         // We're not authenticated if the connection has just opened
1308         gbIsAuthenticated = 0;
1309         
1310         return sock;
1311 }
1312
1313 /**
1314  * \brief Authenticate with the server
1315  * \return Boolean Failure
1316  */
1317 int Authenticate(int Socket)
1318 {
1319         struct passwd   *pwd;
1320         char    *buf;
1321          int    responseCode;
1322         #if ATTEMPT_PASSWORD_AUTH
1323         char    salt[32];
1324          int    i;
1325         regmatch_t      matches[4];
1326         #endif
1327         
1328         if( gbIsAuthenticated ) return 0;
1329         
1330         // Get user name
1331         pwd = getpwuid( getuid() );
1332         
1333         // Attempt automatic authentication
1334         sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1335         
1336         // Check if it worked
1337         buf = ReadLine(Socket);
1338         
1339         responseCode = atoi(buf);
1340         switch( responseCode )
1341         {
1342         case 200:       // Autoauth succeeded, return
1343                 free(buf);
1344                 break;
1345         
1346         case 401:       // Untrusted, attempt password authentication
1347                 free(buf);
1348
1349                 #if ATTEMPT_PASSWORD_AUTH       
1350                 sendf(Socket, "USER %s\n", pwd->pw_name);
1351                 printf("Using username %s\n", pwd->pw_name);
1352                 
1353                 buf = ReadLine(Socket);
1354                 
1355                 // TODO: Get Salt
1356                 // Expected format: 100 SALT <something> ...
1357                 // OR             : 100 User Set
1358                 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1359                 responseCode = atoi(buf);
1360                 if( responseCode != 100 ) {
1361                         fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1362                         free(buf);
1363                         return RV_UNKNOWN_ERROR;        // ERROR
1364                 }
1365                 
1366                 // Check for salt
1367                 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1368                         // Store it for later
1369                         memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1370                         salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1371                 }
1372                 free(buf);
1373                 
1374                 // Give three attempts
1375                 for( i = 0; i < 3; i ++ )
1376                 {
1377                          int    ofs = strlen(pwd->pw_name)+strlen(salt);
1378                         char    tmpBuf[42];
1379                         char    tmp[ofs+20];
1380                         char    *pass = getpass("Password: ");
1381                         uint8_t h[20];
1382                         
1383                         // Create hash string
1384                         // <username><salt><hash>
1385                         strcpy(tmp, pwd->pw_name);
1386                         strcat(tmp, salt);
1387                         SHA1( (unsigned char*)pass, strlen(pass), h );
1388                         memcpy(tmp+ofs, h, 20);
1389                         
1390                         // Hash all that
1391                         SHA1( (unsigned char*)tmp, ofs+20, h );
1392                         sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1393                                 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1394                                 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1395                                 );
1396                 
1397                         // Send password
1398                         sendf(Socket, "PASS %s\n", tmpBuf);
1399                         buf = ReadLine(Socket);
1400                 
1401                         responseCode = atoi(buf);
1402                         // Auth OK?
1403                         if( responseCode == 200 )       break;
1404                         // Bad username/password
1405                         if( responseCode == 401 )       continue;
1406                         
1407                         fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1408                         free(buf);
1409                         return RV_UNKNOWN_ERROR;
1410                 }
1411                 free(buf);
1412                 if( i == 3 )
1413                         return RV_INVALID_USER; // 2 = Bad Password
1414                 
1415                 #else
1416                 fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
1417                 return RV_INVALID_USER;
1418                 #endif
1419                 break;
1420         
1421         case 404:       // Bad Username
1422                 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1423                 free(buf);
1424                 return RV_INVALID_USER;
1425         
1426         default:
1427                 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1428                 printf("%s\n", buf);
1429                 free(buf);
1430                 return RV_UNKNOWN_ERROR;
1431         }
1432         
1433         // Set effective user
1434         if( gsEffectiveUser ) {
1435                 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1436                 
1437                 buf = ReadLine(Socket);
1438                 responseCode = atoi(buf);
1439                 
1440                 switch(responseCode)
1441                 {
1442                 case 200:
1443                         printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1444                         break;
1445                 
1446                 case 403:
1447                         printf("Only coke members can use `dispense -u`\n");
1448                         free(buf);
1449                         return RV_PERMISSIONS;
1450                 
1451                 case 404:
1452                         printf("Invalid user selected\n");
1453                         free(buf);
1454                         return RV_INVALID_USER;
1455                 
1456                 default:
1457                         fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1458                         printf("%s\n", buf);
1459                         free(buf);
1460                         return RV_UNKNOWN_ERROR;
1461                 }
1462                 
1463                 free(buf);
1464         }
1465         
1466         gbIsAuthenticated = 1;
1467         
1468         return 0;
1469 }
1470
1471 int GetUserBalance(int Socket)
1472 {
1473         regmatch_t      matches[6];
1474         struct passwd   *pwd;
1475         char    *buf;
1476          int    responseCode;
1477         
1478         if( !gsUserName )
1479         {
1480                 if( gsEffectiveUser ) {
1481                         gsUserName = gsEffectiveUser;
1482                 }
1483                 else {
1484                         pwd = getpwuid( getuid() );
1485                         gsUserName = strdup(pwd->pw_name);
1486                 }
1487         }
1488         
1489         sendf(Socket, "USER_INFO %s\n", gsUserName);
1490         buf = ReadLine(Socket);
1491         responseCode = atoi(buf);
1492         switch(responseCode)
1493         {
1494         case 202:       break;  // Ok
1495         
1496         case 404:
1497                 printf("Invalid user? (USER_INFO failed)\n");
1498                 free(buf);
1499                 return RV_INVALID_USER;
1500         
1501         default:
1502                 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1503                 printf("%s\n", buf);
1504                 free(buf);
1505                 return RV_UNKNOWN_ERROR;
1506         }
1507
1508         RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1509         
1510         giUserBalance = atoi( buf + matches[4].rm_so );
1511         gsUserFlags = strdup( buf + matches[5].rm_so );
1512         
1513         free(buf);
1514         
1515         return 0;
1516 }
1517
1518 /**
1519  * \brief Read an item info response from the server
1520  * \param Dest  Destination for the read item (strings will be on the heap)
1521  */
1522 int ReadItemInfo(int Socket, tItem *Dest)
1523 {
1524         char    *buf;
1525          int    responseCode;
1526         
1527         regmatch_t      matches[8];
1528         char    *statusStr;
1529         
1530         // Get item info
1531         buf = ReadLine(Socket);
1532         responseCode = atoi(buf);
1533         
1534         switch(responseCode)
1535         {
1536         case 202:       break;
1537         
1538         case 406:
1539                 printf("Bad item name\n");
1540                 free(buf);
1541                 return RV_BAD_ITEM;
1542         
1543         default:
1544                 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1545                 free(buf);
1546                 return RV_UNKNOWN_ERROR;
1547         }
1548         
1549         RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1550         
1551         buf[ matches[3].rm_eo ] = '\0';
1552         buf[ matches[5].rm_eo ] = '\0';
1553         buf[ matches[7].rm_eo ] = '\0';
1554         
1555         statusStr = &buf[ matches[5].rm_so ];
1556         
1557         Dest->ID = atoi( buf + matches[4].rm_so );
1558         
1559         if( strcmp(statusStr, "avail") == 0 )
1560                 Dest->Status = 0;
1561         else if( strcmp(statusStr, "sold") == 0 )
1562                 Dest->Status = 1;
1563         else if( strcmp(statusStr, "error") == 0 )
1564                 Dest->Status = -1;
1565         else {
1566                 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1567                         statusStr);
1568                 return RV_UNKNOWN_ERROR;
1569         }
1570         Dest->Price = atoi( buf + matches[6].rm_so );
1571         
1572         // Hack a little to reduce heap fragmentation
1573         {
1574                 char    tmpType[strlen(buf + matches[3].rm_so) + 1];
1575                 char    tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1576                 strcpy(tmpType, buf + matches[3].rm_so);
1577                 strcpy(tmpDesc, buf + matches[7].rm_so);
1578                 free(buf);
1579                 Dest->Type = strdup( tmpType );
1580                 Dest->Desc = strdup( tmpDesc );
1581         }
1582         
1583         return 0;
1584 }
1585
1586 /**
1587  * \brief Fill the item information structure
1588  * \return Boolean Failure
1589  */
1590 void PopulateItemList(int Socket)
1591 {
1592         char    *buf;
1593          int    responseCode;
1594         
1595         char    *arrayType;
1596          int    count, i;
1597         regmatch_t      matches[4];
1598         
1599         // Ask server for stock list
1600         send(Socket, "ENUM_ITEMS\n", 11, 0);
1601         buf = ReadLine(Socket);
1602         
1603         //printf("Output: %s\n", buf);
1604         
1605         responseCode = atoi(buf);
1606         if( responseCode != 201 ) {
1607                 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1608                 exit(RV_UNKNOWN_ERROR);
1609         }
1610         
1611         // - Get item list -
1612         
1613         // Expected format:
1614         //  201 Items <count>
1615         //  202 Item <count>
1616         RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1617                 
1618         arrayType = &buf[ matches[2].rm_so ];   buf[ matches[2].rm_eo ] = '\0';
1619         count = atoi( &buf[ matches[3].rm_so ] );
1620                 
1621         // Check array type
1622         if( strcmp(arrayType, "Items") != 0 ) {
1623                 // What the?!
1624                 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1625                         arrayType);
1626                 exit(RV_UNKNOWN_ERROR);
1627         }
1628         free(buf);
1629         
1630         giNumItems = count;
1631         gaItems = malloc( giNumItems * sizeof(tItem) );
1632         
1633         // Fetch item information
1634         for( i = 0; i < giNumItems; i ++ )
1635         {
1636                 ReadItemInfo( Socket, &gaItems[i] );
1637         }
1638         
1639         // Read end of list
1640         buf = ReadLine(Socket);
1641         responseCode = atoi(buf);
1642                 
1643         if( responseCode != 200 ) {
1644                 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1645                         responseCode, buf
1646                         );
1647                 exit(-1);
1648         }
1649         
1650         free(buf);
1651 }
1652
1653
1654 /**
1655  * \brief Get information on an item
1656  * \return Boolean Failure
1657  */
1658 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1659 {
1660         tItem   item;
1661          int    ret;
1662         
1663         // Query
1664         sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1665         
1666         ret = ReadItemInfo(Socket, &item);
1667         if(ret) return ret;
1668         
1669         printf("%8s:%-2i %2i.%02i %s\n",
1670                 item.Type, item.ID,
1671                 item.Price/100, item.Price%100,
1672                 item.Desc);
1673         
1674         free(item.Type);
1675         free(item.Desc);
1676         
1677         return 0;
1678 }
1679
1680 /**
1681  * \brief Dispense an item
1682  * \return Boolean Failure
1683  */
1684 int DispenseItem(int Socket, const char *Type, int ID)
1685 {
1686          int    ret, responseCode;
1687         char    *buf;
1688         
1689         // Check for a dry run
1690         if( gbDryRun ) {
1691                 printf("Dry Run - No action\n");
1692                 return 0;
1693         }
1694         
1695         // Dispense!
1696         sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1697         buf = ReadLine(Socket);
1698         
1699         responseCode = atoi(buf);
1700         switch( responseCode )
1701         {
1702         case 200:
1703                 printf("Dispense OK\n");
1704                 ret = 0;
1705                 break;
1706         case 401:
1707                 printf("Not authenticated\n");
1708                 ret = RV_PERMISSIONS;
1709                 break;
1710         case 402:
1711                 printf("Insufficient balance\n");
1712                 ret = RV_BALANCE;
1713                 break;
1714         case 406:
1715                 printf("Bad item name\n");
1716                 ret = RV_BAD_ITEM;
1717                 break;
1718         case 500:
1719                 printf("Item failed to dispense, is the slot empty?\n");
1720                 ret = RV_SERVER_ERROR;
1721                 break;
1722         case 501:
1723                 printf("Dispense not possible (slot empty/permissions)\n");
1724                 ret = RV_SERVER_ERROR;
1725                 break;
1726         default:
1727                 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1728                 ret = RV_UNKNOWN_ERROR;
1729                 break;
1730         }
1731         
1732         free(buf);
1733         return ret;
1734 }
1735
1736 /**
1737  * \brief Alter a user's balance
1738  */
1739 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1740 {
1741         char    *buf;
1742          int    responseCode, rv = -1;
1743         
1744         // Check for a dry run
1745         if( gbDryRun ) {
1746                 printf("Dry Run - No action\n");
1747                 return 0;
1748         }
1749
1750         // Sanity
1751         if( Ammount == 0 ) {
1752                 printf("An amount would be nice\n");
1753                 return RV_ARGUMENTS;
1754         }
1755         
1756         sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1757         buf = ReadLine(Socket);
1758         
1759         responseCode = atoi(buf);
1760         
1761         switch(responseCode)
1762         {
1763         case 200:
1764                 rv = 0; // OK
1765                 break;
1766         case 402:
1767                 fprintf(stderr, "Insufficient balance\n");
1768                 rv = RV_BAD_ITEM;
1769                 break;
1770         case 403:       // Not in coke
1771                 fprintf(stderr, "You are not in coke (sucker)\n");
1772                 rv = RV_PERMISSIONS;
1773                 break;
1774         case 404:       // Unknown user
1775                 fprintf(stderr, "Unknown user '%s'\n", Username);
1776                 rv = RV_INVALID_USER;
1777                 break;
1778         default:
1779                 fprintf(stderr, "Unknown response code %i\n'%s'\n", responseCode, buf);
1780                 rv = RV_UNKNOWN_RESPONSE;
1781                 break;
1782         }
1783         free(buf);
1784         
1785         return rv;
1786 }
1787
1788 /**
1789  * \brief Set a user's balance
1790  * \note Only avaliable to dispense admins
1791  */
1792 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1793 {
1794         char    *buf;
1795          int    responseCode;
1796         
1797         // Check for a dry run
1798         if( gbDryRun ) {
1799                 printf("Dry Run - No action\n");
1800                 return 0;
1801         }
1802         
1803         sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1804         buf = ReadLine(Socket);
1805         
1806         responseCode = atoi(buf);
1807         free(buf);
1808         
1809         switch(responseCode)
1810         {
1811         case 200:       return 0;       // OK
1812         case 403:       // Not in coke
1813                 fprintf(stderr, "You are not an admin\n");
1814                 return RV_PERMISSIONS;
1815         case 404:       // Unknown user
1816                 fprintf(stderr, "Unknown user '%s'\n", Username);
1817                 return RV_INVALID_USER;
1818         default:
1819                 fprintf(stderr, "Unknown response code %i\n", responseCode);
1820                 return RV_UNKNOWN_RESPONSE;
1821         }
1822         
1823         return -1;
1824 }
1825
1826 /**
1827  * \brief Give money to another user
1828  */
1829 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1830 {
1831         char    *buf;
1832          int    responseCode;
1833         
1834         if( Ammount < 0 ) {
1835                 printf("Sorry, you can only give, you can't take.\n");
1836                 return RV_ARGUMENTS;
1837         }
1838         
1839         // Fast return on zero
1840         if( Ammount == 0 ) {
1841                 printf("Are you actually going to give any?\n");
1842                 return RV_ARGUMENTS;
1843         }
1844         
1845         // Check for a dry run
1846         if( gbDryRun ) {
1847                 printf("Dry Run - No action\n");
1848                 return 0;
1849         }
1850         
1851         sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1852
1853         buf = ReadLine(Socket);
1854         responseCode = atoi(buf);
1855         free(buf);      
1856         switch(responseCode)
1857         {
1858         case 200:
1859                 printf("Give succeeded\n");
1860                 return RV_SUCCESS;      // OK
1861         
1862         case 402:       
1863                 fprintf(stderr, "Insufficient balance\n");
1864                 return RV_BALANCE;
1865         
1866         case 404:       // Unknown user
1867                 fprintf(stderr, "Unknown user '%s'\n", Username);
1868                 return RV_INVALID_USER;
1869         
1870         default:
1871                 fprintf(stderr, "Unknown response code %i\n", responseCode);
1872                 return RV_UNKNOWN_RESPONSE;
1873         }
1874         
1875         return -1;
1876 }
1877
1878 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
1879 {
1880         char    *buf;
1881          int    responseCode, ret = -1;
1882         
1883         // Check item id
1884         if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
1885         {
1886                 fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
1887                 return RV_ARGUMENTS;
1888         }
1889
1890         // Check username (quick)
1891         if( strchr(Username, ' ') || strchr(Username, '\n') )
1892         {
1893                 fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
1894                 return RV_ARGUMENTS;
1895         }
1896
1897         // Send the query
1898         sendf(Socket, "REFUND %s %s %i\n", Username, Item, PriceOverride);
1899
1900         buf = ReadLine(Socket);
1901         responseCode = atoi(buf);
1902         switch(responseCode)
1903         {
1904         case 200:
1905                 Dispense_ShowUser(Socket, Username);    // Show destination account
1906                 ret = 0;
1907                 break;
1908         case 403:
1909                 fprintf(stderr, "Refund access is only avaliable to coke members\n");
1910                 ret = RV_PERMISSIONS;
1911                 break;
1912         case 404:
1913                 fprintf(stderr, "Unknown user '%s' passed\n", Username);
1914                 ret = RV_INVALID_USER;
1915                 break;
1916         case 406:
1917                 fprintf(stderr, "Invalid item '%s' passed\n", Item);
1918                 ret = RV_BAD_ITEM;
1919                 break;
1920         default:
1921                 fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
1922                 ret = -1;
1923                 break;
1924         }
1925         free(buf);
1926         return ret;
1927 }
1928
1929 /**
1930  * \brief Donate money to the club
1931  */
1932 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1933 {
1934         char    *buf;
1935          int    responseCode;
1936         
1937         if( Ammount < 0 ) {
1938                 printf("Sorry, you can only give, you can't take.\n");
1939                 return -1;
1940         }
1941         
1942         // Fast return on zero
1943         if( Ammount == 0 ) {
1944                 printf("Are you actually going to give any?\n");
1945                 return 1;
1946         }
1947         
1948         // Check for a dry run
1949         if( gbDryRun ) {
1950                 printf("Dry Run - No action\n");
1951                 return 0;
1952         }
1953         
1954         sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1955         buf = ReadLine(Socket);
1956         
1957         responseCode = atoi(buf);
1958         free(buf);
1959         
1960         switch(responseCode)
1961         {
1962         case 200:       return 0;       // OK
1963         
1964         case 402:       
1965                 fprintf(stderr, "Insufficient balance\n");
1966                 return 1;
1967         
1968         default:
1969                 fprintf(stderr, "Unknown response code %i\n", responseCode);
1970                 return -1;
1971         }
1972         
1973         return -1;
1974 }
1975
1976 /**
1977  * \brief Enumerate users
1978  */
1979 int Dispense_EnumUsers(int Socket)
1980 {
1981         char    *buf;
1982          int    responseCode;
1983          int    nUsers;
1984         regmatch_t      matches[4];
1985         
1986         if( giMinimumBalance != INT_MIN ) {
1987                 if( giMaximumBalance != INT_MAX ) {
1988                         sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1989                 }
1990                 else {
1991                         sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1992                 }
1993         }
1994         else {
1995                 if( giMaximumBalance != INT_MAX ) {
1996                         sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1997                 }
1998                 else {
1999                         sendf(Socket, "ENUM_USERS\n");
2000                 }
2001         }
2002         buf = ReadLine(Socket);
2003         responseCode = atoi(buf);
2004         
2005         switch(responseCode)
2006         {
2007         case 201:       break;  // Ok, length follows
2008         
2009         default:
2010                 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
2011                 free(buf);
2012                 return -1;
2013         }
2014         
2015         // Get count (not actually used)
2016         RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
2017         nUsers = atoi( buf + matches[3].rm_so );
2018         printf("%i users returned\n", nUsers);
2019         
2020         // Free string
2021         free(buf);
2022         
2023         // Read returned users
2024         do {
2025                 buf = ReadLine(Socket);
2026                 responseCode = atoi(buf);
2027                 
2028                 if( responseCode != 202 )       break;
2029                 
2030                 _PrintUserLine(buf);
2031                 free(buf);
2032         } while(responseCode == 202);
2033         
2034         // Check final response
2035         if( responseCode != 200 ) {
2036                 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
2037                 free(buf);
2038                 return -1;
2039         }
2040         
2041         free(buf);
2042         
2043         return 0;
2044 }
2045
2046 int Dispense_ShowUser(int Socket, const char *Username)
2047 {
2048         char    *buf;
2049          int    responseCode, ret;
2050         
2051         sendf(Socket, "USER_INFO %s\n", Username);
2052         buf = ReadLine(Socket);
2053         
2054         responseCode = atoi(buf);
2055         
2056         switch(responseCode)
2057         {
2058         case 202:
2059                 _PrintUserLine(buf);
2060                 ret = 0;
2061                 break;
2062         
2063         case 404:
2064                 printf("Unknown user '%s'\n", Username);
2065                 ret = 1;
2066                 break;
2067         
2068         default:
2069                 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2070                 ret = -1;
2071                 break;
2072         }
2073         
2074         free(buf);
2075         
2076         return ret;
2077 }
2078
2079 void _PrintUserLine(const char *Line)
2080 {
2081         regmatch_t      matches[6];
2082          int    bal;
2083         
2084         RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
2085         // 3: Username
2086         // 4: Balance
2087         // 5: Flags
2088         {
2089                  int    usernameLen = matches[3].rm_eo - matches[3].rm_so;
2090                 char    username[usernameLen + 1];
2091                  int    flagsLen = matches[5].rm_eo - matches[5].rm_so;
2092                 char    flags[flagsLen + 1];
2093                 
2094                 memcpy(username, Line + matches[3].rm_so, usernameLen);
2095                 username[usernameLen] = '\0';
2096                 memcpy(flags, Line + matches[5].rm_so, flagsLen);
2097                 flags[flagsLen] = '\0';
2098                 
2099                 bal = atoi(Line + matches[4].rm_so);
2100                 printf("%-15s: $%8.02f (%s)\n", username, ((float)bal)/100, flags);
2101         }
2102 }
2103
2104 int Dispense_AddUser(int Socket, const char *Username)
2105 {
2106         char    *buf;
2107          int    responseCode, ret;
2108         
2109         // Check for a dry run
2110         if( gbDryRun ) {
2111                 printf("Dry Run - No action\n");
2112                 return 0;
2113         }
2114         
2115         sendf(Socket, "USER_ADD %s\n", Username);
2116         
2117         buf = ReadLine(Socket);
2118         responseCode = atoi(buf);
2119         
2120         switch(responseCode)
2121         {
2122         case 200:
2123                 printf("User '%s' added\n", Username);
2124                 ret = 0;
2125                 break;
2126                 
2127         case 403:
2128                 printf("Only wheel can add users\n");
2129                 ret = 1;
2130                 break;
2131                 
2132         case 404:
2133                 printf("User '%s' already exists\n", Username);
2134                 ret = 0;
2135                 break;
2136         
2137         default:
2138                 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2139                 ret = -1;
2140                 break;
2141         }
2142         
2143         free(buf);
2144         
2145         return ret;
2146 }
2147
2148 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString, const char *Reason)
2149 {
2150         char    *buf;
2151          int    responseCode, ret;
2152         
2153         // Check for a dry run
2154         if( gbDryRun ) {
2155                 printf("Dry Run - No action\n");
2156                 return 0;
2157         }
2158         
2159         // TODO: Pre-validate the string
2160         
2161         sendf(Socket, "USER_FLAGS %s %s %s\n", Username, TypeString, Reason);
2162         
2163         buf = ReadLine(Socket);
2164         responseCode = atoi(buf);
2165         
2166         switch(responseCode)
2167         {
2168         case 200:
2169                 printf("User '%s' updated\n", Username);
2170                 ret = 0;
2171                 break;
2172                 
2173         case 403:
2174                 printf("Only dispense admins can modify users\n");
2175                 ret = RV_PERMISSIONS;
2176                 break;
2177         
2178         case 404:
2179                 printf("User '%s' does not exist\n", Username);
2180                 ret = RV_INVALID_USER;
2181                 break;
2182         
2183         case 407:
2184                 printf("Flag string is invalid\n");
2185                 ret = RV_ARGUMENTS;
2186                 break;
2187         
2188         default:
2189                 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2190                 ret = RV_UNKNOWN_RESPONSE;
2191                 break;
2192         }
2193         
2194         free(buf);
2195         
2196         return ret;
2197 }
2198
2199 int Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName)
2200 {
2201         char    *buf;
2202          int    responseCode, ret;
2203         
2204         // Check for a dry run
2205         if( gbDryRun ) {
2206                 printf("Dry Run - No action\n");
2207                 return 0;
2208         }
2209         
2210         sendf(Socket, "UPDATE_ITEM %s:%i %i %s\n", Type, ID, NewPrice, NewName);
2211         
2212         buf = ReadLine(Socket);
2213         responseCode = atoi(buf);
2214         
2215         switch(responseCode)
2216         {
2217         case 200:
2218                 printf("Item %s:%i updated\n", Type, ID);
2219                 ret = 0;
2220                 break;
2221                 
2222         case 403:
2223                 printf("Only coke members can modify the slots\n");
2224                 ret = RV_PERMISSIONS;
2225                 break;
2226         
2227         case 406:
2228                 printf("Invalid item passed\n");
2229                 ret = RV_BAD_ITEM;
2230                 break;
2231         
2232         default:
2233                 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2234                 ret = -1;
2235                 break;
2236         }
2237         
2238         free(buf);
2239         
2240         return ret;
2241 }
2242
2243 // ---------------
2244 // --- Helpers ---
2245 // ---------------
2246 char *ReadLine(int Socket)
2247 {
2248         static char     buf[BUFSIZ];
2249         static int      bufPos = 0;
2250         static int      bufValid = 0;
2251          int    len;
2252         char    *newline = NULL;
2253          int    retLen = 0;
2254         char    *ret = malloc(10);
2255         
2256         #if DEBUG_TRACE_SERVER
2257         printf("ReadLine: ");
2258         fflush(stdout);
2259         #endif
2260         
2261         ret[0] = '\0';
2262         
2263         while( !newline )
2264         {
2265                 if( bufValid ) {
2266                         len = bufValid;
2267                 }
2268                 else {
2269                         len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
2270                         if( len <= 0 ) {
2271                                 free(ret);
2272                                 return strdup("599 Client Connection Error\n");
2273                         }
2274                 }
2275                 buf[bufPos+len] = '\0';
2276                 
2277                 newline = strchr( buf+bufPos, '\n' );
2278                 if( newline ) {
2279                         *newline = '\0';
2280                 }
2281                 
2282                 retLen += strlen(buf+bufPos);
2283                 ret = realloc(ret, retLen + 1);
2284                 strcat( ret, buf+bufPos );
2285                 
2286                 if( newline ) {
2287                          int    newLen = newline - (buf+bufPos) + 1;
2288                         bufValid = len - newLen;
2289                         len = newLen;
2290                 }
2291                 if( len + bufPos == BUFSIZ - 1 )        bufPos = 0;
2292                 else    bufPos += len;
2293         }
2294         
2295         #if DEBUG_TRACE_SERVER
2296         printf("%i '%s'\n", retLen, ret);
2297         #endif
2298         
2299         return ret;
2300 }
2301
2302 int sendf(int Socket, const char *Format, ...)
2303 {
2304         va_list args;
2305          int    len;
2306         
2307         va_start(args, Format);
2308         len = vsnprintf(NULL, 0, Format, args);
2309         va_end(args);
2310         
2311         {
2312                 char    buf[len+1];
2313                 va_start(args, Format);
2314                 vsnprintf(buf, len+1, Format, args);
2315                 va_end(args);
2316                 
2317                 #if DEBUG_TRACE_SERVER
2318                 printf("sendf: %s", buf);
2319                 #endif
2320                 
2321                 return send(Socket, buf, len, 0);
2322         }
2323 }
2324
2325 char *trim(char *string)
2326 {
2327          int    i;
2328         
2329         while( isspace(*string) )
2330                 string ++;
2331         
2332         for( i = strlen(string); i--; )
2333         {
2334                 if( isspace(string[i]) )
2335                         string[i] = '\0';
2336                 else
2337                         break;
2338         }
2339         
2340         return string;
2341 }
2342
2343 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2344 {
2345          int    ret;
2346         
2347         ret = regexec(regex, string, nMatches, matches, 0);
2348         if( ret && errorMessage ) {
2349                 size_t  len = regerror(ret, regex, NULL, 0);
2350                 char    errorStr[len];
2351                 regerror(ret, regex, errorStr, len);
2352                 printf("string = '%s'\n", string);
2353                 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2354                 exit(-1);
2355         }
2356         
2357         return ret;
2358 }
2359
2360 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2361 {
2362          int    ret = regcomp(regex, pattern, flags);
2363         if( ret ) {
2364                 size_t  len = regerror(ret, regex, NULL, 0);
2365                 char    errorStr[len];
2366                 regerror(ret, regex, errorStr, len);
2367                 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);
2368                 exit(-1);
2369         }
2370 }

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