Fixed not checking return value of recv()
[tpg/opendispense2.git] / src / client / main.c
index 07fb0b4..0995d3b 100644 (file)
@@ -30,6 +30,7 @@
 #define USE_AUTOAUTH   1
 
 #define MAX_TXT_ARGS   5       // Maximum number of textual arguments (including command)
+#define DISPENSE_MULTIPLE_MAX  20      // Maximum argument to -c
 
 enum eUI_Modes
 {
@@ -40,6 +41,20 @@ enum eUI_Modes
        NUM_UI_MODES
 };
 
+enum eReturnValues
+{
+       RV_SUCCESS,
+       RV_BAD_ITEM,
+       RV_INVALID_USER,
+       RV_PERMISSIONS,
+       RV_ARGUMENTS,
+       RV_BALANCE,
+       RV_SERVER_ERROR,        // Generic for 5xx codes
+       RV_UNKNOWN_ERROR = -1,
+       RV_SOCKET_ERROR = -2,
+       RV_UNKNOWN_RESPONSE = -3,
+};
+
 // === TYPES ===
 typedef struct sItem {
        char    *Type;
@@ -50,8 +65,8 @@ typedef struct sItem {
 }      tItem;
 
 // === PROTOTYPES ===
- int   main(int argc, char *argv[]);
 void   ShowUsage(void);
+ int   main(int argc, char *argv[]);
 // --- GUI ---
  int   ShowNCursesUI(void);
  int   ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted);
@@ -66,12 +81,14 @@ void        PopulateItemList(int Socket);
  int   Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
  int   Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason);
  int   Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
+ int   Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride);
  int   Dispense_Donate(int Socket, int Ammount, const char *Reason);
  int   Dispense_EnumUsers(int Socket);
  int   Dispense_ShowUser(int Socket, const char *Username);
 void   _PrintUserLine(const char *Line);
  int   Dispense_AddUser(int Socket, const char *Username);
  int   Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
+ int   Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName);
 // --- Helpers ---
 char   *ReadLine(int Socket);
  int   sendf(int Socket, const char *Format, ...);
@@ -97,8 +114,65 @@ char        *gsEffectiveUser;       //!< '-u' Dispense as another user
 char   *gsUserName;    //!< User that dispense will happen as
 char   *gsUserFlags;   //!< User's flag set
  int   giUserBalance=-1;       //!< User balance (set by Authenticate)
+ int   giDispenseCount = 1;    //!< Number of dispenses to do
 
 // === CODE ===
+void ShowUsage(void)
+{
+       printf(
+               "Usage:\n"
+               "  == Everyone ==\n"
+               "    dispense\n"
+               "        Show interactive list\n"
+               "    dispense <name>|<index>|<itemid>\n"
+               "        Dispense named item (<name> matches if it is a unique prefix)\n"
+               "    dispense give <user> <ammount> \"<reason>\"\n"
+               "        Give money to another user\n"
+               "    dispense donate <ammount> \"<reason>\"\n"
+               "        Donate to the club\n"
+               "    dispense iteminfo <itemid>\n"
+               "        Get the name and price for an item\n"
+               "  == Coke members == \n"
+               "    dispense acct [<user>]\n"
+               "        Show user balances\n"
+               "    dispense acct <user> [+-]<ammount> \"<reason>\"\n"
+               "        Alter a account value\n"
+               "    dispense refund <user> <itemid> [<price>]\n"
+               "        Refund an item to a user (with optional price override)\n"
+               "    dispense slot <itemid> <price> <name>\n"
+               "        Rename/Re-price a slot\n"
+               "  == Dispense administrators ==\n"
+               "    dispense acct <user> =<ammount> \"<reason>\"\n"
+               "        Set an account balance\n"
+               "    dispense user add <user>\n"
+               "        Create new account\n"
+               "    dispense user type <user> <flags>\n"
+               "        Alter a user's flags\n"
+               "        <flags> is a comma-separated list of user, coke, admin, internal or disabled\n"
+               "        Flags are removed by preceding the name with '-' or '!'\n"
+               "\n"
+               "General Options:\n"
+               "    -c <count>\n"
+               "        Dispense multiple times\n"
+               "    -u <username>\n"
+               "        Set a different user (Coke members only)\n"
+               "    -h / -?\n"
+               "        Show help text\n"
+               "    -G\n"
+               "        Use alternate GUI\n"
+               "    -n\n"
+               "        Dry run - Do not actually do dispenses\n"
+               "    -m <min balance>\n"
+               "    -M <max balance>\n"
+               "        Set the Maximum/Minimum balances shown in `dispense acct`\n"
+               "Definitions:\n"
+               "    <itemid>\n"
+               "        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"
+//             "    <user>\n"
+//             "        Account name\n"
+               );
+}
+
 int main(int argc, char *argv[])
 {
         int    sock;
@@ -134,11 +208,26 @@ int main(int argc, char *argv[])
                        case '?':
                                ShowUsage();
                                return 0;
-                       
+                                       
+                       case 'c':
+                               if( i + 1 >= argc ) {
+                                       fprintf(stderr, "%s: -c takes an argument\n", argv[0]);
+                                       ShowUsage();
+                                       return -1;
+                               }
+                               giDispenseCount = atoi(argv[++i]);
+                               if( giDispenseCount < 1 || giDispenseCount > DISPENSE_MULTIPLE_MAX ) {
+                                       fprintf(stderr, "Sorry, only 1-20 can be passed to -c (safety)\n");
+                                       return -1;
+                               }
+                               
+                               break ;
+       
                        case 'm':       // Minimum balance
                                if( i + 1 >= argc ) {
                                        fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
                                        ShowUsage();
+                                       return RV_ARGUMENTS;
                                }
                                giMinimumBalance = atoi(argv[++i]);
                                break;
@@ -146,6 +235,7 @@ int main(int argc, char *argv[])
                                if( i + 1 >= argc ) {
                                        fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
                                        ShowUsage();
+                                       return RV_ARGUMENTS;
                                }
                                giMaximumBalance = atoi(argv[++i]);
                                break;
@@ -154,6 +244,7 @@ int main(int argc, char *argv[])
                                if( i + 1 >= argc ) {
                                        fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
                                        ShowUsage();
+                                       return RV_ARGUMENTS;
                                }
                                gsEffectiveUser = argv[++i];
                                break;
@@ -162,6 +253,7 @@ int main(int argc, char *argv[])
                                if( i + 1 >= argc ) {
                                        fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
                                        ShowUsage();
+                                       return RV_ARGUMENTS;
                                }
                                gsDispenseServer = argv[++i];
                                break;
@@ -169,10 +261,22 @@ int main(int argc, char *argv[])
                                if( i + 1 >= argc ) {
                                        fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
                                        ShowUsage();
+                                       return RV_ARGUMENTS;
                                }
                                giDispensePort = atoi(argv[++i]);
                                break;
                        
+                       // Set slot name/price
+                       case 's':
+                               if( text_argc != 0 ) {
+                                       fprintf(stderr, "%s: -s must appear before other arguments\n", argv[0]);
+                                       ShowUsage();
+                                       return RV_ARGUMENTS;
+                               }
+                               text_args[0] = "slot";  // HACK!!
+                               text_argc ++;
+                               break;
+                       
                        case 'G':       // Don't use GUI
                                giUIMode = UI_MODE_BASIC;
                                break;
@@ -182,15 +286,16 @@ int main(int argc, char *argv[])
                        case 'n':       // Dry Run / read-only
                                gbDryRun = 1;
                                break;
-                       case '0':       case '1':
-                       case '2':       case '3':
-                       case '4':       case '5':
-                       case '6':       case '7':
-                       case '8':       case '9':
+                       default:
+//                             if( !isdigit(argv[i][0]) ) {
+//                                     fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
+//                                     ShowUsage();
+//                                     return RV_ARGUMENTS;
+//                             }
                                if( text_argc + 1 ==  MAX_TXT_ARGS )
                                {
                                        fprintf(stderr, "ERROR: Too many arguments\n");
-                                       return 1;
+                                       return RV_ARGUMENTS;
                                }
                                text_args[text_argc++] = argv[i];
                                break;
@@ -202,7 +307,7 @@ int main(int argc, char *argv[])
                if( text_argc + 1 == MAX_TXT_ARGS )
                {
                        fprintf(stderr, "ERROR: Too many arguments\n");
-                       return 1;
+                       return RV_ARGUMENTS;
                }
        
                text_args[text_argc++] = argv[i];
@@ -216,8 +321,8 @@ int main(int argc, char *argv[])
        {
                // Connect to server
                sock = OpenConnection(gsDispenseServer, giDispensePort);
-               if( sock < 0 )  return -1;
-                       // List accounts?
+               if( sock < 0 )  return RV_SOCKET_ERROR;
+               // List accounts?
                if( text_argc == 1 ) {
                        ret = Dispense_EnumUsers(sock);
                        close(sock);
@@ -227,11 +332,17 @@ int main(int argc, char *argv[])
                // text_args[1]: Username
                
                // Alter account?
-               if( text_argc == 4 )
+               if( text_argc != 2 )
                {
+                       if( text_argc != 4 ) {
+                               fprintf(stderr, "`dispense acct` requires a reason\n");
+                               ShowUsage();
+                               return RV_ARGUMENTS;
+                       }
+                       
                        // Authentication required
-                       if( Authenticate(sock) )
-                               return -1;
+                       ret = Authenticate(sock);
+                       if(ret) return ret;
                        
                        // text_args[1]: Username
                        // text_args[2]: Ammount
@@ -262,12 +373,12 @@ int main(int argc, char *argv[])
        //
        // `dispense give`
        // - "Here, have some money."
-       if( strcmp(text_args[0], "give") == 0 )
+       else if( strcmp(text_args[0], "give") == 0 )
        {
                if( text_argc != 4 ) {
                        fprintf(stderr, "`dispense give` takes three arguments\n");
                        ShowUsage();
-                       return -1;
+                       return RV_ARGUMENTS;
                }
                
                // text_args[1]: Destination
@@ -276,11 +387,11 @@ int main(int argc, char *argv[])
                
                // Connect to server
                sock = OpenConnection(gsDispenseServer, giDispensePort);
-               if( sock < 0 )  return -1;
+               if( sock < 0 )  return RV_SOCKET_ERROR;
                
                // Authenticate
-               if( Authenticate(sock) )
-                       return -1;
+               ret = Authenticate(sock);
+               if(ret) return ret;
                
                ret = Dispense_Give(sock, text_args[1], atoi(text_args[2]), text_args[3]);
 
@@ -297,16 +408,16 @@ int main(int argc, char *argv[])
                if( text_argc == 1 ) {
                        fprintf(stderr, "Error: `dispense user` requires arguments\n");
                        ShowUsage();
-                       exit(1);
+                       return RV_ARGUMENTS;
                }
                
                // Connect to server
                sock = OpenConnection(gsDispenseServer, giDispensePort);
-               if( sock < 0 )  return -1;
+               if( sock < 0 )  return RV_SOCKET_ERROR;
                
                // Attempt authentication
-               if( Authenticate(sock) )
-                       return -1;
+               ret = Authenticate(sock);
+               if(ret) return ret;
                
                // Add new user?
                if( strcmp(text_args[1], "add") == 0 )
@@ -314,7 +425,7 @@ int main(int argc, char *argv[])
                        if( text_argc != 3 ) {
                                fprintf(stderr, "Error: `dispense user add` requires an argument\n");
                                ShowUsage();
-                               exit(1);
+                               return RV_ARGUMENTS;
                        }
                        
                        ret = Dispense_AddUser(sock, text_args[2]);
@@ -325,7 +436,7 @@ int main(int argc, char *argv[])
                        if( text_argc != 4 ) {
                                fprintf(stderr, "Error: `dispense user flags` requires two arguments\n");
                                ShowUsage();
-                               exit(1);
+                               return RV_ARGUMENTS;
                        }
                        
                        ret = Dispense_SetUserType(sock, text_args[2], text_args[3]);
@@ -334,7 +445,7 @@ int main(int argc, char *argv[])
                {
                        fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
                        ShowUsage();
-                       exit(1);
+                       return RV_ARGUMENTS;
                }
                close(sock);
                return ret;
@@ -346,24 +457,58 @@ int main(int argc, char *argv[])
                if( text_argc != 3 ) {
                        fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
                        ShowUsage();
-                       exit(1);
+                       return RV_ARGUMENTS;
                }
                
                // Connect to server
                sock = OpenConnection(gsDispenseServer, giDispensePort);
-               if( sock < 0 )  return -1;
+               if( sock < 0 )  return RV_SOCKET_ERROR;
                
                // Attempt authentication
-               if( Authenticate(sock) )
-                       return -1;
+               ret = Authenticate(sock);
+               if(ret) return ret;
                
                // Do donation
-               ret =Dispense_Donate(sock, atoi(text_args[1]), text_args[2]);
+               ret = Dispense_Donate(sock, atoi(text_args[1]), text_args[2]);
                                
                close(sock);
 
                return ret;
        }
+       // Refund an item
+       else if( strcmp(text_args[0], "refund") == 0 )
+       {
+                int     price = 0;
+               // Check argument count
+               if( text_argc != 3 && text_argc != 4 ) {
+                       fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
+                       ShowUsage();
+                       return RV_ARGUMENTS;
+               }
+       
+               // Connect to server
+               sock = OpenConnection(gsDispenseServer, giDispensePort);
+               if(sock < 0)    return RV_SOCKET_ERROR; 
+
+               // Attempt authentication
+               ret = Authenticate(sock);
+               if(ret) return ret;
+
+               if( text_argc == 4 ) {
+                       price = atoi(text_args[3]);
+                       if( price <= 0 ) {
+                               fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
+                               return RV_ARGUMENTS;
+                       }
+               }
+
+               // Username, Item, cost
+               ret = Dispense_Refund(sock, text_args[1], text_args[2], price);
+
+               // TODO: More
+               close(sock);
+               return RV_UNKNOWN_ERROR;
+       }
        // Query an item price
        else if( strcmp(text_args[0], "iteminfo") == 0 )
        {
@@ -374,34 +519,92 @@ int main(int argc, char *argv[])
                if( text_argc != 2 ) {
                        fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
                        ShowUsage();
-                       exit(1);
+                       return RV_ARGUMENTS;
                }
                // Parse item ID
                if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
                        fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
-                       exit(1);
+                       return RV_ARGUMENTS;
                }
                type = text_args[1] + matches[1].rm_so;
                text_args[1][ matches[1].rm_eo ] = '\0';
                id = atoi( text_args[1] + matches[2].rm_so );
 
                sock = OpenConnection(gsDispenseServer, giDispensePort);
-               if( sock < 0 )  return -1;
+               if( sock < 0 )  return RV_SOCKET_ERROR;
+               
                ret = Dispense_ItemInfo(sock, type, id);
                close(sock);
                return ret;
        }
+       // Set slot
+       else if( strcmp(text_args[0], "slot") == 0 )
+       {
+               regmatch_t matches[3];
+               char    *item_type, *newname;
+                int    item_id, price;
+               
+               // Check arguments
+               if( text_argc != 4 ) {
+                       fprintf(stderr, "Error: `dispense slot` takes three arguments\n");
+                       ShowUsage();
+                       return RV_ARGUMENTS;
+               }
+               
+               // Parse arguments
+               if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
+                       fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
+                       return RV_ARGUMENTS;
+               }
+               item_type = text_args[1] + matches[1].rm_so;
+               text_args[1][ matches[1].rm_eo ] = '\0';
+               item_id = atoi( text_args[1] + matches[2].rm_so );
+
+               // - Price
+               price = atoi( text_args[2] );
+               if( price <= 0 && text_args[2][0] != '0' ) {
+                       fprintf(stderr, "Error: Invalid price passed (must be >= 0)\n");
+                       return RV_ARGUMENTS;
+               }
+               
+               // - New name
+               newname = text_args[3];
+               // -- Sanity
+               {
+                       char *pos;
+                       for( pos = newname; *pos; pos ++ )
+                       {
+                               if( !isalnum(*pos) && *pos != ' ' ) {
+                                       fprintf(stderr, "Error: You should only have letters, numbers and spaces in an item name\n");
+                                       return RV_ARGUMENTS;
+                               }
+                       }
+               }
+               
+               // Connect & Authenticate
+               sock = OpenConnection(gsDispenseServer, giDispensePort);
+               if( sock < 0 )  return RV_SOCKET_ERROR;
+               ret = Authenticate(sock);
+               if(ret) return ret;
+               // Update the slot
+               ret = Dispense_SetItem(sock, item_type, item_id, price, newname);
+               
+               close(sock);
+               return ret;
+       }
        // Item name / pattern
-       else {
+       else
+       {
                gsItemPattern = text_args[0];
        }
        
        // Connect to server
        sock = OpenConnection(gsDispenseServer, giDispensePort);
-       if( sock < 0 )  return -1;
+       if( sock < 0 )  return RV_SOCKET_ERROR;
 
        // Get the user's balance
-       GetUserBalance(sock);
+       ret = GetUserBalance(sock);
+       if(ret) return ret;
 
        // Get items
        PopulateItemList(sock);
@@ -417,8 +620,9 @@ int main(int argc, char *argv[])
                {
                        // Connect, Authenticate, dispense and close
                        sock = OpenConnection(gsDispenseServer, giDispensePort);
-                       if( sock < 0 )  return -1;
-                       Authenticate(sock);
+                       if( sock < 0 )  return RV_SOCKET_ERROR;
+                       ret = Authenticate(sock);
+                       if(ret) return ret;
                        ret = DispenseItem(sock, "door", 0);
                        close(sock);
                        return ret;
@@ -437,11 +641,12 @@ int main(int argc, char *argv[])
                        
                        // Connect, Authenticate, dispense and close
                        sock = OpenConnection(gsDispenseServer, giDispensePort);
-                       if( sock < 0 )  return -1;
+                       if( sock < 0 )  return RV_SOCKET_ERROR;
                        
                        Dispense_ItemInfo(sock, ident, id);
                        
-                       Authenticate(sock);
+                       ret = Authenticate(sock);
+                       if(ret) return ret;
                        ret = DispenseItem(sock, ident, id);
                        close(sock);
                        return ret;
@@ -485,7 +690,7 @@ int main(int argc, char *argv[])
                                        // TODO: Allow ambiguous matches?
                                        // or just print a wanrning
                                        printf("Warning - Ambiguous pattern, stopping\n");
-                                       return 1;
+                                       return RV_BAD_ITEM;
                                }
                        }
                        
@@ -493,7 +698,7 @@ int main(int argc, char *argv[])
                        if( best == -1 )
                        {
                                fprintf(stderr, "No item matches the passed string\n");
-                               return 1;
+                               return RV_BAD_ITEM;
                        }
                        
                        i = best;
@@ -544,63 +749,30 @@ int main(int argc, char *argv[])
        // Check for a valid item ID
        if( i >= 0 )
        {
+                int j;
                // Connect, Authenticate, dispense and close
                sock = OpenConnection(gsDispenseServer, giDispensePort);
-               if( sock < 0 )  return -1;
+               if( sock < 0 )  return RV_SOCKET_ERROR;
                        
-               Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
+               ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
+               if(ret) return ret;
+               
+               ret = Authenticate(sock);
+               if(ret) return ret;
                
-               Authenticate(sock);
-               ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
+               for( j = 0; j < giDispenseCount; j ++ ) {
+                       ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
+                       if( ret )       break;
+               }
+               if( j > 1 ) {
+                       printf("%i items dispensed\n", j);
+               }
                close(sock);
        }
 
        return ret;
 }
 
-void ShowUsage(void)
-{
-       printf(
-               "Usage:\n"
-               "  == Everyone ==\n"
-               "    dispense\n"
-               "        Show interactive list\n"
-               "    dispense <name>|<index>|<itemid>\n"
-               "        Dispense named item (<name> matches if it is a unique prefix)\n"
-               "    dispense give <user> <ammount> \"<reason>\"\n"
-               "        Give money to another user\n"
-               "    dispense donate <ammount> \"<reason>\"\n"
-               "        Donate to the club\n"
-               "    dispense iteminfo <type>:<id>\n"
-               "        Get the name and price for an item\n"
-               "  == Coke members == \n"
-               "    dispense acct [<user>]\n"
-               "        Show user balances\n"
-               "    dispense acct <user> [+-]<ammount> \"<reason>\"\n"
-               "        Alter a account value\n"
-               "  == Dispense administrators ==\n"
-               "    dispense acct <user> =<ammount> \"<reason>\"\n"
-               "        Set an account balance\n"
-               "    dispense user add <user>\n"
-               "        Create new coke account (Admins only)\n"
-               "    dispense user type <user> <flags>\n"
-               "        Alter a user's flags\n"
-               "        <flags> is a comma-separated list of user, coke, admin or disabled\n"
-               "        Flags are removed by preceding the name with '-' or '!'\n"
-               "\n"
-               "General Options:\n"
-               "    -u <username>\n"
-               "        Set a different user (Coke members only)\n"
-               "    -h / -?\n"
-               "        Show help text\n"
-               "    -G\n"
-               "        Use alternate GUI\n"
-               "    -m <min balance>\n"
-               "    -M <max balance>\n"
-               "        Set the Maximum/Minimum balances shown in `dispense acct`\n"
-               );
-}
-
 // -------------------
 // --- NCurses GUI ---
 // -------------------
@@ -609,9 +781,6 @@ void ShowUsage(void)
  */
 int ShowNCursesUI(void)
 {
-       // TODO: ncurses interface (with separation between item classes)
-       // - Hmm... that would require standardising the item ID to be <class>:<index>
-       // Oh, why not :)
         int    ch;
         int    i, times;
         int    xBase, yBase;
@@ -637,11 +806,11 @@ int ShowNCursesUI(void)
                username = pwd->pw_name;
        }
        // Get balance
-       snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, giUserBalance%100);
+       snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
        
        // Enter curses mode
        initscr();
-       raw(); noecho();
+       cbreak(); noecho();
        
        // Get max index
        maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
@@ -784,6 +953,7 @@ int ShowNCursesUI(void)
                        case '\n':
                                ret = ShowItemAt(0, 0, 0, currentItem, 0);
                                break;
+                       case 0x1b:      // Escape
                        case 'q':
                                ret = -1;       // -1: Return with no dispense
                                break;
@@ -861,6 +1031,8 @@ int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
        // Width = 0, don't print
        if( Width > 0 )
        {
+               // 4 preceding, 5 price
+               int nameWidth = Width - 4 - 5;
                move( Row, Col );
                
                if( Index >= 0 )
@@ -870,26 +1042,26 @@ int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
                        {
                        case 0:
                                if( bHilighted )
-                                       printw("-> ");
+                                       printw("->  ");
                                else
-                                       printw("   ");
+                                       printw("    ");
                                break;
                        case 1:
-                               printw("SLD");
+                               printw("SLD ");
                                break;
                        
                        default:
                        case -1:
-                               printw("ERR");
+                               printw("ERR ");
                                break;
                        }
                        
-                       printw(" %s", name);
+                       printw("%-*.*s", nameWidth, nameWidth, name);
                
-                       getyx(stdscr, _y, _x);
+//                     getyx(stdscr, _y, _x);
                        // Assumes max 4 digit prices
-                       times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
-                       while(times--)  addch(' ');
+//                     times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
+//                     while(times--)  addch(' ');
                        
                        printw(" %4i", price);
                }
@@ -1027,6 +1199,9 @@ int OpenConnection(const char *Host, int Port)
                fprintf(stderr, "Failed to connect to server\n");
                return -1;
        }
+
+       // We're not authenticated if the connection has just opened
+       gbIsAuthenticated = 0;
        
        return sock;
 }
@@ -1040,9 +1215,11 @@ int Authenticate(int Socket)
        struct passwd   *pwd;
        char    *buf;
         int    responseCode;
+       #if ATTEMPT_PASSWORD_AUTH
        char    salt[32];
         int    i;
        regmatch_t      matches[4];
+       #endif
        
        if( gbIsAuthenticated ) return 0;
        
@@ -1064,7 +1241,8 @@ int Authenticate(int Socket)
        
        case 401:       // Untrusted, attempt password authentication
                free(buf);
-               
+
+               #if ATTEMPT_PASSWORD_AUTH       
                sendf(Socket, "USER %s\n", pwd->pw_name);
                printf("Using username %s\n", pwd->pw_name);
                
@@ -1078,7 +1256,7 @@ int Authenticate(int Socket)
                if( responseCode != 100 ) {
                        fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
                        free(buf);
-                       return -1;      // ERROR
+                       return RV_UNKNOWN_ERROR;        // ERROR
                }
                
                // Check for salt
@@ -1124,23 +1302,28 @@ int Authenticate(int Socket)
                        
                        fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
                        free(buf);
-                       return -1;
+                       return RV_UNKNOWN_ERROR;
                }
                free(buf);
                if( i == 3 )
-                       return 2;       // 2 = Bad Password
+                       return RV_INVALID_USER; // 2 = Bad Password
+               
+               #else
+               fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
+               return RV_INVALID_USER;
+               #endif
                break;
        
        case 404:       // Bad Username
                fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
                free(buf);
-               return 1;
+               return RV_INVALID_USER;
        
        default:
                fprintf(stderr, "Unkown response code %i from server\n", responseCode);
                printf("%s\n", buf);
                free(buf);
-               return -1;
+               return RV_UNKNOWN_ERROR;
        }
        
        // Set effective user
@@ -1159,18 +1342,18 @@ int Authenticate(int Socket)
                case 403:
                        printf("Only coke members can use `dispense -u`\n");
                        free(buf);
-                       return -1;
+                       return RV_PERMISSIONS;
                
                case 404:
                        printf("Invalid user selected\n");
                        free(buf);
-                       return -1;
+                       return RV_INVALID_USER;
                
                default:
                        fprintf(stderr, "Unkown response code %i from server\n", responseCode);
                        printf("%s\n", buf);
                        free(buf);
-                       exit(-1);
+                       return RV_UNKNOWN_ERROR;
                }
                
                free(buf);
@@ -1209,13 +1392,13 @@ int GetUserBalance(int Socket)
        case 404:
                printf("Invalid user? (USER_INFO failed)\n");
                free(buf);
-               return -1;
+               return RV_INVALID_USER;
        
        default:
                fprintf(stderr, "Unkown response code %i from server\n", responseCode);
                printf("%s\n", buf);
                free(buf);
-               exit(-1);
+               return RV_UNKNOWN_ERROR;
        }
 
        RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
@@ -1251,11 +1434,12 @@ int ReadItemInfo(int Socket, tItem *Dest)
        case 406:
                printf("Bad item name\n");
                free(buf);
-               return 1;
+               return RV_BAD_ITEM;
        
        default:
                fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
-               exit(-1);
+               free(buf);
+               return RV_UNKNOWN_ERROR;
        }
        
        RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
@@ -1277,7 +1461,7 @@ int ReadItemInfo(int Socket, tItem *Dest)
        else {
                fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
                        statusStr);
-               return 1;
+               return RV_UNKNOWN_ERROR;
        }
        Dest->Price = atoi( buf + matches[6].rm_so );
        
@@ -1317,7 +1501,7 @@ void PopulateItemList(int Socket)
        responseCode = atoi(buf);
        if( responseCode != 201 ) {
                fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
-               exit(-1);
+               exit(RV_UNKNOWN_ERROR);
        }
        
        // - Get item list -
@@ -1335,7 +1519,7 @@ void PopulateItemList(int Socket)
                // What the?!
                fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
                        itemType);
-               exit(-1);
+               exit(RV_UNKNOWN_ERROR);
        }
                
        itemStart = &buf[ matches[3].rm_eo ];
@@ -1373,14 +1557,13 @@ void PopulateItemList(int Socket)
 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
 {
        tItem   item;
+        int    ret;
        
        // Query
        sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
        
-       if( ReadItemInfo(Socket, &item) )
-       {
-               return -1;
-       }
+       ret = ReadItemInfo(Socket, &item);
+       if(ret) return ret;
        
        printf("%8s:%-2i %2i.%02i %s\n",
                item.Type, item.ID,
@@ -1421,27 +1604,27 @@ int DispenseItem(int Socket, const char *Type, int ID)
                break;
        case 401:
                printf("Not authenticated\n");
-               ret = 1;
+               ret = RV_PERMISSIONS;
                break;
        case 402:
                printf("Insufficient balance\n");
-               ret = 1;
+               ret = RV_BALANCE;
                break;
        case 406:
                printf("Bad item name\n");
-               ret = 1;
+               ret = RV_BAD_ITEM;
                break;
        case 500:
                printf("Item failed to dispense, is the slot empty?\n");
-               ret = 1;
+               ret = RV_SERVER_ERROR;
                break;
        case 501:
                printf("Dispense not possible (slot empty/permissions)\n");
-               ret = 1;
+               ret = RV_SERVER_ERROR;
                break;
        default:
                printf("Unknown response code %i ('%s')\n", responseCode, buf);
-               ret = -2;
+               ret = RV_UNKNOWN_ERROR;
                break;
        }
        
@@ -1462,6 +1645,12 @@ int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const c
                printf("Dry Run - No action\n");
                return 0;
        }
+
+       // Sanity
+       if( Ammount == 0 ) {
+               printf("An ammount would be nice\n");
+               return RV_ARGUMENTS;
+       }
        
        sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
        buf = ReadLine(Socket);
@@ -1474,16 +1663,16 @@ int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const c
        case 200:       return 0;       // OK
        case 402:
                fprintf(stderr, "Insufficient balance\n");
-               return 1;
+               return RV_BAD_ITEM;
        case 403:       // Not in coke
                fprintf(stderr, "You are not in coke (sucker)\n");
-               return 1;
+               return RV_PERMISSIONS;
        case 404:       // Unknown user
                fprintf(stderr, "Unknown user '%s'\n", Username);
-               return 2;
+               return RV_INVALID_USER;
        default:
                fprintf(stderr, "Unknown response code %i\n", responseCode);
-               return -1;
+               return RV_UNKNOWN_RESPONSE;
        }
        
        return -1;
@@ -1515,13 +1704,13 @@ int Dispense_SetBalance(int Socket, const char *Username, int Balance, const cha
        case 200:       return 0;       // OK
        case 403:       // Not in coke
                fprintf(stderr, "You are not an admin\n");
-               return 1;
+               return RV_PERMISSIONS;
        case 404:       // Unknown user
                fprintf(stderr, "Unknown user '%s'\n", Username);
-               return 2;
+               return RV_INVALID_USER;
        default:
                fprintf(stderr, "Unknown response code %i\n", responseCode);
-               return -1;
+               return RV_UNKNOWN_RESPONSE;
        }
        
        return -1;
@@ -1537,13 +1726,13 @@ int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Rea
        
        if( Ammount < 0 ) {
                printf("Sorry, you can only give, you can't take.\n");
-               return -1;
+               return RV_ARGUMENTS;
        }
        
        // Fast return on zero
        if( Ammount == 0 ) {
                printf("Are you actually going to give any?\n");
-               return 0;
+               return RV_ARGUMENTS;
        }
        
        // Check for a dry run
@@ -1553,33 +1742,82 @@ int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Rea
        }
        
        sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
+
        buf = ReadLine(Socket);
-       
        responseCode = atoi(buf);
-       free(buf);
-       
+       free(buf);      
        switch(responseCode)
        {
        case 200:
                printf("Give succeeded\n");
-               return 0;       // OK
+               return RV_SUCCESS;      // OK
        
        case 402:       
                fprintf(stderr, "Insufficient balance\n");
-               return 1;
+               return RV_BALANCE;
        
        case 404:       // Unknown user
                fprintf(stderr, "Unknown user '%s'\n", Username);
-               return 2;
+               return RV_INVALID_USER;
        
        default:
                fprintf(stderr, "Unknown response code %i\n", responseCode);
-               return -1;
+               return RV_UNKNOWN_RESPONSE;
        }
        
        return -1;
 }
 
+int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
+{
+       char    *buf;
+        int    responseCode, ret = -1;
+       
+       // Check item id
+       if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
+       {
+               fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
+               return RV_ARGUMENTS;
+       }
+
+       // Check username (quick)
+       if( strchr(Username, ' ') || strchr(Username, '\n') )
+       {
+               fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
+               return RV_ARGUMENTS;
+       }
+
+       // Send the query
+       sendf(Socket, "REFUND %s %s %i\n", Username, Item, PriceOverride);
+
+       buf = ReadLine(Socket);
+       responseCode = atoi(buf);
+       switch(responseCode)
+       {
+       case 200:
+               Dispense_ShowUser(Socket, Username);    // Show destination account
+               ret = 0;
+               break;
+       case 403:
+               fprintf(stderr, "Refund access is only avaliable to coke members\n");
+               ret = RV_PERMISSIONS;
+               break;
+       case 404:
+               fprintf(stderr, "Unknown user '%s' passed\n", Username);
+               ret = RV_INVALID_USER;
+               break;
+       case 406:
+               fprintf(stderr, "Invalid item '%s' passed\n", Item);
+               ret = RV_BAD_ITEM;
+               break;
+       default:
+               fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
+               ret = -1;
+               break;
+       }
+       free(buf);
+       return ret;
+}
 
 /**
  * \brief Donate money to the club
@@ -1597,7 +1835,7 @@ int Dispense_Donate(int Socket, int Ammount, const char *Reason)
        // Fast return on zero
        if( Ammount == 0 ) {
                printf("Are you actually going to give any?\n");
-               return 0;
+               return 1;
        }
        
        // Check for a dry run
@@ -1827,18 +2065,62 @@ int Dispense_SetUserType(int Socket, const char *Username, const char *TypeStrin
                
        case 403:
                printf("Only wheel can modify users\n");
-               ret = 1;
+               ret = RV_PERMISSIONS;
                break;
        
        case 404:
                printf("User '%s' does not exist\n", Username);
-               ret = 0;
+               ret = RV_INVALID_USER;
                break;
        
        case 407:
                printf("Flag string is invalid\n");
+               ret = RV_ARGUMENTS;
+               break;
+       
+       default:
+               fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
+               ret = RV_UNKNOWN_RESPONSE;
+               break;
+       }
+       
+       free(buf);
+       
+       return ret;
+}
+
+int Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName)
+{
+       char    *buf;
+        int    responseCode, ret;
+       
+       // Check for a dry run
+       if( gbDryRun ) {
+               printf("Dry Run - No action\n");
+               return 0;
+       }
+       
+       sendf(Socket, "UPDATE_ITEM %s:%i %i %s\n", Type, ID, NewPrice, NewName);
+       
+       buf = ReadLine(Socket);
+       responseCode = atoi(buf);
+       
+       switch(responseCode)
+       {
+       case 200:
+               printf("Item %s:%i updated\n", Type, ID);
                ret = 0;
                break;
+               
+       case 403:
+               printf("Only coke members can modify the slots\n");
+               ret = RV_PERMISSIONS;
+               break;
+       
+       case 406:
+               printf("Invalid item passed\n");
+               ret = RV_BAD_ITEM;
+               break;
        
        default:
                fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
@@ -1878,6 +2160,10 @@ char *ReadLine(int Socket)
                }
                else {
                        len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
+                       if( len < 0 ) {
+                               free(ret);
+                               return strdup("499 Client Connection Error\n");
+                       }
                        buf[bufPos+len] = '\0';
                }
                

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