3 * UCC (University [of WA] Computer Club) Electronic Accounting System
6 * main.c - Core and Initialisation
8 * This file is licenced under the 3-clause BSD Licence. See the file
9 * COPYING for full details.
14 #include <ctype.h> // isspace
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
28 #define USE_NCURSES_INTERFACE 0
29 #define DEBUG_TRACE_SERVER 0
32 typedef struct sItem {
40 int main(int argc, char *argv[]);
43 int ShowNCursesUI(void);
44 void ShowItemAt(int Row, int Col, int Width, int Index);
45 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
46 // --- Coke Server Communication ---
47 int OpenConnection(const char *Host, int Port);
48 int Authenticate(int Socket);
49 void PopulateItemList(int Socket);
50 int DispenseItem(int Socket, int ItemID);
51 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
52 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
53 int Dispense_Donate(int Socket, int Ammount, const char *Reason);
54 int Dispense_EnumUsers(int Socket);
55 int Dispense_ShowUser(int Socket, const char *Username);
56 void _PrintUserLine(const char *Line);
57 int Dispense_AddUser(int Socket, const char *Username);
58 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
60 char *ReadLine(int Socket);
61 int sendf(int Socket, const char *Format, ...);
62 char *trim(char *string);
63 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
64 void CompileRegex(regex_t *regex, const char *pattern, int flags);
67 char *gsDispenseServer = "localhost";
68 int giDispensePort = 11020;
72 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex;
73 int gbIsAuthenticated = 0;
75 char *gsItemPattern; //!< Item pattern
76 char *gsEffectiveUser; //!< '-u' Dispense as another user
77 int gbUseNCurses = 0; //!< '-G' Use the NCurses GUI?
78 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
79 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
82 int main(int argc, char *argv[])
88 // -- Create regular expressions
89 // > Code Type Count ...
90 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
91 // > Code Type Ident Price Desc
92 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z]+):([0-9]+)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
94 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
95 // > Code 'User' Username Balance Flags
96 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
99 for( i = 1; i < argc; i ++ )
112 case 'm': // Minimum balance
113 giMinimumBalance = atoi(argv[++i]);
115 case 'M': // Maximum balance
116 giMaximumBalance = atoi(argv[++i]);
119 case 'u': // Override User
120 gsEffectiveUser = argv[++i];
131 if( strcmp(arg, "acct") == 0 )
134 sock = OpenConnection(gsDispenseServer, giDispensePort);
135 if( sock < 0 ) return -1;
138 if( i + 1 == argc ) {
139 Dispense_EnumUsers(sock);
143 // argv[i+1]: Username
148 if( i + 3 >= argc ) {
149 fprintf(stderr, "Error: `dispense acct' needs a reason\n");
153 // Authentication required
154 if( Authenticate(sock) )
157 // argv[i+1]: Username
158 // argv[i+2]: Ammount
162 Dispense_AlterBalance(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
165 // Show user information
166 Dispense_ShowUser(sock, argv[i+1]);
173 // - "Here, have some money."
174 if( strcmp(arg, "give") == 0 )
176 if( i + 3 >= argc ) {
177 fprintf(stderr, "`dispense give` takes three arguments\n");
181 // TODO: `dispense give`
183 // argv[i+1]: Destination
184 // argv[i+2]: Ammount
188 sock = OpenConnection(gsDispenseServer, giDispensePort);
189 if( sock < 0 ) return -1;
192 if( Authenticate(sock) )
195 Dispense_Give(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
200 // - User administration (Wheel Only)
201 if( strcmp(arg, "user") == 0 )
203 // Check argument count
204 if( i + 1 >= argc ) {
205 fprintf(stderr, "Error: `dispense user` requires arguments\n");
211 sock = OpenConnection(gsDispenseServer, giDispensePort);
212 if( sock < 0 ) return -1;
214 // Attempt authentication
215 if( Authenticate(sock) )
219 if( strcmp(argv[i+1], "add") == 0 )
221 if( i + 2 >= argc ) {
222 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
227 Dispense_AddUser(sock, argv[i+2]);
230 else if( strcmp(argv[i+1], "type") == 0 )
232 if( i + 3 >= argc ) {
233 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
238 Dispense_SetUserType(sock, argv[i+2], argv[i+3]);
242 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
250 if( strcmp(arg, "donate") == 0 )
252 // Check argument count
253 if( i + 2 >= argc ) {
254 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
260 sock = OpenConnection(gsDispenseServer, giDispensePort);
261 if( sock < 0 ) return -1;
263 // Attempt authentication
264 if( Authenticate(sock) )
268 Dispense_Donate(sock, atoi(argv[i+1]), argv[i+1]);
274 // Item name / pattern
281 sock = OpenConnection(gsDispenseServer, giDispensePort);
282 if( sock < 0 ) return -1;
288 PopulateItemList(sock);
292 // TODO: Implement `dispense <name>`
293 printf("TODO: Implement `dispense <name>`\n");
296 else if( gbUseNCurses )
302 for( i = 0; i < giNumItems; i ++ ) {
303 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
304 gaItems[i].Price, gaItems[i].Desc);
313 fgets(buffer, BUFSIZ, stdin);
317 if( buf[0] == 'q' ) break;
321 if( i != 0 || buf[0] == '0' )
323 if( i < 0 || i >= giNumItems ) {
324 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
332 // Check for a valid item ID
334 DispenseItem(sock, i);
346 " Show interactive list\n"
348 " Dispense named item\n"
349 " dispense give <user> <ammount> \"<reason>\"\n"
350 " Give money to another user\n"
351 " dispense donate <ammount> \"<reason>\"\n"
352 " Donate to the club\n"
353 " dispense acct [<user>]\n"
354 " Show user balances\n"
355 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
356 " Alter a account value (Coke members only)\n"
357 " dispense user add <user>\n"
358 " Create new coke account (Admins only)\n"
359 " dispense user type <user> <flags>\n"
360 " Alter a user's flags\n"
361 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
362 " Flags are removed by preceding the name with '-' or '!'\n"
366 " Set a different user (Coke members only)\n"
370 " Use alternate GUI\n"
371 " -m <min balance>\n"
372 " -M <max balance>\n"
373 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
377 // -------------------
378 // --- NCurses GUI ---
379 // -------------------
381 * \brief Render the NCurses UI
383 int ShowNCursesUI(void)
385 // TODO: ncurses interface (with separation between item classes)
386 // - Hmm... that would require standardising the item ID to be <class>:<index>
391 const int displayMinWidth = 40;
392 const int displayMinItems = 8;
393 char *titleString = "Dispense";
394 int itemCount = displayMinItems;
397 int ret = -2; // -2: Used for marking "no return yet"
406 // - 6: randomly chosen (Need at least 3)
407 itemCount = LINES - 6;
408 if( itemCount > giNumItems )
409 itemCount = giNumItems;
412 height = itemCount + 3;
413 width = displayMinWidth;
416 xBase = COLS/2 - width/2;
417 yBase = LINES/2 - height/2;
422 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
425 for( i = 0; i < itemCount; i ++ )
427 move( yBase + 1 + i, xBase );
429 if( currentItem == itemBase + i ) {
437 // - Oh god, magic numbers!
438 if( i == 0 && itemBase > 0 ) {
440 times = width-1 - 8 - 3;
441 while(times--) addch(' ');
443 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
445 times = width-1 - 8 - 3;
446 while(times--) addch(' ');
450 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
454 // Scrollbar (if needed)
455 if( giNumItems > itemCount ) {
459 else if( i == itemCount - 1 ) {
463 int percentage = itemBase * 100 / (giNumItems-itemCount);
464 if( i-1 == percentage*(itemCount-3)/100 ) {
478 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
491 //if( itemBase < giNumItems - (itemCount) )
493 if( currentItem < giNumItems - 1 )
495 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
501 if( currentItem > 0 )
503 if( itemBase + 1 > currentItem && itemBase > 0 )
519 ret = -1; // -1: Return with no dispense
523 // Check if the return value was changed
524 if( ret != -2 ) break;
536 * \brief Show item \a Index at (\a Col, \a Row)
537 * \note Part of the NCurses UI
539 void ShowItemAt(int Row, int Col, int Width, int Index)
547 if( Index < 0 || Index >= giNumItems ) {
552 name = gaItems[Index].Desc;
553 price = gaItems[Index].Price;
556 printw("%02i %s", Index, name);
558 getyx(stdscr, _y, _x);
559 // Assumes max 4 digit prices
560 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
561 while(times--) addch(' ');
562 printw("%4i", price);
566 * \brief Print a three-part string at the specified position (formatted)
567 * \note NCurses UI Helper
569 * Prints \a Left on the left of the area, \a Right on the righthand side
570 * and \a Mid in the middle of the area. These are padded with \a Pad1
571 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
573 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
574 * and the arguments to these are read in that order.
576 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
577 const char *Mid, char Pad2, const char *Right, ...)
579 int lLen, mLen, rLen;
584 // Get the length of the strings
585 va_start(args, Right);
586 lLen = vsnprintf(NULL, 0, Left, args);
587 mLen = vsnprintf(NULL, 0, Mid, args);
588 rLen = vsnprintf(NULL, 0, Right, args);
592 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
593 return ; // TODO: What to do?
599 va_start(args, Right);
603 vsnprintf(tmp, lLen+1, Left, args);
607 times = Width/2 - mLen/2 - lLen;
608 while(times--) addch(Pad1);
612 vsnprintf(tmp, mLen+1, Mid, args);
616 times = Width/2 - mLen/2 - rLen;
617 while(times--) addch(Pad2);
621 vsnprintf(tmp, rLen+1, Right, args);
626 // ---------------------
627 // --- Coke Protocol ---
628 // ---------------------
629 int OpenConnection(const char *Host, int Port)
631 struct hostent *host;
632 struct sockaddr_in serverAddr;
635 host = gethostbyname(Host);
637 fprintf(stderr, "Unable to look up '%s'\n", Host);
641 memset(&serverAddr, 0, sizeof(serverAddr));
643 serverAddr.sin_family = AF_INET; // IPv4
644 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
645 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
646 serverAddr.sin_port = htons(Port);
648 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
650 fprintf(stderr, "Failed to create socket\n");
656 struct sockaddr_in localAddr;
657 memset(&localAddr, 0, sizeof(localAddr));
658 localAddr.sin_family = AF_INET; // IPv4
659 localAddr.sin_port = 1023; // IPv4
660 // Attempt to bind to low port for autoauth
661 bind(sock, &localAddr, sizeof(localAddr));
665 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
666 fprintf(stderr, "Failed to connect to server\n");
674 * \brief Authenticate with the server
675 * \return Boolean Failure
677 int Authenticate(int Socket)
684 regmatch_t matches[4];
686 if( gbIsAuthenticated ) return 0;
689 pwd = getpwuid( getuid() );
691 // Attempt automatic authentication
692 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
694 // Check if it worked
695 buf = ReadLine(Socket);
697 responseCode = atoi(buf);
698 switch( responseCode )
700 case 200: // Autoauth succeeded, return
704 case 401: // Untrusted, attempt password authentication
707 sendf(Socket, "USER %s\n", pwd->pw_name);
708 printf("Using username %s\n", pwd->pw_name);
710 buf = ReadLine(Socket);
713 // Expected format: 100 SALT <something> ...
715 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
716 responseCode = atoi(buf);
717 if( responseCode != 100 ) {
718 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
724 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
725 // Store it for later
726 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
727 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
731 // Give three attempts
732 for( i = 0; i < 3; i ++ )
734 int ofs = strlen(pwd->pw_name)+strlen(salt);
737 char *pass = getpass("Password: ");
740 // Create hash string
741 // <username><salt><hash>
742 strcpy(tmp, pwd->pw_name);
744 SHA1( (unsigned char*)pass, strlen(pass), h );
745 memcpy(tmp+ofs, h, 20);
748 SHA1( (unsigned char*)tmp, ofs+20, h );
749 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
750 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
751 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
755 sendf(Socket, "PASS %s\n", tmpBuf);
756 buf = ReadLine(Socket);
758 responseCode = atoi(buf);
760 if( responseCode == 200 ) break;
761 // Bad username/password
762 if( responseCode == 401 ) continue;
764 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
770 return 2; // 2 = Bad Password
773 case 404: // Bad Username
774 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
779 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
785 // Set effective user
786 if( gsEffectiveUser ) {
787 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
789 buf = ReadLine(Socket);
790 responseCode = atoi(buf);
795 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
799 printf("Only coke members can use `dispense -u`\n");
804 printf("Invalid user selected\n");
809 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
818 gbIsAuthenticated = 1;
825 * \brief Fill the item information structure
826 * \return Boolean Failure
828 void PopulateItemList(int Socket)
833 char *itemType, *itemStart;
835 regmatch_t matches[4];
837 // Ask server for stock list
838 send(Socket, "ENUM_ITEMS\n", 11, 0);
839 buf = ReadLine(Socket);
841 //printf("Output: %s\n", buf);
843 responseCode = atoi(buf);
844 if( responseCode != 201 ) {
845 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
854 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
856 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
857 count = atoi( &buf[ matches[3].rm_so ] );
860 if( strcmp(itemType, "Items") != 0 ) {
862 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
867 itemStart = &buf[ matches[3].rm_eo ];
872 gaItems = malloc( giNumItems * sizeof(tItem) );
874 // Fetch item information
875 for( i = 0; i < giNumItems; i ++ )
877 regmatch_t matches[7];
880 buf = ReadLine(Socket);
881 responseCode = atoi(buf);
883 if( responseCode != 202 ) {
884 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
888 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
890 buf[ matches[3].rm_eo ] = '\0';
892 gaItems[i].Type = strdup( buf + matches[3].rm_so );
893 gaItems[i].ID = atoi( buf + matches[4].rm_so );
894 gaItems[i].Price = atoi( buf + matches[5].rm_so );
895 gaItems[i].Desc = strdup( buf + matches[6].rm_so );
901 buf = ReadLine(Socket);
902 responseCode = atoi(buf);
904 if( responseCode != 200 ) {
905 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
915 * \brief Dispense an item
916 * \return Boolean Failure
918 int DispenseItem(int Socket, int ItemID)
920 int ret, responseCode;
923 if( ItemID < 0 || ItemID > giNumItems ) return -1;
926 sendf(Socket, "DISPENSE %s:%i\n", gaItems[ItemID].Type, gaItems[ItemID].ID);
927 buf = ReadLine(Socket);
929 responseCode = atoi(buf);
930 switch( responseCode )
933 printf("Dispense OK\n");
937 printf("Not authenticated\n");
941 printf("Insufficient balance\n");
945 printf("Bad item name, bug report\n");
949 printf("Item failed to dispense, is the slot empty?\n");
953 printf("Dispense not possible (slot empty/permissions)\n");
957 printf("Unknown response code %i ('%s')\n", responseCode, buf);
967 * \brief Alter a user's balance
969 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
974 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
975 buf = ReadLine(Socket);
977 responseCode = atoi(buf);
982 case 200: return 0; // OK
984 fprintf(stderr, "Insufficient balance\n");
986 case 403: // Not in coke
987 fprintf(stderr, "You are not in coke (sucker)\n");
989 case 404: // Unknown user
990 fprintf(stderr, "Unknown user '%s'\n", Username);
993 fprintf(stderr, "Unknown response code %i\n", responseCode);
1001 * \brief Give money to another user
1003 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1009 printf("Sorry, you can only give, you can't take.\n");
1013 // Fast return on zero
1014 if( Ammount == 0 ) {
1015 printf("Are you actually going to give any?\n");
1019 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1020 buf = ReadLine(Socket);
1022 responseCode = atoi(buf);
1025 switch(responseCode)
1027 case 200: return 0; // OK
1030 fprintf(stderr, "Insufficient balance\n");
1033 case 404: // Unknown user
1034 fprintf(stderr, "Unknown user '%s'\n", Username);
1038 fprintf(stderr, "Unknown response code %i\n", responseCode);
1047 * \brief Donate money to the club
1049 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1055 printf("Sorry, you can only give, you can't take.\n");
1059 // Fast return on zero
1060 if( Ammount == 0 ) {
1061 printf("Are you actually going to give any?\n");
1065 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1066 buf = ReadLine(Socket);
1068 responseCode = atoi(buf);
1071 switch(responseCode)
1073 case 200: return 0; // OK
1076 fprintf(stderr, "Insufficient balance\n");
1080 fprintf(stderr, "Unknown response code %i\n", responseCode);
1088 * \brief Enumerate users
1090 int Dispense_EnumUsers(int Socket)
1095 regmatch_t matches[4];
1097 if( giMinimumBalance != INT_MIN ) {
1098 if( giMaximumBalance != INT_MAX ) {
1099 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1102 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1106 if( giMaximumBalance != INT_MAX ) {
1107 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1110 sendf(Socket, "ENUM_USERS\n");
1113 buf = ReadLine(Socket);
1114 responseCode = atoi(buf);
1116 switch(responseCode)
1118 case 201: break; // Ok, length follows
1121 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1126 // Get count (not actually used)
1127 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1128 nUsers = atoi( buf + matches[3].rm_so );
1129 printf("%i users returned\n", nUsers);
1134 // Read returned users
1136 buf = ReadLine(Socket);
1137 responseCode = atoi(buf);
1139 if( responseCode != 202 ) break;
1141 _PrintUserLine(buf);
1143 } while(responseCode == 202);
1145 // Check final response
1146 if( responseCode != 200 ) {
1147 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1157 int Dispense_ShowUser(int Socket, const char *Username)
1160 int responseCode, ret;
1162 sendf(Socket, "USER_INFO %s\n", Username);
1163 buf = ReadLine(Socket);
1165 responseCode = atoi(buf);
1167 switch(responseCode)
1170 _PrintUserLine(buf);
1175 printf("Unknown user '%s'\n", Username);
1180 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1190 void _PrintUserLine(const char *Line)
1192 regmatch_t matches[6];
1195 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1200 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1201 char username[usernameLen + 1];
1202 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1203 char flags[flagsLen + 1];
1205 memcpy(username, Line + matches[3].rm_so, usernameLen);
1206 username[usernameLen] = '\0';
1207 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1208 flags[flagsLen] = '\0';
1210 bal = atoi(Line + matches[4].rm_so);
1211 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1215 int Dispense_AddUser(int Socket, const char *Username)
1218 int responseCode, ret;
1220 sendf(Socket, "USER_ADD %s\n", Username);
1222 buf = ReadLine(Socket);
1223 responseCode = atoi(buf);
1225 switch(responseCode)
1228 printf("User '%s' added\n", Username);
1233 printf("Only wheel can add users\n");
1238 printf("User '%s' already exists\n", Username);
1243 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1253 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1256 int responseCode, ret;
1258 // TODO: Pre-validate the string
1260 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1262 buf = ReadLine(Socket);
1263 responseCode = atoi(buf);
1265 switch(responseCode)
1268 printf("User '%s' updated\n", Username);
1273 printf("Only wheel can modify users\n");
1278 printf("User '%s' does not exist\n", Username);
1283 printf("Flag string is invalid\n");
1288 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1301 char *ReadLine(int Socket)
1303 static char buf[BUFSIZ];
1304 static int bufPos = 0;
1305 static int bufValid = 0;
1307 char *newline = NULL;
1309 char *ret = malloc(10);
1311 #if DEBUG_TRACE_SERVER
1312 printf("ReadLine: ");
1324 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1325 buf[bufPos+len] = '\0';
1328 newline = strchr( buf+bufPos, '\n' );
1333 retLen += strlen(buf+bufPos);
1334 ret = realloc(ret, retLen + 1);
1335 strcat( ret, buf+bufPos );
1338 int newLen = newline - (buf+bufPos) + 1;
1339 bufValid = len - newLen;
1342 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1345 #if DEBUG_TRACE_SERVER
1346 printf("%i '%s'\n", retLen, ret);
1352 int sendf(int Socket, const char *Format, ...)
1357 va_start(args, Format);
1358 len = vsnprintf(NULL, 0, Format, args);
1363 va_start(args, Format);
1364 vsnprintf(buf, len+1, Format, args);
1367 #if DEBUG_TRACE_SERVER
1368 printf("sendf: %s", buf);
1371 return send(Socket, buf, len, 0);
1375 char *trim(char *string)
1379 while( isspace(*string) )
1382 for( i = strlen(string); i--; )
1384 if( isspace(string[i]) )
1393 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1397 ret = regexec(regex, string, nMatches, matches, 0);
1399 size_t len = regerror(ret, regex, NULL, 0);
1401 regerror(ret, regex, errorStr, len);
1402 printf("string = '%s'\n", string);
1403 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1410 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1412 int ret = regcomp(regex, pattern, flags);
1414 size_t len = regerror(ret, regex, NULL, 0);
1416 regerror(ret, regex, errorStr, len);
1417 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);