Cleanup work (much needed)
[tpg/opendispense2.git] / src / client / main.c
index 8411181..3dd5e2f 100644 (file)
  * This file is licenced under the 3-clause BSD Licence. See the file
  * COPYING for full details.
  */
+#include <stdlib.h>
 #include <stdio.h>
+#include <string.h>
+#include <ctype.h>     // isspace
+#include <stdarg.h>
+#include <regex.h>
+#include <ncurses.h>
+
+#include <unistd.h>    // close
+#include <netdb.h>     // gethostbyname
+#include <pwd.h>       // getpwuids
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <openssl/sha.h>       // SHA1
+
+#define        USE_NCURSES_INTERFACE   0
+
+// === TYPES ===
+typedef struct sItem {
+       char    *Ident;
+       char    *Desc;
+        int    Price;
+}      tItem;
+
+// === PROTOTYPES ===
+ int   ShowNCursesUI(void);
+void   PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
+
+ int   sendf(int Socket, const char *Format, ...);
+
+ int   OpenConnection(const char *Host, int Port);
+ int   Authenticate(int Socket);
+void   PopulateItemList(int Socket);
+ int   DispenseItem(int Socket, int ItemID);
+
+char   *trim(char *string);
+ int   RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
+void   CompileRegex(regex_t *regex, const char *pattern, int flags);
 
 // === GLOBALS ===
-char   *gsDispenseServer = "martello";
+char   *gsDispenseServer = "localhost";
  int   giDispensePort = 11020;
+tItem  *gaItems;
+ int   giNumItems;
+regex_t        gArrayRegex, gItemRegex, gSaltRegex;
+
+char   *gsOverrideUser;
 
 // === CODE ===
 int main(int argc, char *argv[])
 {
+        int    sock;
+        int    i;
+       char    buffer[BUFSIZ];
+       
+       // -- Create regular expressions
+       // > Code Type Count ...
+       CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED);     //
+       // > Code Type Ident Price Desc
+       CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z0-9:]+?)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
+       // > Code 'SALT' salt
+       CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+(.+)\\s+(.+)$", REG_EXTENDED);
+       
        // Connect to server
+       sock = OpenConnection(gsDispenseServer, giDispensePort);
+       if( sock < 0 )  return -1;
+
+       // Authenticate
+       Authenticate(sock);
+
+       // Parse Arguments
+       for( i = 1; i < argc; i ++ )
+       {
+               char    *arg = argv[i];
+               
+               if( arg[0] == '-' ) {
+                                       
+                       switch(arg[1])
+                       {
+                       case 'u':       // Override User
+                               gsOverrideUser = argv[++i];
+                               break;
+                       }
+
+                       continue;
+               }
+               if( strcmp(argv[1], "acct") == 0 ) {
+                       // Alter account
+                       // List accounts
+                       return 0;
+               }
+               else {
+                       // Item name / pattern
+               }
+       }
+
+       // Get items
+       PopulateItemList(sock);
+       
+       #if USE_NCURSES_INTERFACE
+               i = ShowNCursesUI();
+       #else
+               for( i = 0; i < giNumItems; i ++ ) {            
+                       printf("%2i %s\t%3i %s\n", i, gaItems[i].Ident, gaItems[i].Price, gaItems[i].Desc);
+               }
+               printf(" q Quit\n");
+               for(;;)
+               {
+                       char    *buf;
+                       
+                       i = -1;
+                       
+                       fgets(buffer, BUFSIZ, stdin);
+                       
+                       buf = trim(buffer);
+                       
+                       if( buf[0] == 'q' )     break;
+                       
+                       i = atoi(buf);
+                       
+                       if( i != 0 || buf[0] == '0' )
+                       {
+                               if( i < 0 || i >= giNumItems ) {
+                                       printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
+                                       continue;
+                               }
+                               break;
+                       }
+               }
+       #endif
+       
+       // Check for a valid item ID
+       if( i >= 0 )
+               DispenseItem(sock, i);
+
+       close(sock);
+
+       return 0;
+}
+
+/**
+ * \brief Show item \a Index at (\a Col, \a Row)
+ * \note Part of the NCurses UI
+ */
+void ShowItemAt(int Row, int Col, int Width, int Index)
+{
+        int    _x, _y, times;
        
+       move( Row, Col );
+       
+       if( Index < 0 || Index >= giNumItems ) {
+               printw("%02i OOR", Index);
+               return ;
+       }
+       printw("%02i %s", Index, gaItems[Index].Desc);
+       
+       getyx(stdscr, _y, _x);
+       // Assumes max 4 digit prices
+       times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
+       while(times--)  addch(' ');
+       printw("%4i", gaItems[Index].Price);
+}
 
-       // Determine what to do
-       if( argc > 1 )
+/**
+ * \brief Render the NCurses UI
+ */
+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;
+       const int       displayMinWidth = 40;
+       const int       displayMinItems = 8;
+       char    *titleString = "Dispense";
+        int    itemCount = displayMinItems;
+        int    itemBase = 0;
+        
+        int    height = itemCount + 3;
+        int    width = displayMinWidth;
+        
+       // Enter curses mode
+       initscr();
+       raw(); noecho();
+       
+       xBase = COLS/2 - width/2;
+       yBase = LINES/2 - height/2;
+       
+       for( ;; )
        {
-               if( strcmp(argv[1], "acct") == 0 )
+               // Header
+               PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
+               
+               // Items
+               for( i = 0; i < itemCount; i ++ )
                {
-                       return 0;
+                       move( yBase + 1 + i, xBase );
+                       addch('|');
+                       addch(' ');
+                       
+                       // Check for ... row
+                       if( i == 0 && itemBase > 0 ) {
+                               printw("   ...");
+                               times = width - 1 - 8;
+                               while(times--)  addch(' ');
+                       }
+                       else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
+                               printw("   ...");
+                               times = width - 1 - 8;
+                               while(times--)  addch(' ');
+                       }
+                       // Show an item
+                       else {
+                               ShowItemAt( yBase + 1 + i, xBase + 2, width - 4, itemBase + i);
+                               addch(' ');
+                       }
+                       
+                       // Scrollbar (if needed)
+                       if( giNumItems > itemCount ) {
+                               if( i == 0 ) {
+                                       addch('A');
+                               }
+                               else if( i == itemCount - 1 ) {
+                                       addch('V');
+                               }
+                               else {
+                                        int    percentage = itemBase * 100 / (giNumItems-itemCount);
+                                       if( i-1 == percentage*(itemCount-3)/100 ) {
+                                               addch('#');
+                                       }
+                                       else {
+                                               addch('|');
+                                       }
+                               }
+                       }
+                       else {
+                               addch('|');
+                       }
+               }
+               
+               // Footer
+               PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
+               
+               // Get input
+               ch = getch();
+               
+               if( ch == '\x1B' ) {
+                       ch = getch();
+                       if( ch == '[' ) {
+                               ch = getch();
+                               
+                               switch(ch)
+                               {
+                               case 'B':
+                                       if( itemBase < giNumItems - (itemCount) )
+                                               itemBase ++;
+                                       break;
+                               case 'A':
+                                       if( itemBase > 0 )
+                                               itemBase --;
+                                       break;
+                               }
+                       }
+                       else {
+                               
+                       }
+               }
+               else {
+                       break;
+               }
+               
+       }
+       
+       
+       // Leave
+       endwin();
+       return -1;
+}
+
+/**
+ * \brief Print a three-part string at the specified position (formatted)
+ * \note NCurses UI Helper
+ * 
+ * Prints \a Left on the left of the area, \a Right on the righthand side
+ * and \a Mid in the middle of the area. These are padded with \a Pad1
+ * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
+ * 
+ * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
+ * and the arguments to these are read in that order.
+ */
+void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
+       const char *Mid, char Pad2, const char *Right, ...)
+{
+        int    lLen, mLen, rLen;
+        int    times;
+       
+       va_list args;
+       
+       // Get the length of the strings
+       va_start(args, Right);
+       lLen = vsnprintf(NULL, 0, Left, args);
+       mLen = vsnprintf(NULL, 0, Mid, args);
+       rLen = vsnprintf(NULL, 0, Right, args);
+       va_end(args);
+       
+       // Sanity check
+       if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
+               return ;        // TODO: What to do?
+       }
+       
+       move(Row, Col);
+       
+       // Render strings
+       va_start(args, Right);
+       // - Left
+       {
+               char    tmp[lLen+1];
+               vsnprintf(tmp, lLen+1, Left, args);
+               addstr(tmp);
+       }
+       // - Left padding
+       times = Width/2 - mLen/2 - lLen;
+       while(times--)  addch(Pad1);
+       // - Middle
+       {
+               char    tmp[mLen+1];
+               vsnprintf(tmp, mLen+1, Mid, args);
+               addstr(tmp);
+       }
+       // - Right Padding
+       times = Width/2 - mLen/2 - rLen;
+       while(times--)  addch(Pad2);
+       // - Right
+       {
+               char    tmp[rLen+1];
+               vsnprintf(tmp, rLen+1, Right, args);
+               addstr(tmp);
+       }
+}
+
+// === HELPERS ===
+int sendf(int Socket, const char *Format, ...)
+{
+       va_list args;
+        int    len;
+       
+       va_start(args, Format);
+       len = vsnprintf(NULL, 0, Format, args);
+       va_end(args);
+       
+       {
+               char    buf[len+1];
+               va_start(args, Format);
+               vsnprintf(buf, len+1, Format, args);
+               va_end(args);
+               
+               return send(Socket, buf, len, 0);
+       }
+}
+
+int OpenConnection(const char *Host, int Port)
+{
+       struct hostent  *host;
+       struct sockaddr_in      serverAddr;
+        int    sock;
+       
+       host = gethostbyname(Host);
+       if( !host ) {
+               fprintf(stderr, "Unable to look up '%s'\n", Host);
+               return -1;
+       }
+       
+       memset(&serverAddr, 0, sizeof(serverAddr));
+       
+       serverAddr.sin_family = AF_INET;        // IPv4
+       // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
+       serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
+       serverAddr.sin_port = htons(Port);
+       
+       sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
+       if( sock < 0 ) {
+               fprintf(stderr, "Failed to create socket\n");
+               return -1;
+       }
+       
+       #if USE_AUTOAUTH
+       {
+               struct sockaddr_in      localAddr;
+               memset(&localAddr, 0, sizeof(localAddr));
+               localAddr.sin_family = AF_INET; // IPv4
+               localAddr.sin_port = 1023;      // IPv4
+               // Attempt to bind to low port for autoauth
+               bind(sock, &localAddr, sizeof(localAddr));
+       }
+       #endif
+       
+       if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
+               fprintf(stderr, "Failed to connect to server\n");
+               return -1;
+       }
+       
+       return sock;
+}
+
+/**
+ * \brief Authenticate with the server
+ * \return Boolean Failure
+ */
+int Authenticate(int Socket)
+{
+       struct passwd   *pwd;
+       char    buf[512];
+        int    responseCode;
+       char    salt[32];
+        int    i;
+       regmatch_t      matches[4];
+       
+       // Get user name
+       pwd = getpwuid( getuid() );
+       
+       // Attempt automatic authentication
+       sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
+       
+       // Check if it worked
+       recv(Socket, buf, 511, 0);
+       trim(buf);
+       
+       responseCode = atoi(buf);
+       switch( responseCode )
+       {
+       case 200:       // Authenticated, return :)
+               return 0;
+       case 401:       // Untrusted, attempt password authentication
+               sendf(Socket, "USER %s\n", pwd->pw_name);
+               printf("Using username %s\n", pwd->pw_name);
+               
+               recv(Socket, buf, 511, 0);
+               trim(buf);
+               // TODO: Get Salt
+               // Expected format: 100 SALT <something> ...
+               // OR             : 100 User Set
+               RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
+               responseCode = atoi(buf);
+               if( responseCode != 100 ) {
+                       fprintf(stderr, "Unknown repsonse code %i from server\n", responseCode);
+                       return -1;      // ERROR
                }
+               
+               // Check for salt
+               if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
+                       memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
+                       salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
+               }
+               
+               // Get password
+               fflush(stdout);
+               
+               // Give three attempts
+               for( i = 0; i < 3; i ++ )
+               {
+                        int    ofs = strlen(pwd->pw_name)+strlen(salt);
+                       char    tmp[ofs+20];
+                       char    *pass = getpass("Password: ");
+                       uint8_t h[20];
+                       
+                       // Create hash string
+                       // <username><salt><hash>
+                       strcpy(tmp, pwd->pw_name);
+                       strcat(tmp, salt);
+                       SHA1( (unsigned char*)pass, strlen(pass), h );
+                       memcpy(tmp+ofs, h, 20);
+                       
+                       // Hash all that
+                       SHA1( (unsigned char*)tmp, ofs+20, h );
+                       sprintf(buf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
+                               h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
+                               h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
+                               );
+                       fflush(stdout); // Debug
+               
+                       // Send password
+                       sendf(Socket, "PASS %s\n", buf);
+                       recv(Socket, buf, 511, 0);
+               
+                       responseCode = atoi(buf);
+                       // Auth OK?
+                       if( responseCode == 200 )       break;
+                       // Bad username/password
+                       if( responseCode == 401 )       continue;
+                       
+                       fprintf(stderr, "Unknown repsonse code %i from server\n", responseCode);
+                       return -1;
+               }
+               return 2;       // 2 = Bad Password
+       
+       case 404:       // Bad Username
+               fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
+               return 1;
+       
+       default:
+               fprintf(stderr, "Unkown response code %i from server\n", responseCode);
+               printf("%s\n", buf);
+               return -1;
        }
+       
+       printf("%s\n", buf);
+       return 0;       // Seems OK
+}
 
+void PopulateItemList(int Socket)
+{
+       char    buffer[BUFSIZ];
+        int    len;
+        int    responseCode;
+       
+       char    *itemType, *itemStart;
+        int    count, i;
+       regmatch_t      matches[4];
+       
        // Ask server for stock list
+       send(Socket, "ENUM_ITEMS\n", 11, 0);
+       len = recv(Socket, buffer, BUFSIZ-1, 0);
+       buffer[len] = '\0';
+       
+       trim(buffer);
        
-       // Display the list for the user
-       // and choose what to dispense
+       //printf("Output: %s\n", buffer);
+       
+       responseCode = atoi(buffer);
+       if( responseCode != 201 ) {
+               fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
+               exit(-1);
+       }
+       
+       // - Get item list -
+       
+       // Expected format: 201 Items <count> <item1> <item2> ...
+       RunRegex(&gArrayRegex, buffer, 4, matches, "Malformed server response");
+               
+       itemType = &buffer[ matches[2].rm_so ]; buffer[ matches[2].rm_eo ] = '\0';
+       count = atoi( &buffer[ matches[3].rm_so ] );
+               
+       // Check array type
+       if( strcmp(itemType, "Items") != 0 ) {
+               // What the?!
+               fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
+                       itemType);
+               exit(-1);
+       }
+               
+       itemStart = &buffer[ matches[3].rm_eo ];
+               
+       gaItems = malloc( count * sizeof(tItem) );
+               
+       for( giNumItems = 0; giNumItems < count && itemStart; giNumItems ++ )
+       {
+               char    *next = strchr( ++itemStart, ' ' );
+               if( next )      *next = '\0';
+               gaItems[giNumItems].Ident = strdup(itemStart);
+               itemStart = next;
+       }
+       
+       // Fetch item information
+       for( i = 0; i < giNumItems; i ++ )
+       {
+               regmatch_t      matches[6];
+               
+               // Get item info
+               sendf(Socket, "ITEM_INFO %s\n", gaItems[i].Ident);
+               len = recv(Socket, buffer, BUFSIZ-1, 0);
+               buffer[len] = '\0';
+               trim(buffer);
+               
+               responseCode = atoi(buffer);
+               if( responseCode != 202 ) {
+                       fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
+                       exit(-1);
+               }
+               
+               RunRegex(&gItemRegex, buffer, 6, matches, "Malformed server response");
+               
+               buffer[ matches[3].rm_eo ] = '\0';
+               
+               gaItems[i].Price = atoi( buffer + matches[4].rm_so );
+               gaItems[i].Desc = strdup( buffer + matches[5].rm_so );
+       }
+}
 
-       return 0;
+int DispenseItem(int Socket, int ItemID)
+{
+        int    len, responseCode;
+       char    buffer[BUFSIZ];
+       
+       if( ItemID < 0 || ItemID > giNumItems ) return -1;
+       
+       // Dispense!
+       sendf(Socket, "DISPENSE %s\n", gaItems[ItemID].Ident);
+       len = recv(Socket, buffer, BUFSIZ-1, 0);
+       buffer[len] = '\0';
+       trim(buffer);
+       
+       responseCode = atoi(buffer);
+       switch( responseCode )
+       {
+       case 200:
+               printf("Dispense OK\n");
+               return 0;
+       case 401:
+               printf("Not authenticated\n");
+               return 1;
+       case 402:
+               printf("Insufficient balance\n");
+               return 1;
+       case 406:
+               printf("Bad item name, bug report\n");
+               return 1;
+       case 500:
+               printf("Item failed to dispense, is the slot empty?\n");
+               return 1;
+       case 501:
+               printf("Dispense not possible (slot empty/permissions)\n");
+               return 1;
+       default:
+               printf("Unknown response code %i ('%s')\n", responseCode, buffer);
+               return -2;
+       }
+}
+
+char *trim(char *string)
+{
+        int    i;
+       
+       while( isspace(*string) )
+               string ++;
+       
+       for( i = strlen(string); i--; )
+       {
+               if( isspace(string[i]) )
+                       string[i] = '\0';
+               else
+                       break;
+       }
+       
+       return string;
+}
+
+int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
+{
+        int    ret;
+       
+       ret = regexec(regex, string, nMatches, matches, 0);
+       if( ret ) {
+               size_t  len = regerror(ret, regex, NULL, 0);
+               char    errorStr[len];
+               regerror(ret, regex, errorStr, len);
+               printf("string = '%s'\n", string);
+               fprintf(stderr, "%s\n%s", errorMessage, errorStr);
+               exit(-1);
+       }
+       
+       return ret;
+}
+
+void CompileRegex(regex_t *regex, const char *pattern, int flags)
+{
+        int    ret = regcomp(regex, pattern, flags);
+       if( ret ) {
+               size_t  len = regerror(ret, regex, NULL, 0);
+               char    errorStr[len];
+               regerror(ret, regex, errorStr, len);
+               fprintf(stderr, "Regex compilation failed - %s\n", errorStr);
+               exit(-1);
+       }
 }

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