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

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