Fixed correctness in stdio, minor changes in ls to handle dirs with negative sizes
[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_Colour(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 char    *cCOLOUR_NAMES[8] = {"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"};\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         {"colour", Command_Colour}, {"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    length = 0;\r
53          int    i;\r
54          int    iArgCount = 0;\r
55          int    bCached = 1;\r
56         \r
57         gasEnvironment = envp;\r
58         \r
59         Command_Clear(0, NULL);\r
60         \r
61         {\r
62                 char    *tmp = getenv("CWD");\r
63                 if(tmp) {\r
64                         gsCurrentDirectory = malloc(strlen(tmp)+1);\r
65                         strcpy(gsCurrentDirectory, tmp);\r
66                 } else {\r
67                         gsCurrentDirectory = malloc(2);\r
68                         strcpy(gsCurrentDirectory, "/");\r
69                 }\r
70         }       \r
71         \r
72         write(_stdout, 22, "Acess Shell Version 3\n");\r
73         write(_stdout,  2, "\n");\r
74         for(;;)\r
75         {\r
76                 // Free last command & arguments\r
77                 if(saArgs[0])   free(saArgs);\r
78                 if(!bCached)    free(sCommandStr);\r
79                 bCached = 0;\r
80                 write(_stdout, strlen(gsCurrentDirectory), gsCurrentDirectory);\r
81                 write(_stdout, 3, "$ ");\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          \r
139         // Preset Variables\r
140         ret = malloc( space+1 );\r
141         if(!ret)        return NULL;\r
142         len = 0;        pos = 0;\r
143                 \r
144         // Read In Command Line\r
145         do {\r
146                 read(_stdin, 1, &ch);   // Read Character from stdin (read is a blocking call)\r
147                 // Control characters\r
148                 if(ch == '\x1B') {\r
149                         read(_stdin, 1, &ch);   // Read control character\r
150                         switch(ch)\r
151                         {\r
152                         case 'D':       if(pos) pos--;  break;\r
153                         case 'C':       if(pos<len)     pos++;  break;\r
154                         case '[':\r
155                                 read(_stdin, 1, &ch);   // Read control character\r
156                                 switch(ch)\r
157                                 {\r
158                                 case 'D':       if(pos) pos--;  break;\r
159                                 case 'C':       if(pos<len)     pos++;  break;\r
160                                 }\r
161                         }\r
162                         continue;\r
163                 }\r
164                 // Backspace\r
165                 if(ch == '\b') {\r
166                         if(len <= 0)            continue;       // Protect against underflows\r
167                         if(pos == len) {        // Simple case of end of string\r
168                                 len --; pos--;\r
169                         } else {\r
170                                 memmove(&ret[pos-1], &ret[pos], len-pos);\r
171                                 pos --;\r
172                                 len --;\r
173                         }\r
174                         write(_stdout, 1, &ch);\r
175                         continue;\r
176                 }\r
177                 // Tab\r
178                 if(ch == '\t') {\r
179                         //TODO: Implement Tab-Completion\r
180                         //Currently just ignore tabs\r
181                         continue;\r
182                 }\r
183                 \r
184                 // Expand Buffer\r
185                 if(len > space) {\r
186                         space += 256;\r
187                         ret = realloc(ret, space+1);\r
188                         if(!ret)        return NULL;\r
189                 }\r
190                 \r
191                 write(_stdout, 1, &ch);\r
192                 ret[pos++] = ch;\r
193                 len ++;\r
194         } while(ch != '\n');\r
195         \r
196         // Remove newline\r
197         pos --;\r
198         ret[pos] = '\0';\r
199         \r
200         // Return length\r
201         if(Length)      *Length = len;\r
202         \r
203         return ret;\r
204 }\r
205 \r
206 /**\r
207  * \fn void Parse_Args(char *str, char **dest)\r
208  * \brief Parse a string into an argument array\r
209  */\r
210 void Parse_Args(char *str, char **dest)\r
211 {\r
212          int    i = 1;\r
213         char    *buf = malloc( strlen(str) + 1 );\r
214         \r
215         if(buf == NULL) {\r
216                 dest[0] = NULL;\r
217                 Print("Parse_Args: Out of heap space!\n");\r
218                 return ;\r
219         }\r
220         \r
221         strcpy(buf, str);\r
222         dest[0] = buf;\r
223         \r
224         // Trim leading whitespace\r
225         while(*buf == ' ' && *buf)      buf++;\r
226         \r
227         for(;;)\r
228         {\r
229                 dest[i] = buf;  // Save start of string\r
230                 i++;\r
231                 while(*buf && *buf != ' ')\r
232                 {\r
233                         if(*buf++ == '"')\r
234                         {\r
235                                 while(*buf && !(*buf == '"' && buf[-1] != '\\'))\r
236                                         buf++;\r
237                         }\r
238                 }\r
239                 if(*buf == '\0')        break;\r
240                 *buf = '\0';\r
241                 while(*++buf == ' ' && *buf);\r
242                 if(*buf == '\0')        break;\r
243         }\r
244         dest[i] = NULL;\r
245         if(i == 1) {\r
246                 free(buf);\r
247                 dest[0] = NULL;\r
248         }\r
249 }\r
250 \r
251 /**\r
252  * \fn void CallCommand(char **Args)\r
253  */\r
254 void CallCommand(char **Args)\r
255 {\r
256         t_sysFInfo      info;\r
257          int    pid = -1;\r
258          int    fd = 0;\r
259         char    sTmpBuffer[1024];\r
260         char    *exefile = Args[0];\r
261         \r
262         if(exefile[0] == '/'\r
263         || (exefile[0] == '.' && exefile[1] == '/')\r
264         || (exefile[0] == '.' && exefile[1] == '.' && exefile[2] == '/')\r
265                 )\r
266         {\r
267                 GeneratePath(exefile, gsCurrentDirectory, sTmpBuffer);\r
268                 // Check file existence\r
269                 fd = open(sTmpBuffer, OPENFLAG_EXEC);\r
270                 if(fd == -1) {\r
271                         Print("Unknown Command: `");Print(Args[0]);Print("'\n");        // Error Message\r
272                         return ;\r
273                 }\r
274                 \r
275                 // Get File info and close file\r
276                 finfo( fd, &info, 0 );\r
277                 close( fd );\r
278                 \r
279                 // Check if the file is a directory\r
280                 if(info.flags & FILEFLAG_DIRECTORY) {\r
281                         Print("`");Print(sTmpBuffer);   // Error Message\r
282                         Print("' is a directory.\n");\r
283                         return ;\r
284                 }\r
285         }\r
286         else\r
287         {\r
288                  int    i;\r
289                 \r
290                 // Check all components of $PATH\r
291                 for( i = 0; i < giNumPathDirs; i++ )\r
292                 {\r
293                         GeneratePath(exefile, gasPathDirs[i], sTmpBuffer);\r
294                         fd = open(sTmpBuffer, OPENFLAG_EXEC);\r
295                         if(fd == -1)    continue;\r
296                         finfo( fd, &info, 0 );\r
297                         close( fd );\r
298                         if(info.flags & FILEFLAG_DIRECTORY)     continue;\r
299                         // Woohoo! We found a valid command\r
300                         break;\r
301                 }\r
302                 \r
303                 // Exhausted path directories\r
304                 if( i == giNumPathDirs ) {\r
305                         Print("Unknown Command: `");Print(exefile);Print("'\n");\r
306                         return ;\r
307                 }\r
308         }\r
309         \r
310         // Create new process\r
311         pid = clone(CLONE_VM, 0);\r
312         // Start Task\r
313         if(pid == 0)\r
314                 execve(sTmpBuffer, Args, gasEnvironment);\r
315         if(pid <= 0) {\r
316                 Print("Unablt to create process: `");Print(sTmpBuffer);Print("'\n");    // Error Message\r
317         }\r
318         else {\r
319                  int    status;\r
320                 waittid(pid, &status);\r
321         }\r
322 }\r
323 \r
324 /**\r
325  * \fn void Command_Logout(int argc, char **argv)\r
326  * \brief Exit the shell, logging the user out\r
327  */\r
328 void Command_Logout(int argc, char **argv)\r
329 {\r
330         exit(0);\r
331 }\r
332 \r
333 /**\r
334  * \fn void Command_Clear(int argc, char **argv)\r
335  * \brief Clear the screen\r
336  */\r
337 void Command_Clear(int argc, char **argv)\r
338 {\r
339         write(_stdout, 4, "\x1B[2J");   //Clear Screen\r
340 }\r
341 \r
342 /**\r
343  * \fn void Command_Colour(int argc, char **argv)\r
344  * \brief Set the colour of the shell prompt\r
345  * \note Conflicts with coloured `dir` display\r
346  */\r
347 void Command_Colour(int argc, char **argv)\r
348 {\r
349         int fg, bg;\r
350         char    clrStr[6] = "\x1B[37m";\r
351         \r
352         // Verify Arg Count\r
353         if(argc < 2)\r
354         {\r
355                 goto usage;\r
356         }\r
357         \r
358         // Check Colour\r
359         for(fg=0;fg<8;fg++)\r
360                 if(strcmp(cCOLOUR_NAMES[fg], argv[1]) == 0)\r
361                         break;\r
362 \r
363         // Foreground a valid colour\r
364         if(fg == 8) {\r
365                 Print("Unknown Colour '");Print(argv[1]);Print("'\n");\r
366                 goto usage;\r
367         }\r
368         // Set Foreground\r
369         clrStr[3] = '0' + fg;\r
370         write(_stdout, 6, clrStr);\r
371         \r
372         // Need to Set Background?\r
373         if(argc > 2)\r
374         {\r
375                 for(bg=0;bg<8;bg++)\r
376                         if(strcmp(cCOLOUR_NAMES[bg], argv[2]) == 0)\r
377                                 break;\r
378         \r
379                 // Valid colour\r
380                 if(bg == 8)\r
381                 {\r
382                         Print("Unknown Colour '");Print(argv[2]);Print("'\n");\r
383                         goto usage;\r
384                 }\r
385         \r
386                 clrStr[2] = '4';\r
387                 clrStr[3] = '0' + bg;\r
388                 write(_stdout, 6, clrStr);\r
389         }\r
390         // Return\r
391         return;\r
392 \r
393         // Function Usage (Requested via a Goto (I know it's ugly))\r
394 usage:\r
395         Print("Usage: colour <foreground> [<background>]\n");\r
396         Print("Valid Colours are ");\r
397         for(fg=0;fg<8;fg++)\r
398         {\r
399                 Print(cCOLOUR_NAMES[fg]);\r
400                 write(_stdout, 3, ", ");\r
401         }\r
402         write(_stdout, 4, "\b\b\n");\r
403         return;\r
404 }\r
405 \r
406 /**\r
407  * \fn void Command_Cd(int argc, char **argv)\r
408  * \brief Change directory\r
409  */\r
410 void Command_Cd(int argc, char **argv)\r
411 {\r
412         char    tmpPath[1024];\r
413         int             fp;\r
414         t_sysFInfo      stats;\r
415         \r
416         if(argc < 2)\r
417         {\r
418                 Print(gsCurrentDirectory);Print("\n");\r
419                 return;\r
420         }\r
421         \r
422         GeneratePath(argv[1], gsCurrentDirectory, tmpPath);\r
423         \r
424         fp = open(tmpPath, 0);\r
425         if(fp == -1) {\r
426                 write(_stdout, 26, "Directory does not exist\n");\r
427                 return;\r
428         }\r
429         finfo(fp, &stats, 0);\r
430         close(fp);\r
431         \r
432         if( !(stats.flags & FILEFLAG_DIRECTORY) ) {\r
433                 write(_stdout, 17, "Not a Directory\n");\r
434                 return;\r
435         }\r
436         \r
437         free(gsCurrentDirectory);\r
438         gsCurrentDirectory = malloc(strlen(tmpPath)+1);\r
439         strcpy(gsCurrentDirectory, tmpPath);\r
440         \r
441         // Register change with kernel\r
442         chdir( gsCurrentDirectory );\r
443 }\r
444 \r
445 /**\r
446  * \fn void Command_Dir(int argc, char **argv)\r
447  * \brief Print the contents of a directory\r
448  */\r
449 void Command_Dir(int argc, char **argv)\r
450 {\r
451          int    dp, fp, dirLen;\r
452         char    modeStr[11] = "RWXrwxRWX ";\r
453         char    tmpPath[1024];\r
454         char    *fileName;\r
455         t_sysFInfo      info;\r
456         t_sysACL        acl;\r
457         \r
458         // Generate Directory Path\r
459         if(argc > 1)\r
460                 dirLen = GeneratePath(argv[1], gsCurrentDirectory, tmpPath);\r
461         else\r
462         {\r
463                 strcpy(tmpPath, gsCurrentDirectory);\r
464         }\r
465         dirLen = strlen(tmpPath);\r
466         \r
467         // Open Directory\r
468         dp = open(tmpPath, OPENFLAG_READ);\r
469         // Check if file opened\r
470         if(dp == -1)\r
471         {\r
472                 printf("Unable to open directory `%s', File cannot be found\n", tmpPath);\r
473                 return;\r
474         }\r
475         // Get File Stats\r
476         if( finfo(dp, &info, 0) == -1 )\r
477         {\r
478                 close(dp);\r
479                 write(_stdout, 34, "stat Failed, Bad File Descriptor\n");\r
480                 return;\r
481         }\r
482         // Check if it's a directory\r
483         if(!(info.flags & FILEFLAG_DIRECTORY))\r
484         {\r
485                 close(dp);\r
486                 write(_stdout, 27, "Unable to open directory `");\r
487                 write(_stdout, strlen(tmpPath)+1, tmpPath);\r
488                 write(_stdout, 20, "', Not a directory\n");\r
489                 return;\r
490         }\r
491         \r
492         // Append Shash for file paths\r
493         if(tmpPath[dirLen-1] != '/')\r
494         {\r
495                 tmpPath[dirLen++] = '/';\r
496                 tmpPath[dirLen] = '\0';\r
497         }\r
498         \r
499         fileName = (char*)(tmpPath+dirLen);\r
500         // Read Directory Content\r
501         while( (fp = readdir(dp, fileName)) )\r
502         {\r
503                 if(fp < 0)\r
504                 {\r
505                         if(fp == -3)\r
506                                 write(_stdout, 42, "Invalid Permissions to traverse directory\n");\r
507                         break;\r
508                 }\r
509                 // Open File\r
510                 fp = open(tmpPath, 0);\r
511                 if(fp == -1)    continue;\r
512                 // Get File Stats\r
513                 finfo(fp, &info, 0);\r
514                 \r
515                 if(info.flags & FILEFLAG_DIRECTORY)\r
516                         write(_stdout, 1, "d");\r
517                 else\r
518                         write(_stdout, 1, "-");\r
519                 \r
520                 // Print Mode\r
521                 // - Owner\r
522                 acl.group = 0;  acl.id = info.uid;\r
523                 _SysGetACL(fp, &acl);\r
524                 if(acl.perms & 1)       modeStr[0] = 'r';       else    modeStr[0] = '-';\r
525                 if(acl.perms & 2)       modeStr[1] = 'w';       else    modeStr[1] = '-';\r
526                 if(acl.perms & 8)       modeStr[2] = 'x';       else    modeStr[2] = '-';\r
527                 // - Group\r
528                 acl.group = 1;  acl.id = info.gid;\r
529                 _SysGetACL(fp, &acl);\r
530                 if(acl.perms & 1)       modeStr[3] = 'r';       else    modeStr[3] = '-';\r
531                 if(acl.perms & 2)       modeStr[4] = 'w';       else    modeStr[4] = '-';\r
532                 if(acl.perms & 8)       modeStr[5] = 'x';       else    modeStr[5] = '-';\r
533                 // - World\r
534                 acl.group = 1;  acl.id = -1;\r
535                 _SysGetACL(fp, &acl);\r
536                 if(acl.perms & 1)       modeStr[6] = 'r';       else    modeStr[6] = '-';\r
537                 if(acl.perms & 2)       modeStr[7] = 'w';       else    modeStr[7] = '-';\r
538                 if(acl.perms & 8)       modeStr[8] = 'x';       else    modeStr[8] = '-';\r
539                 write(_stdout, 10, modeStr);\r
540                 close(fp);\r
541                 \r
542                 // Colour Code\r
543                 if(info.flags & FILEFLAG_DIRECTORY)     // Directory: Green\r
544                         write(_stdout, 6, "\x1B[32m");\r
545                 // Default: White\r
546                 \r
547                 // Print Name\r
548                 write(_stdout, strlen(fileName), fileName);\r
549                 \r
550                 // Print slash if applicable\r
551                 if(info.flags & FILEFLAG_DIRECTORY)\r
552                         write(_stdout, 1, "/");\r
553                 \r
554                 // Revert Colour\r
555                 write(_stdout, 6, "\x1B[37m");\r
556                 \r
557                 // Newline!\r
558                 write(_stdout, 1, "\n");\r
559         }\r
560         // Close Directory\r
561         close(dp);\r
562 }\r

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