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

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