Usermode - Added stdio output caching
[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 #include <readline.h>\r
11 \r
12 #define _stdin  0\r
13 #define _stdout 1\r
14 #define _stderr 2\r
15 \r
16 // ==== PROTOTYPES ====\r
17  int    Parse_Args(const char *str, char **dest);\r
18 void    CallCommand(char **Args);\r
19 void    Command_Logout(int argc, char **argv);\r
20 void    Command_Clear(int argc, char **argv);\r
21 void    Command_Help(int argc, char **argv);\r
22 void    Command_Cd(int argc, char **argv);\r
23 void    Command_Dir(int argc, char **argv);\r
24 \r
25 // ==== CONSTANT GLOBALS ====\r
26 struct  {\r
27         char    *name;\r
28         void    (*fcn)(int argc, char **argv);\r
29 }       cBUILTINS[] = {\r
30         {"exit", Command_Logout},       {"logout", Command_Logout},\r
31         {"help", Command_Help}, {"clear", Command_Clear},\r
32         {"cd", Command_Cd}, {"dir", Command_Dir}\r
33 };\r
34 static char     *cDEFAULT_PATH[] = {"/Acess/Bin"};\r
35 #define BUILTIN_COUNT   (sizeof(cBUILTINS)/sizeof(cBUILTINS[0]))\r
36 \r
37 // ==== LOCAL VARIABLES ====\r
38  int    giNumPathDirs = 1;\r
39 char    **gasPathDirs = cDEFAULT_PATH;\r
40 char    **gasEnvironment;\r
41 char    gsCommandBuffer[1024];\r
42 char    *gsCurrentDirectory = NULL;\r
43 char    **gasCommandHistory;\r
44  int    giLastCommand = 0;\r
45  int    giCommandSpace = 0;\r
46 \r
47 // ==== CODE ====\r
48 int main(int argc, char *argv[], char **envp)\r
49 {\r
50         char    *sCommandStr;\r
51         char    *saArgs[32] = {0};\r
52          int    i;\r
53          int    iArgCount = 0;\r
54         tReadline       *readline_state = Readline_Init(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         printf("Acess Shell Version 3\n\n");\r
72         for(;;)\r
73         {\r
74                 // Free last command & arguments\r
75                 if(saArgs[0])   free(saArgs[0]);\r
76                 \r
77                 printf("%s$ ", gsCurrentDirectory);\r
78                 fflush(stdout);\r
79                 \r
80                 // Read Command line\r
81                 sCommandStr = Readline( readline_state );\r
82                 printf("\n");\r
83                 \r
84                 // Parse Command Line into arguments\r
85                 iArgCount = Parse_Args(sCommandStr, saArgs);\r
86                 \r
87                 // Silently Ignore all empty commands\r
88                 if(saArgs[1][0] == '\0')        continue;\r
89                 \r
90                 // Check Built-In Commands\r
91                 for( i = 0; i < BUILTIN_COUNT; i++ )\r
92                 {\r
93                         if( strcmp(saArgs[1], cBUILTINS[i].name) == 0 )\r
94                         {\r
95                                 cBUILTINS[i].fcn(iArgCount-1, &saArgs[1]);\r
96                                 break;\r
97                         }\r
98                 }\r
99                 if(i != BUILTIN_COUNT)  continue;\r
100                 \r
101                 // Shall we?\r
102                 CallCommand( &saArgs[1] );\r
103                 \r
104                 free( sCommandStr );\r
105         }\r
106 }\r
107 \r
108 /**\r
109  * \fn int Parse_Args(const char *str, char **dest)\r
110  * \brief Parse a string into an argument array\r
111  */\r
112 int Parse_Args(const char *str, char **dest)\r
113 {\r
114          int    i = 1;\r
115         char    *buf = malloc( strlen(str) + 1 );\r
116         \r
117         if(buf == NULL) {\r
118                 dest[0] = NULL;\r
119                 printf("Parse_Args: Out of heap space!\n");\r
120                 return 0;\r
121         }\r
122         \r
123         strcpy(buf, str);\r
124         dest[0] = buf;\r
125         \r
126         // Trim leading whitespace\r
127         while(*buf == ' ' && *buf)      buf++;\r
128         \r
129         for(;;)\r
130         {\r
131                 dest[i] = buf;  // Save start of string\r
132                 i++;\r
133                 while(*buf && *buf != ' ')\r
134                 {\r
135                         if(*buf++ == '"')\r
136                         {\r
137                                 while(*buf && !(*buf == '"' && buf[-1] != '\\'))\r
138                                         buf++;\r
139                         }\r
140                 }\r
141                 if(*buf == '\0')        break;\r
142                 *buf = '\0';\r
143                 while(*++buf == ' ' && *buf);\r
144                 if(*buf == '\0')        break;\r
145         }\r
146         dest[i] = NULL;\r
147         \r
148         return i;\r
149 }\r
150 \r
151 /**\r
152  * \fn void CallCommand(char **Args)\r
153  */\r
154 void CallCommand(char **Args)\r
155 {\r
156         t_sysFInfo      info;\r
157          int    pid = -1;\r
158          int    fd = 0;\r
159         char    sTmpBuffer[1024];\r
160         char    *exefile = Args[0];\r
161         \r
162         if(exefile[0] == '/'\r
163         || (exefile[0] == '.' && exefile[1] == '/')\r
164         || (exefile[0] == '.' && exefile[1] == '.' && exefile[2] == '/')\r
165                 )\r
166         {\r
167                 GeneratePath(exefile, gsCurrentDirectory, sTmpBuffer);\r
168                 // Check file existence\r
169                 fd = _SysOpen(sTmpBuffer, OPENFLAG_EXEC);\r
170                 if(fd == -1) {\r
171                         printf("Unknown Command: `%s'\n", Args[0]);     // Error Message\r
172                         return ;\r
173                 }\r
174                 \r
175                 // Get File info and close file\r
176                 _SysFInfo( fd, &info, 0 );\r
177                 _SysClose( fd );\r
178                 \r
179                 // Check if the file is a directory\r
180                 if(info.flags & FILEFLAG_DIRECTORY) {\r
181                         printf("`%s' is a directory.\n", sTmpBuffer);\r
182                         return ;\r
183                 }\r
184         }\r
185         else\r
186         {\r
187                  int    i;\r
188                 \r
189                 // Check all components of $PATH\r
190                 for( i = 0; i < giNumPathDirs; i++ )\r
191                 {\r
192                         GeneratePath(exefile, gasPathDirs[i], sTmpBuffer);\r
193                         fd = _SysOpen(sTmpBuffer, OPENFLAG_EXEC);\r
194                         if(fd == -1)    continue;\r
195                         _SysFInfo( fd, &info, 0 );\r
196                         _SysClose( fd );\r
197                         if(info.flags & FILEFLAG_DIRECTORY)     continue;\r
198                         // Woohoo! We found a valid command\r
199                         break;\r
200                 }\r
201                 \r
202                 // Exhausted path directories\r
203                 if( i == giNumPathDirs ) {\r
204                         printf("Unknown Command: `%s'\n", exefile);\r
205                         return ;\r
206                 }\r
207         }\r
208         \r
209         // Create new process\r
210         int fds[] = {0, 1, 2};\r
211         pid = _SysSpawn(sTmpBuffer, (const char **)Args, (const char **)gasEnvironment, 3, fds, NULL);\r
212         if(pid <= 0) {\r
213                 printf("Unable to create process: `%s'\n", sTmpBuffer); // Error Message\r
214         }\r
215         else {\r
216                  int    status;\r
217                 _SysWaitTID(pid, &status);\r
218         }\r
219 }\r
220 \r
221 /**\r
222  * \fn void Command_Logout(int argc, char **argv)\r
223  * \brief Exit the shell, logging the user out\r
224  */\r
225 void Command_Logout(int argc, char **argv)\r
226 {\r
227         exit(0);\r
228 }\r
229 \r
230 /**\r
231  * \fn void Command_Colour(int argc, char **argv)\r
232  * \brief Displays the help screen\r
233  */\r
234 void Command_Help(int argc, char **argv)\r
235 {\r
236         printf( "Acess 2 Command Line Interface\n"\r
237                 " By John Hodge (thePowersGang / [TPG])\n"\r
238                 "\n"\r
239                 "Builtin Commands:\n"\r
240                 " logout: Return to the login prompt\n"\r
241                 " exit:   Same\n"\r
242                 " help:   Display this message\n"\r
243                 " clear:  Clear the screen\n"\r
244                 " cd:     Change the current directory\n"\r
245                 " dir:    Print the contents of the current directory\n");\r
246         return;\r
247 }\r
248 \r
249 /**\r
250  * \fn void Command_Clear(int argc, char **argv)\r
251  * \brief Clear the screen\r
252  */\r
253 void Command_Clear(int argc, char **argv)\r
254 {\r
255         _SysWrite(_stdout, "\x1B[2J", 4);       //Clear Screen\r
256 }\r
257 \r
258 /**\r
259  * \fn void Command_Cd(int argc, char **argv)\r
260  * \brief Change directory\r
261  */\r
262 void Command_Cd(int argc, char **argv)\r
263 {\r
264         char    tmpPath[1024];\r
265         int             fp;\r
266         t_sysFInfo      stats;\r
267         \r
268         if(argc < 2)\r
269         {\r
270                 printf("%s\n", gsCurrentDirectory);\r
271                 return;\r
272         }\r
273         \r
274         GeneratePath(argv[1], gsCurrentDirectory, tmpPath);\r
275         \r
276         fp = _SysOpen(tmpPath, 0);\r
277         if(fp == -1) {\r
278                 printf("Directory does not exist\n");\r
279                 return;\r
280         }\r
281         _SysFInfo(fp, &stats, 0);\r
282         _SysClose(fp);\r
283         \r
284         if( !(stats.flags & FILEFLAG_DIRECTORY) ) {\r
285                 printf("Not a Directory\n");\r
286                 return;\r
287         }\r
288         \r
289         free(gsCurrentDirectory);\r
290         gsCurrentDirectory = malloc(strlen(tmpPath)+1);\r
291         strcpy(gsCurrentDirectory, tmpPath);\r
292         \r
293         // Register change with kernel\r
294         _SysChdir( gsCurrentDirectory );\r
295 }\r
296 \r
297 /**\r
298  * \fn void Command_Dir(int argc, char **argv)\r
299  * \brief Print the contents of a directory\r
300  */\r
301 void Command_Dir(int argc, char **argv)\r
302 {\r
303          int    dp, fp, dirLen;\r
304         char    modeStr[11] = "RWXrwxRWX ";\r
305         char    tmpPath[1024];\r
306         char    *fileName;\r
307         t_sysFInfo      info;\r
308         t_sysACL        acl;\r
309         \r
310         // Generate Directory Path\r
311         if(argc > 1)\r
312                 dirLen = GeneratePath(argv[1], gsCurrentDirectory, tmpPath);\r
313         else\r
314         {\r
315                 strcpy(tmpPath, gsCurrentDirectory);\r
316         }\r
317         dirLen = strlen(tmpPath);\r
318         \r
319         // Open Directory\r
320         dp = _SysOpen(tmpPath, OPENFLAG_READ);\r
321         // Check if file opened\r
322         if(dp == -1)\r
323         {\r
324                 printf("Unable to open directory `%s', File cannot be found\n", tmpPath);\r
325                 return;\r
326         }\r
327         // Get File Stats\r
328         if( _SysFInfo(dp, &info, 0) == -1 )\r
329         {\r
330                 _SysClose(dp);\r
331                 printf("stat Failed, Bad File Descriptor\n");\r
332                 return;\r
333         }\r
334         // Check if it's a directory\r
335         if(!(info.flags & FILEFLAG_DIRECTORY))\r
336         {\r
337                 _SysClose(dp);\r
338                 printf("Unable to open directory `%s', Not a directory\n", tmpPath);\r
339                 return;\r
340         }\r
341         \r
342         // Append Shash for file paths\r
343         if(tmpPath[dirLen-1] != '/')\r
344         {\r
345                 tmpPath[dirLen++] = '/';\r
346                 tmpPath[dirLen] = '\0';\r
347         }\r
348         \r
349         fileName = (char*)(tmpPath+dirLen);\r
350         // Read Directory Content\r
351         while( (fp = _SysReadDir(dp, fileName)) )\r
352         {\r
353                 if(fp < 0)\r
354                 {\r
355                         if(fp == -3)\r
356                                 printf("Invalid Permissions to traverse directory\n");\r
357                         break;\r
358                 }\r
359                 // Open File\r
360                 fp = _SysOpen(tmpPath, 0);\r
361                 if(fp == -1)    continue;\r
362                 // Get File Stats\r
363                 _SysFInfo(fp, &info, 0);\r
364                 \r
365                 if(info.flags & FILEFLAG_DIRECTORY)\r
366                         printf("d");\r
367                 else\r
368                         printf("-");\r
369                 \r
370                 // Print Mode\r
371                 // - Owner\r
372                 acl.object = info.uid;\r
373                 _SysGetACL(fp, &acl);\r
374                 if(acl.perms & 1)       modeStr[0] = 'r';       else    modeStr[0] = '-';\r
375                 if(acl.perms & 2)       modeStr[1] = 'w';       else    modeStr[1] = '-';\r
376                 if(acl.perms & 8)       modeStr[2] = 'x';       else    modeStr[2] = '-';\r
377                 // - Group\r
378                 acl.object = info.gid | 0x80000000;\r
379                 _SysGetACL(fp, &acl);\r
380                 if(acl.perms & 1)       modeStr[3] = 'r';       else    modeStr[3] = '-';\r
381                 if(acl.perms & 2)       modeStr[4] = 'w';       else    modeStr[4] = '-';\r
382                 if(acl.perms & 8)       modeStr[5] = 'x';       else    modeStr[5] = '-';\r
383                 // - World\r
384                 acl.object = 0xFFFFFFFF;\r
385                 _SysGetACL(fp, &acl);\r
386                 if(acl.perms & 1)       modeStr[6] = 'r';       else    modeStr[6] = '-';\r
387                 if(acl.perms & 2)       modeStr[7] = 'w';       else    modeStr[7] = '-';\r
388                 if(acl.perms & 8)       modeStr[8] = 'x';       else    modeStr[8] = '-';\r
389                 printf(modeStr);\r
390                 _SysClose(fp);\r
391                 \r
392                 // Colour Code\r
393                 if(info.flags & FILEFLAG_DIRECTORY)     // Directory: Green\r
394                         printf("\x1B[32m");\r
395                 // Default: White\r
396                 \r
397                 // Print Name\r
398                 printf("%s", fileName);\r
399                 \r
400                 // Print slash if applicable\r
401                 if(info.flags & FILEFLAG_DIRECTORY)\r
402                         printf("/");\r
403                 \r
404                 // Revert Colour\r
405                 printf("\x1B[37m");\r
406                 \r
407                 // Newline!\r
408                 printf("\n");\r
409         }\r
410         // Close Directory\r
411         _SysClose(dp);\r
412 }\r

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