Kernel - Cleaning up messages
[tpg/acess2.git] / Usermode / Applications / CLIShell_src / main.c
1 /*\r
2  * AcessOS Shell Version 3\r
3  */\r
4 #define USE_READLINE    1\r
5 #include <acess/sys.h>\r
6 #include <stdlib.h>\r
7 #include <stdio.h>\r
8 #include <string.h>\r
9 #include "header.h"\r
10 \r
11 #if USE_READLINE\r
12 # include "readline.h"\r
13 #endif\r
14 \r
15 #define _stdin  0\r
16 #define _stdout 1\r
17 #define _stderr 2\r
18 \r
19 // ==== PROTOTYPES ====\r
20 char    *ReadCommandLine(int *Length);\r
21 void    Parse_Args(char *str, char **dest);\r
22 void    CallCommand(char **Args);\r
23 void    Command_Logout(int argc, char **argv);\r
24 void    Command_Clear(int argc, char **argv);\r
25 void    Command_Help(int argc, char **argv);\r
26 void    Command_Cd(int argc, char **argv);\r
27 void    Command_Dir(int argc, char **argv);\r
28 \r
29 // ==== CONSTANT GLOBALS ====\r
30 struct  {\r
31         char    *name;\r
32         void    (*fcn)(int argc, char **argv);\r
33 }       cBUILTINS[] = {\r
34         {"exit", Command_Logout},       {"logout", Command_Logout},\r
35         {"help", Command_Help}, {"clear", Command_Clear},\r
36         {"cd", Command_Cd}, {"dir", Command_Dir}\r
37 };\r
38 static char     *cDEFAULT_PATH[] = {"/Acess/Bin"};\r
39 #define BUILTIN_COUNT   (sizeof(cBUILTINS)/sizeof(cBUILTINS[0]))\r
40 \r
41 // ==== LOCAL VARIABLES ====\r
42  int    giNumPathDirs = 1;\r
43 char    **gasPathDirs = cDEFAULT_PATH;\r
44 char    **gasEnvironment;\r
45 char    gsCommandBuffer[1024];\r
46 char    *gsCurrentDirectory = NULL;\r
47 char    **gasCommandHistory;\r
48  int    giLastCommand = 0;\r
49  int    giCommandSpace = 0;\r
50 \r
51 // ==== CODE ====\r
52 int main(int argc, char *argv[], char *envp[])\r
53 {\r
54         char    *sCommandStr;\r
55         char    *saArgs[32] = {0};\r
56          int    length = 0;\r
57          int    i;\r
58          int    iArgCount = 0;\r
59         #if !USE_READLINE\r
60          int    bCached = 1;\r
61         #else\r
62         tReadline       *readline_state = Readline_Init(1);\r
63         #endif\r
64         \r
65         gasEnvironment = envp;\r
66         \r
67         Command_Clear(0, NULL);\r
68         \r
69         {\r
70                 char    *tmp = getenv("CWD");\r
71                 if(tmp) {\r
72                         gsCurrentDirectory = malloc(strlen(tmp)+1);\r
73                         strcpy(gsCurrentDirectory, tmp);\r
74                 } else {\r
75                         gsCurrentDirectory = malloc(2);\r
76                         strcpy(gsCurrentDirectory, "/");\r
77                 }\r
78         }       \r
79         \r
80         write(_stdout, 22, "Acess Shell Version 3\n");\r
81         write(_stdout,  2, "\n");\r
82         for(;;)\r
83         {\r
84                 // Free last command & arguments\r
85                 if(saArgs[0])   free(saArgs);\r
86                 #if !USE_READLINE\r
87                 if(!bCached)    free(sCommandStr);\r
88                 bCached = 0;\r
89                 #endif\r
90                 \r
91                 write(_stdout, strlen(gsCurrentDirectory), gsCurrentDirectory);\r
92                 write(_stdout, 2, "$ ");\r
93                 \r
94                 // Read Command line\r
95                 #if USE_READLINE\r
96                 sCommandStr = Readline( readline_state );\r
97                 printf("\n");\r
98                 length = strlen(sCommandStr);\r
99                 #else\r
100                 sCommandStr = ReadCommandLine( &length );\r
101                 \r
102                 if(!sCommandStr) {\r
103                         write(_stdout, 25, "PANIC: Out of heap space\n");\r
104                         return -1;\r
105                 }\r
106                 \r
107                 // Check if the command should be cached\r
108                 if(gasCommandHistory == NULL || strcmp(sCommandStr, gasCommandHistory[giLastCommand]) != 0)\r
109                 {\r
110                         if(giLastCommand >= giCommandSpace) {\r
111                                 giCommandSpace += 12;\r
112                                 gasCommandHistory = realloc(gasCommandHistory, giCommandSpace*sizeof(char*));\r
113                         }\r
114                         giLastCommand ++;\r
115                         gasCommandHistory[ giLastCommand ] = sCommandStr;\r
116                         bCached = 1;\r
117                 }\r
118                 #endif\r
119                 \r
120                 // Parse Command Line into arguments\r
121                 Parse_Args(sCommandStr, saArgs);\r
122                 \r
123                 // Count Arguments\r
124                 iArgCount = 0;\r
125                 while(saArgs[iArgCount])        iArgCount++;\r
126                 \r
127                 // Silently Ignore all empty commands\r
128                 if(saArgs[1][0] == '\0')        continue;\r
129                 \r
130                 // Check Built-In Commands\r
131                 for( i = 0; i < BUILTIN_COUNT; i++ )\r
132                 {\r
133                         if( strcmp(saArgs[1], cBUILTINS[i].name) == 0 )\r
134                         {\r
135                                 cBUILTINS[i].fcn(iArgCount-1, &saArgs[1]);\r
136                                 break;\r
137                         }\r
138                 }\r
139                 if(i != BUILTIN_COUNT)  continue;\r
140                 \r
141                 // Shall we?\r
142                 CallCommand( &saArgs[1] );\r
143                 \r
144                 #if USE_READLINE\r
145                 free( sCommandStr );\r
146                 #endif\r
147         }\r
148 }\r
149 \r
150 /**\r
151  * \fn char *ReadCommandLine(int *Length)\r
152  * \brief Read from the command line\r
153  */\r
154 char *ReadCommandLine(int *Length)\r
155 {\r
156         char    *ret;\r
157          int    len, pos, space = 1023;\r
158         char    ch;\r
159         #if 0\r
160          int    scrollbackPos = giLastCommand;\r
161         #endif\r
162          \r
163         // Preset Variables\r
164         ret = malloc( space+1 );\r
165         if(!ret)        return NULL;\r
166         len = 0;        pos = 0;\r
167                 \r
168         // Read In Command Line\r
169         do {\r
170                 read(_stdin, 1, &ch);   // Read Character from stdin (read is a blocking call)\r
171                 \r
172                 if(ch == '\n')  break;\r
173                 \r
174                 switch(ch)\r
175                 {\r
176                 // Control characters\r
177                 case '\x1B':\r
178                         read(_stdin, 1, &ch);   // Read control character\r
179                         switch(ch)\r
180                         {\r
181                         //case 'D':     if(pos) pos--;  break;\r
182                         //case 'C':     if(pos<len)     pos++;  break;\r
183                         case '[':\r
184                                 read(_stdin, 1, &ch);   // Read control character\r
185                                 switch(ch)\r
186                                 {\r
187                                 #if 0\r
188                                 case 'A':       // Up\r
189                                         {\r
190                                                  int    oldLen = len;\r
191                                                 if( scrollbackPos > 0 ) break;\r
192                                                 \r
193                                                 free(ret);\r
194                                                 ret = strdup( gasCommandHistory[--scrollbackPos] );\r
195                                                 \r
196                                                 len = strlen(ret);\r
197                                                 while(pos--)    write(_stdout, 3, "\x1B[D");\r
198                                                 write(_stdout, len, ret);       pos = len;\r
199                                                 while(pos++ < oldLen)   write(_stdout, 1, " ");\r
200                                         }\r
201                                         break;\r
202                                 case 'B':       // Down\r
203                                         {\r
204                                                  int    oldLen = len;\r
205                                                 if( scrollbackPos < giLastCommand-1 )   break;\r
206                                                 \r
207                                                 free(ret);\r
208                                                 ret = strdup( gasCommandHistory[++scrollbackPos] );\r
209                                                 \r
210                                                 len = strlen(ret);\r
211                                                 while(pos--)    write(_stdout, 3, "\x1B[D");\r
212                                                 write(_stdout, len, ret);       pos = len;\r
213                                                 while(pos++ < oldLen)   write(_stdout, 1, " ");\r
214                                         }\r
215                                         break;\r
216                                 #endif\r
217                                 case 'D':       // Left\r
218                                         if(pos == 0)    break;\r
219                                         pos --;\r
220                                         write(_stdout, 3, "\x1B[D");\r
221                                         break;\r
222                                 case 'C':       // Right\r
223                                         if(pos == len)  break;\r
224                                         pos++;\r
225                                         write(_stdout, 3, "\x1B[C");\r
226                                         break;\r
227                                 }\r
228                         }\r
229                         break;\r
230                 \r
231                 // Backspace\r
232                 case '\b':\r
233                         if(len <= 0)            break;  // Protect against underflows\r
234                         write(_stdout, 1, &ch);\r
235                         if(pos == len) {        // Simple case of end of string\r
236                                 len --;\r
237                                 pos--;\r
238                         }\r
239                         else {\r
240                                 char    buf[7] = "\x1B[000D";\r
241                                 buf[2] += ((len-pos+1)/100) % 10;\r
242                                 buf[3] += ((len-pos+1)/10) % 10;\r
243                                 buf[4] += (len-pos+1) % 10;\r
244                                 write(_stdout, len-pos, &ret[pos]);     // Move Text\r
245                                 ch = ' ';       write(_stdout, 1, &ch); ch = '\b';      // Clear deleted character\r
246                                 write(_stdout, 7, buf); // Update Cursor\r
247                                 // Alter Buffer\r
248                                 memmove(&ret[pos-1], &ret[pos], len-pos);\r
249                                 pos --;\r
250                                 len --;\r
251                         }\r
252                         break;\r
253                 \r
254                 // Tab\r
255                 case '\t':\r
256                         //TODO: Implement Tab-Completion\r
257                         //Currently just ignore tabs\r
258                         break;\r
259                 \r
260                 default:                \r
261                         // Expand Buffer\r
262                         if(len+1 > space) {\r
263                                 space += 256;\r
264                                 ret = realloc(ret, space+1);\r
265                                 if(!ret)        return NULL;\r
266                         }\r
267                         \r
268                         // Editing inside the buffer\r
269                         if(pos != len) {\r
270                                 char    buf[7] = "\x1B[000D";\r
271                                 buf[2] += ((len-pos)/100) % 10;\r
272                                 buf[3] += ((len-pos)/10) % 10;\r
273                                 buf[4] += (len-pos) % 10;\r
274                                 write(_stdout, 1, &ch); // Print new character\r
275                                 write(_stdout, len-pos, &ret[pos]);     // Move Text\r
276                                 write(_stdout, 7, buf); // Update Cursor\r
277                                 memmove( &ret[pos+1], &ret[pos], len-pos );\r
278                         }\r
279                         else {\r
280                                 write(_stdout, 1, &ch);\r
281                         }\r
282                         ret[pos++] = ch;\r
283                         len ++;\r
284                         break;\r
285                 }\r
286         } while(ch != '\n');\r
287         \r
288         // Cap String\r
289         ret[len] = '\0';\r
290         printf("\n");\r
291         \r
292         // Return length\r
293         if(Length)      *Length = len;\r
294         \r
295         return ret;\r
296 }\r
297 \r
298 /**\r
299  * \fn void Parse_Args(char *str, char **dest)\r
300  * \brief Parse a string into an argument array\r
301  */\r
302 void Parse_Args(char *str, char **dest)\r
303 {\r
304          int    i = 1;\r
305         char    *buf = malloc( strlen(str) + 1 );\r
306         \r
307         if(buf == NULL) {\r
308                 dest[0] = NULL;\r
309                 Print("Parse_Args: Out of heap space!\n");\r
310                 return ;\r
311         }\r
312         \r
313         strcpy(buf, str);\r
314         dest[0] = buf;\r
315         \r
316         // Trim leading whitespace\r
317         while(*buf == ' ' && *buf)      buf++;\r
318         \r
319         for(;;)\r
320         {\r
321                 dest[i] = buf;  // Save start of string\r
322                 i++;\r
323                 while(*buf && *buf != ' ')\r
324                 {\r
325                         if(*buf++ == '"')\r
326                         {\r
327                                 while(*buf && !(*buf == '"' && buf[-1] != '\\'))\r
328                                         buf++;\r
329                         }\r
330                 }\r
331                 if(*buf == '\0')        break;\r
332                 *buf = '\0';\r
333                 while(*++buf == ' ' && *buf);\r
334                 if(*buf == '\0')        break;\r
335         }\r
336         dest[i] = NULL;\r
337         if(i == 1) {\r
338                 free(buf);\r
339                 dest[0] = NULL;\r
340         }\r
341 }\r
342 \r
343 /**\r
344  * \fn void CallCommand(char **Args)\r
345  */\r
346 void CallCommand(char **Args)\r
347 {\r
348         t_sysFInfo      info;\r
349          int    pid = -1;\r
350          int    fd = 0;\r
351         char    sTmpBuffer[1024];\r
352         char    *exefile = Args[0];\r
353         \r
354         if(exefile[0] == '/'\r
355         || (exefile[0] == '.' && exefile[1] == '/')\r
356         || (exefile[0] == '.' && exefile[1] == '.' && exefile[2] == '/')\r
357                 )\r
358         {\r
359                 GeneratePath(exefile, gsCurrentDirectory, sTmpBuffer);\r
360                 // Check file existence\r
361                 fd = open(sTmpBuffer, OPENFLAG_EXEC);\r
362                 if(fd == -1) {\r
363                         Print("Unknown Command: `");Print(Args[0]);Print("'\n");        // Error Message\r
364                         return ;\r
365                 }\r
366                 \r
367                 // Get File info and close file\r
368                 finfo( fd, &info, 0 );\r
369                 close( fd );\r
370                 \r
371                 // Check if the file is a directory\r
372                 if(info.flags & FILEFLAG_DIRECTORY) {\r
373                         Print("`");Print(sTmpBuffer);   // Error Message\r
374                         Print("' is a directory.\n");\r
375                         return ;\r
376                 }\r
377         }\r
378         else\r
379         {\r
380                  int    i;\r
381                 \r
382                 // Check all components of $PATH\r
383                 for( i = 0; i < giNumPathDirs; i++ )\r
384                 {\r
385                         GeneratePath(exefile, gasPathDirs[i], sTmpBuffer);\r
386                         fd = open(sTmpBuffer, OPENFLAG_EXEC);\r
387                         if(fd == -1)    continue;\r
388                         finfo( fd, &info, 0 );\r
389                         close( fd );\r
390                         if(info.flags & FILEFLAG_DIRECTORY)     continue;\r
391                         // Woohoo! We found a valid command\r
392                         break;\r
393                 }\r
394                 \r
395                 // Exhausted path directories\r
396                 if( i == giNumPathDirs ) {\r
397                         Print("Unknown Command: `");Print(exefile);Print("'\n");\r
398                         return ;\r
399                 }\r
400         }\r
401         \r
402         // Create new process\r
403         pid = clone(CLONE_VM, 0);\r
404         // Start Task\r
405         if(pid == 0)\r
406                 execve(sTmpBuffer, Args, gasEnvironment);\r
407         if(pid <= 0) {\r
408                 Print("Unablt to create process: `");Print(sTmpBuffer);Print("'\n");    // Error Message\r
409         }\r
410         else {\r
411                  int    status;\r
412                 waittid(pid, &status);\r
413         }\r
414 }\r
415 \r
416 /**\r
417  * \fn void Command_Logout(int argc, char **argv)\r
418  * \brief Exit the shell, logging the user out\r
419  */\r
420 void Command_Logout(int argc, char **argv)\r
421 {\r
422         exit(0);\r
423 }\r
424 \r
425 /**\r
426  * \fn void Command_Colour(int argc, char **argv)\r
427  * \brief Displays the help screen\r
428  */\r
429 void Command_Help(int argc, char **argv)\r
430 {\r
431         Print("Acess 2 Command Line Interface\n");\r
432         Print(" By John Hodge (thePowersGang / [TPG])\n");\r
433         Print("\n");\r
434         Print("Builtin Commands:\n");\r
435         Print(" logout: Return to the login prompt\n");\r
436         Print(" exit:   Same\n");\r
437         Print(" help:   Display this message\n");\r
438         Print(" clear:  Clear the screen\n");\r
439         Print(" cd:     Change the current directory\n");\r
440         Print(" dir:    Print the contents of the current directory\n");\r
441         //Print("\n");\r
442         return;\r
443 }\r
444 \r
445 /**\r
446  * \fn void Command_Clear(int argc, char **argv)\r
447  * \brief Clear the screen\r
448  */\r
449 void Command_Clear(int argc, char **argv)\r
450 {\r
451         write(_stdout, 4, "\x1B[2J");   //Clear Screen\r
452 }\r
453 \r
454 /**\r
455  * \fn void Command_Cd(int argc, char **argv)\r
456  * \brief Change directory\r
457  */\r
458 void Command_Cd(int argc, char **argv)\r
459 {\r
460         char    tmpPath[1024];\r
461         int             fp;\r
462         t_sysFInfo      stats;\r
463         \r
464         if(argc < 2)\r
465         {\r
466                 Print(gsCurrentDirectory);Print("\n");\r
467                 return;\r
468         }\r
469         \r
470         GeneratePath(argv[1], gsCurrentDirectory, tmpPath);\r
471         \r
472         fp = open(tmpPath, 0);\r
473         if(fp == -1) {\r
474                 write(_stdout, 26, "Directory does not exist\n");\r
475                 return;\r
476         }\r
477         finfo(fp, &stats, 0);\r
478         close(fp);\r
479         \r
480         if( !(stats.flags & FILEFLAG_DIRECTORY) ) {\r
481                 write(_stdout, 17, "Not a Directory\n");\r
482                 return;\r
483         }\r
484         \r
485         free(gsCurrentDirectory);\r
486         gsCurrentDirectory = malloc(strlen(tmpPath)+1);\r
487         strcpy(gsCurrentDirectory, tmpPath);\r
488         \r
489         // Register change with kernel\r
490         chdir( gsCurrentDirectory );\r
491 }\r
492 \r
493 /**\r
494  * \fn void Command_Dir(int argc, char **argv)\r
495  * \brief Print the contents of a directory\r
496  */\r
497 void Command_Dir(int argc, char **argv)\r
498 {\r
499          int    dp, fp, dirLen;\r
500         char    modeStr[11] = "RWXrwxRWX ";\r
501         char    tmpPath[1024];\r
502         char    *fileName;\r
503         t_sysFInfo      info;\r
504         t_sysACL        acl;\r
505         \r
506         // Generate Directory Path\r
507         if(argc > 1)\r
508                 dirLen = GeneratePath(argv[1], gsCurrentDirectory, tmpPath);\r
509         else\r
510         {\r
511                 strcpy(tmpPath, gsCurrentDirectory);\r
512         }\r
513         dirLen = strlen(tmpPath);\r
514         \r
515         // Open Directory\r
516         dp = open(tmpPath, OPENFLAG_READ);\r
517         // Check if file opened\r
518         if(dp == -1)\r
519         {\r
520                 printf("Unable to open directory `%s', File cannot be found\n", tmpPath);\r
521                 return;\r
522         }\r
523         // Get File Stats\r
524         if( finfo(dp, &info, 0) == -1 )\r
525         {\r
526                 close(dp);\r
527                 write(_stdout, 34, "stat Failed, Bad File Descriptor\n");\r
528                 return;\r
529         }\r
530         // Check if it's a directory\r
531         if(!(info.flags & FILEFLAG_DIRECTORY))\r
532         {\r
533                 close(dp);\r
534                 write(_stdout, 27, "Unable to open directory `");\r
535                 write(_stdout, strlen(tmpPath)+1, tmpPath);\r
536                 write(_stdout, 20, "', Not a directory\n");\r
537                 return;\r
538         }\r
539         \r
540         // Append Shash for file paths\r
541         if(tmpPath[dirLen-1] != '/')\r
542         {\r
543                 tmpPath[dirLen++] = '/';\r
544                 tmpPath[dirLen] = '\0';\r
545         }\r
546         \r
547         fileName = (char*)(tmpPath+dirLen);\r
548         // Read Directory Content\r
549         while( (fp = readdir(dp, fileName)) )\r
550         {\r
551                 if(fp < 0)\r
552                 {\r
553                         if(fp == -3)\r
554                                 write(_stdout, 42, "Invalid Permissions to traverse directory\n");\r
555                         break;\r
556                 }\r
557                 // Open File\r
558                 fp = open(tmpPath, 0);\r
559                 if(fp == -1)    continue;\r
560                 // Get File Stats\r
561                 finfo(fp, &info, 0);\r
562                 \r
563                 if(info.flags & FILEFLAG_DIRECTORY)\r
564                         write(_stdout, 1, "d");\r
565                 else\r
566                         write(_stdout, 1, "-");\r
567                 \r
568                 // Print Mode\r
569                 // - Owner\r
570                 acl.group = 0;  acl.id = info.uid;\r
571                 _SysGetACL(fp, &acl);\r
572                 if(acl.perms & 1)       modeStr[0] = 'r';       else    modeStr[0] = '-';\r
573                 if(acl.perms & 2)       modeStr[1] = 'w';       else    modeStr[1] = '-';\r
574                 if(acl.perms & 8)       modeStr[2] = 'x';       else    modeStr[2] = '-';\r
575                 // - Group\r
576                 acl.group = 1;  acl.id = info.gid;\r
577                 _SysGetACL(fp, &acl);\r
578                 if(acl.perms & 1)       modeStr[3] = 'r';       else    modeStr[3] = '-';\r
579                 if(acl.perms & 2)       modeStr[4] = 'w';       else    modeStr[4] = '-';\r
580                 if(acl.perms & 8)       modeStr[5] = 'x';       else    modeStr[5] = '-';\r
581                 // - World\r
582                 acl.group = 1;  acl.id = -1;\r
583                 _SysGetACL(fp, &acl);\r
584                 if(acl.perms & 1)       modeStr[6] = 'r';       else    modeStr[6] = '-';\r
585                 if(acl.perms & 2)       modeStr[7] = 'w';       else    modeStr[7] = '-';\r
586                 if(acl.perms & 8)       modeStr[8] = 'x';       else    modeStr[8] = '-';\r
587                 write(_stdout, 10, modeStr);\r
588                 close(fp);\r
589                 \r
590                 // Colour Code\r
591                 if(info.flags & FILEFLAG_DIRECTORY)     // Directory: Green\r
592                         write(_stdout, 6, "\x1B[32m");\r
593                 // Default: White\r
594                 \r
595                 // Print Name\r
596                 write(_stdout, strlen(fileName), fileName);\r
597                 \r
598                 // Print slash if applicable\r
599                 if(info.flags & FILEFLAG_DIRECTORY)\r
600                         write(_stdout, 1, "/");\r
601                 \r
602                 // Revert Colour\r
603                 write(_stdout, 6, "\x1B[37m");\r
604                 \r
605                 // Newline!\r
606                 write(_stdout, 1, "\n");\r
607         }\r
608         // Close Directory\r
609         close(dp);\r
610 }\r

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