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

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