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

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