-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommands.c
More file actions
959 lines (807 loc) · 30.4 KB
/
commands.c
File metadata and controls
959 lines (807 loc) · 30.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
#include "utils.h"
#include "commands.h"
#include "prompt.h"
#include "alias.h"
void hop(char **args, int argc) {
char *target_dir;
char cwd[PATH_MAX];
// now i need to implement for absolute paths, he one thing i know is that it will always have argc =2 as 1 is hop command and other is an entire path without spaces and the it will have / as a character at the start
// 1 way in which i could be given the arguements is like hop /home/ineshdheer/Downloads, this case has already been handled and the other way for absolute paths is like hop ~/project, this is what i need to fix
if (argc == 1 && strcmp(args[0], "hop") == 0) {
target_dir = shell_home_directory;
if (chdir(target_dir) == -1) {
handle_error("Error changing directory");
return;
}
// Print the new working directory
if (getcwd(cwd, sizeof(cwd)) == NULL) {
handle_error("Error getting current directory");
return;
}
printf("%s\n", cwd);
return;
}
if (args[1][0] == '~' && args[1][1] == '/') {
// Handle case where path starts with ~/
char *target_dir = args[1] + 2; // Skip '~/' to get the relative path from home
char *username = get_username();
// Calculate the size needed for the final directory string
size_t final_dir_size = strlen("/home/") + strlen(username) + strlen("/") + strlen(target_dir) + 1;
// Allocate memory for the final directory path
char *final_dir = malloc(final_dir_size);
if (final_dir == NULL) {
free(final_dir);
handle_error("Error allocating memory");
return;
}
// Construct the final directory path
snprintf(final_dir, final_dir_size, "/home/%s/%s", username, target_dir);
printf("%s\n", final_dir);
// Attempt to change to the final directory
if (chdir(final_dir) == -1) {
handle_error("Error changing directory");
free(final_dir);
return;
}
free(final_dir);
return;
}
for (int i = 1; i < argc; ++i) {
target_dir = args[i];
// Handle '.' for the current directory
if (strcmp(target_dir, ".") == 0) {
target_dir = cwd;
}
// Handle '..' for the parent directory
else if (strcmp(target_dir, "..") == 0) {
if (chdir("..") == -1) {
handle_error("Error changing directory");
return;
}
if (getcwd(cwd, sizeof(cwd)) == NULL) {
handle_error("Error getting current directory");
return;
}
printf("%s\n", cwd);
continue;
}
// Handle '~' for the shell's home directory
else if (strcmp(target_dir, "~") == 0) {
target_dir = shell_home_directory;
}
// Handle '-' for the previous directory
else if (strcmp(target_dir, "-") == 0) {
if (strlen(prev_dir) == 0) {
printf("No previous directory\n");
return;
}
target_dir = prev_dir;
}
// Save the current directory before changing it
if (getcwd(cwd, sizeof(cwd)) == NULL) {
handle_error("Error getting current directory");
return;
}
// Change the directory
if (chdir(target_dir) == -1) {
handle_error("Error changing directory");
return;
}
// Update the previous directory
strncpy(prev_dir, cwd, sizeof(prev_dir) - 1);
prev_dir[sizeof(prev_dir) - 1] = '\0'; // Ensure null-termination
// Print the new working directory
if (getcwd(cwd, sizeof(cwd)) == NULL) {
handle_error("Error getting current directory");
return;
}
printf("%s\n", cwd);
}
// If no arguments are provided, hop to the home directory
}
void load_log() {
FILE *log_file = fopen(LOG_FILE_PATH, "r");
if (!log_file) return;
char buffer[256];
while (fgets(buffer, sizeof(buffer), log_file)) {
buffer[strcspn(buffer, "\n")] = 0; // Remove newline character
command_log[log_count++] = strdup(buffer);
if (log_count >= MAX_LOG_SIZE) break;
}
fclose(log_file);
}
void save_log() {
FILE *log_file = fopen(LOG_FILE_PATH, "w");
if (!log_file) {
handle_error("Failed to open log file");
return;
}
for (int i = 0; i < log_count; ++i) {
fprintf(log_file, "%s\n", command_log[i]);
// printf("wrote %s\n", command_log[i]);
free(command_log[i]); // Freeing here
command_log[i] = NULL; // Ensuring pointer is nullified after freeing
}
log_count = 0; // Reset log count after saving
fflush(log_file); // Ensure all data is written to the file
fclose(log_file);
}
// Initialize the log at startup
void init_log() {
char string1[100] = {'\0'};
strcpy(string1, shell_home_directory);
strcat(string1, "/command_log.txt");
FILE *log_file = fopen(string1, "a");
if (log_file) {
fclose(log_file); // Close immediately after ensuring the file exists
}
load_log(); // Load the log from the file
}
// Cleanup and save the log at shutdown
void cleanup_log() {
save_log(); // Log saving already frees memory, so clear_log() is no longer needed
}
// Add a command to the log
void add_to_log(const char *command) {
if (log_count > 0 && strcmp(command_log[log_count - 1], command) == 0) {
return; // Don't add if it's the same as the last command
}
if (strstr(command, "log") != NULL) {
return; // Don't add if the command contains the word 'log' anywhere
}
if (strcmp(command, "log purge") == 0) {
return; // Don't add if the command is 'log purge'
}
// If the log is full, free the oldest entry before shifting
if (log_count >= MAX_LOG_SIZE) {
free(command_log[0]);
memmove(&command_log[0], &command_log[1], sizeof(char*) * (MAX_LOG_SIZE - 1));
log_count--;
}
command_log[log_count] = strdup(command);
if (command_log[log_count] == NULL) {
handle_error("Failed to allocate memory for log entry");
return;
}
log_count++;
}
// Display the log
void display_log() {
for (int i = 0; i < log_count; ++i) {
printf("%d: %s\n", i+1, command_log[log_count - i - 1]); // Display the log in reverse order with index
}
}
// Clear the log
void clear_log() {
for (int i = 0; i < log_count; ++i) {
free(command_log[i]);
command_log[i] = NULL;
}
log_count = 0;
save_log(); // Save the cleared log to the file
}
// Execute a command from the log
void execute_from_log(int index) {
if (index < 0 || index > log_count) {
handle_error("Invalid log index");
return;
}
char *command_to_execute = command_log[log_count - index];
printf("Executing: %s\n", command_to_execute);
process_command(command_to_execute);
}
// Handle the log command
void log_command(char **args, int argc) {
if (argc == 1) {
display_log();
} else if (argc == 2 && strcmp(args[1], "purge") == 0) {
clear_log();
} else if (argc == 3 && strcmp(args[1], "execute") == 0) {
int index = atoi(args[2]);
execute_from_log(index);
} else {
handle_error("Invalid log command");
}
}
// Function to compare strings for qsort
int compare(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
// Function to print file details
void print_file_details(const char *path, const char *filename) {
struct stat fileStat;
char fullpath[PATH_MAX];
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, filename);
if (stat(fullpath, &fileStat) == -1) {
handle_error("Error getting file stats");
return;
}
// Print file type and permissions
printf((S_ISDIR(fileStat.st_mode)) ? "d" : "-");
printf((fileStat.st_mode & S_IRUSR) ? "r" : "-");
printf((fileStat.st_mode & S_IWUSR) ? "w" : "-");
printf((fileStat.st_mode & S_IXUSR) ? "x" : "-");
printf((fileStat.st_mode & S_IRGRP) ? "r" : "-");
printf((fileStat.st_mode & S_IWGRP) ? "w" : "-");
printf((fileStat.st_mode & S_IXGRP) ? "x" : "-");
printf((fileStat.st_mode & S_IROTH) ? "r" : "-");
printf((fileStat.st_mode & S_IWOTH) ? "w" : "-");
printf((fileStat.st_mode & S_IXOTH) ? "x" : "-");
// number of links to the file jo ki basically number of hard links to the file hote hain
printf(" %lu", fileStat.st_nlink);
//user and group name of the file
struct passwd *pwd = getpwuid(fileStat.st_uid);
struct group *grp = getgrgid(fileStat.st_gid);
printf(" %s %s", pwd ? pwd->pw_name : "???", grp ? grp->gr_name : "???");
// file size
printf(" %5ld", fileStat.st_size);
// last modification time
char timebuff[80];
strftime(timebuff, sizeof(timebuff), "%b %d %H:%M", localtime(&fileStat.st_mtime));
printf(" %s", timebuff);
// file name with color codes ke saath
if (S_ISDIR(fileStat.st_mode)) {
printf(" \033[1;34m%s\033[0m\n", filename); // Blue for directories
} else if (fileStat.st_mode & S_IXUSR) {
printf(" \033[1;32m%s\033[0m\n", filename); // Green for executables
} else {
printf(" \033[0;37m%s\033[0m\n", filename); // White for regular files
}
}
void reveal(char **args, int argc) {
int optind = 1;
int show_all = 0;
int show_long = 0;
char *target_dir = ".";
// Parse flags
while (optind < argc && args[optind][0] == '-') {
for (int j = 1; args[optind][j] != '\0'; ++j) {
if (args[optind][j] == 'a') {
show_all = 1;
} else if (args[optind][j] == 'l') {
show_long = 1;
} else {
// printf("Error: Invalid flag '%c'\n", args[optind][j]);
handle_error("Invalid flag");
return;
}
}
optind++;
}
if (optind < argc) {
target_dir = args[optind]; // Get target directory
}
// Handle special symbols
if (strcmp(target_dir, ".") == 0) {
target_dir = getcwd(NULL, 0); // Current working directory
} else if (strcmp(target_dir, "..") == 0 || strstr(target_dir, "../") != NULL) {
char *resolved_path = realpath(target_dir, NULL); // Resolve relative paths
if (resolved_path == NULL) {
handle_error("Error resolving path");
return;
}
target_dir = resolved_path;
} else if (target_dir[0] == '~' && target_dir[1] != '/') {
target_dir = shell_home_directory; // Shell's home directory
} else if (target_dir[0] == '~' && target_dir[1] == '/') {
char *username = get_username();
char *offset = target_dir + 2;
size_t final_dir_size = strlen("/home/") + strlen(username) + strlen("/") + strlen(offset) + 1;
char *final_dir = malloc(final_dir_size);
if (final_dir == NULL) {
handle_error("Error allocating memory");
return;
}
snprintf(final_dir, final_dir_size, "/home/%s/%s", username, offset);
target_dir = final_dir;
} else if (strcmp(target_dir, "-") == 0) {
if (strlen(prev_dir) == 0) {
handle_error("No previous directory");
return;
}
target_dir = prev_dir; // Previous directory handling
} else if (target_dir[0] == '/') {
// Do nothing for absolute path
} else {
handle_error("Invalid directory");
return;
}
DIR *dir = opendir(target_dir);
if (dir == NULL) {
handle_error("Error opening directory");
free(target_dir);
return;
}
struct dirent *entry;
char **entries = malloc(sizeof(char *) * 1000);
if (!entries) {
handle_error("Error allocating memory");
closedir(dir);
free(target_dir);
return;
}
int count = 0;
// Read and store directory entries
while ((entry = readdir(dir)) != NULL) {
if (!show_all && entry->d_name[0] == '.') {
continue;
}
entries[count++] = strdup(entry->d_name);
}
closedir(dir);
// Sort entries lexicographically
qsort(entries, count, sizeof(char*), compare);
// Print entries with color coding regardless of flags
for (int i = 0; i < count; ++i) {
if (show_long) {
print_file_details(target_dir, entries[i]);
} else {
// Always apply color coding
struct stat fileStat;
char fullpath[PATH_MAX];
snprintf(fullpath, sizeof(fullpath), "%s/%s", target_dir, entries[i]);
stat(fullpath, &fileStat); // Get file stats for color coding
// Print file name with color coding
if (S_ISDIR(fileStat.st_mode)) {
printf("\033[1;34m%s\033[0m\n", entries[i]); // Blue directories
} else if (fileStat.st_mode & S_IXUSR) {
printf("\033[1;32m%s\033[0m\n", entries[i]); // Green executables
} else {
printf("\033[0;37m%s\033[0m\n", entries[i]); // White for others
}
}
free(entries[i]);
}
// Free dynamically allocated memory for target_dir
if (target_dir != args[optind]) {
free(target_dir);
}
free(entries);
}
// void print_process_details(pid_t pid) { // backup function without the foreground and background process group check
// char path[4096];
// char status[4096];
// char exec_path[4096];
// // Prepare the path to the status file
// sprintf(path, "/proc/%d/status", pid);
// FILE *fp = fopen(path, "r");
// if (fp == NULL) {
// handle_error("Error opening status file");
// return;
// }
// printf("PID: %d\n", pid);
// // Get the process group ID
// pid_t pgid = getpgid(pid);
// if (pgid < 0) {
// handle_error("Error getting process group");
// fclose(fp);
// return;
// }
// printf("Process Group: %d\n", pgid);
// // Read and print the process state and memory size
// while (fgets(status, sizeof(status), fp) != NULL) {
// if (strncmp(status, "State:", 6) == 0) {
// // Print the full state description
// printf("State: %s", status + 7); // Print the whole line, not just the character
// } else if (strncmp(status, "VmSize:", 7) == 0) {
// printf("%s", status); // Print virtual memory size
// }
// }
// fclose(fp);
// // Prepare the path to the executable link
// sprintf(path, "/proc/%d/exe", pid);
// ssize_t len = readlink(path, exec_path, sizeof(exec_path) - 1);
// if (len != -1) {
// exec_path[len] = '\0';
// printf("Executable Path: %s\n", exec_path); // Print executable path
// } else {
// handle_error("Error reading executable path");
// }
// }
void print_process_details(pid_t pid) {
char path[4096];
char status[4096];
char exec_path[4096];
char full_state[4096]; // To store the full state description
// Prepare the path to the status file
sprintf(path, "/proc/%d/status", pid);
FILE *fp = fopen(path, "r");
if (fp == NULL) {
handle_error("Error opening status file");
return;
}
printf("PID: %d\n", pid);
// Get the process group ID
pid_t pgid = getpgid(pid);
if (pgid < 0) {
handle_error("Error getting process group");
fclose(fp);
return;
}
printf("Process Group: %d\n", pgid);
// Get the foreground process group ID for the terminal
pid_t fg_pgid = tcgetpgrp(STDIN_FILENO);
// Read the process state
char state_char = '\0'; // Variable to hold the state character
while (fgets(status, sizeof(status), fp) != NULL) {
if (strncmp(status, "State:", 6) == 0) {
// Extract the state character (first character after "State:")
state_char = status[7];
// Store the full state description (everything after "State: ")
strncpy(full_state, status + 8, sizeof(full_state) - 1); // +8 to skip "State: "
full_state[sizeof(full_state) - 1] = '\0'; // Ensure null-termination
break; // We only need the state line, so we can exit the loop early
}
}
fclose(fp);
// Print the state with or without the '+' depending on foreground/background status
if (pgid == fg_pgid) {
// Foreground process: add a '+' after the state character
printf("State: %c+%s", state_char, full_state);
} else {
// Background process: print only the state character with the description
printf("State: %c%s", state_char, full_state);
}
// Prepare the path to the executable link
sprintf(path, "/proc/%d/exe", pid);
ssize_t len = readlink(path, exec_path, sizeof(exec_path) - 1);
if (len != -1) {
exec_path[len] = '\0';
printf("Executable Path: %s\n", exec_path); // Print executable path
} else {
handle_error("Error reading executable path");
}
}
void proclore(char **args, int argc) {
if (argc == 1) {
// Print details of the opened shell (the current shell process)
print_process_details(getpid());
} else {
// Extract PID from args and print details of the specified process
int pid = atoi(args[1]);
if (pid <= 0) {
printf("Invalid PID\n");
return;
}
print_process_details(pid);
}
}
void search_directory(const char *base_dir, const char *search_term, char results[MAX_RESULTS][MAX_PATH], int *result_count, int d_flag, int f_flag, int e_flag, char *found_file, char *found_dir, int *file_count, int *dir_count) {
DIR *dir;
struct dirent *entry;
struct stat path_stat;
char path[MAX_PATH];
if (!(dir = opendir(base_dir))) {
handle_error("Error opening directory");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
snprintf(path, sizeof(path), "%s/%s", base_dir, entry->d_name);
stat(path, &path_stat);
// Calculate the relative path from the base directory
const char *relative_path = path + strlen(base_dir) + 1;
if (S_ISDIR(path_stat.st_mode)) {
if (strncmp(entry->d_name, search_term, strlen(search_term)) == 0 && (d_flag || (!d_flag && !f_flag))) {
(*dir_count)++;
strncpy(found_dir, path, sizeof(path));
if (*result_count < MAX_RESULTS) {
snprintf(results[*result_count], MAX_PATH, BLUE "%s" RESET, relative_path);
(*result_count)++;
}
}
// Recursively search in this directory
search_directory(path, search_term, results, result_count, d_flag, f_flag, e_flag, found_file, found_dir, file_count, dir_count);
} else if (S_ISREG(path_stat.st_mode)) {
if (strncmp(entry->d_name, search_term, strlen(search_term)) == 0 && (f_flag || (!d_flag && !f_flag))) {
(*file_count)++;
strncpy(found_file, path, sizeof(path));
if (*result_count < MAX_RESULTS) {
snprintf(results[*result_count], MAX_PATH, GREEN "%s" RESET, relative_path);
(*result_count)++;
}
}
}
}
closedir(dir);
}
void seek(char **args, int argc) {
int d_flag = 0, f_flag = 0, e_flag = 0;
char *target_name = NULL;
char *target_dir = ".";
int file_count = 0, dir_count = 0;
char found_file[MAX_PATH] = {0};
char found_dir[MAX_PATH] = {0};
for (int i = 1; i < argc; i++) {
if (strcmp(args[i], "-d") == 0) {
d_flag = 1;
} else if (strcmp(args[i], "-f") == 0) {
f_flag = 1;
} else if (strcmp(args[i], "-e") == 0) {
e_flag = 1;
} else if (!target_name) {
target_name = args[i];
} else {
target_dir = args[i];
}
}
if (d_flag && f_flag) {
printf("Invalid flags! Cannot use both -d and -f at the same time.\n");
return;
}
if (!target_name) {
printf("No target name provided!\n");
return;
}
char results[MAX_RESULTS][MAX_PATH];
int result_count = 0;
search_directory(target_dir, target_name, results, &result_count, d_flag, f_flag, e_flag, found_file, found_dir, &file_count, &dir_count);
if (result_count == 0) {
printf("No match found!\n");
} else {
for (int i = 0; i < result_count; i++) {
printf("%s\n", results[i]);
}
}
if (e_flag) {
if (file_count == 1 && dir_count == 0) {
FILE *file = fopen(found_file, "r");
if (!file) {
handle_error("Error opening file");
return;
}
char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);
} else if (dir_count == 1 && file_count == 0) {
if (chdir(found_dir) == 0) {
char cwd[MAX_PATH];
getcwd(cwd, sizeof(cwd));
printf("Changed directory to: %s\n", cwd);
} else {
handle_error("Error changing directory");
}
} else {
printf("No match found!\n");
}
}
}
// Error handling function
void reportError(const char *message) {
perror(message);
}
// Global variable to hold terminal settings
struct termios originalTermios;
// Function to restore the original terminal settings
void restoreTerminalMode() {
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &originalTermios) == -1) {
reportError("tcsetattr failed");
}
}
// Function to set the terminal to raw mode
void configureRawMode() {
if (tcgetattr(STDIN_FILENO, &originalTermios) == -1) {
reportError("tcgetattr failed");
}
atexit(restoreTerminalMode);
struct termios rawSettings = originalTermios;
rawSettings.c_lflag &= ~(ICANON | ECHO);
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &rawSettings) == -1) {
reportError("tcsetattr failed");
}
}
// Function to continuously print the last PID
void executeNeonate(int interval) {
setbuf(stdout, NULL);
configureRawMode();
pid_t childProcess = fork();
if (childProcess == 0) {
// Child process
while (1) {
FILE *pidFile = fopen("/proc/sys/kernel/ns_last_pid", "r");
if (pidFile) {
char lastPid[10];
if (fgets(lastPid, sizeof(lastPid), pidFile) != NULL) {
printf("%s", lastPid);
}
fclose(pidFile);
}
sleep(interval);
}
} else if (childProcess > 0) {
// Parent process
char inputChar;
while (read(STDIN_FILENO, &inputChar, 1) == 1 && inputChar != 'x') {
// Wait for the user to press 'x'
}
kill(childProcess, SIGKILL); // Terminate the child process
}
restoreTerminalMode(); // Restore terminal settings before exiting
}
// Function to handle the neonate command
void handleNeonateCommand(char *command) {
char *argument = strtok(command, " "); // Get the command name
argument = strtok(NULL, " "); // Get the first argument
if (argument == NULL) {
// If no time argument is provided, print the last PID
FILE *pidFile = fopen("/proc/sys/kernel/ns_last_pid", "r");
if (pidFile) {
char lastPid[10];
fgets(lastPid, sizeof(lastPid), pidFile);
printf("%s", lastPid);
fclose(pidFile);
}
return;
}
argument = strtok(NULL, " "); // Get the second argument
if (argument == NULL) {
printf("Error: Insufficient arguments provided!\n");
return;
}
int interval = atoi(argument); // Convert the time argument to an integer
executeNeonate(interval); // Execute the neonate command with the specified time interval
}
void remove_html_tags(char *str) { // rephrase this function
regex_t regex;
regmatch_t match[1];
char* tagStart;
char* tagEnd;
const char *pattern = "<[^>]*>";
// Compile the regular expression
if (regcomp(®ex, pattern, REG_EXTENDED) != 0) {
fprintf(stderr, "Could not compile regex\n");
return;
}
// Process the input string
while (regexec(®ex, str, 1, match, 0) == 0) {
tagStart = str + match[0].rm_so;
tagEnd = str + match[0].rm_eo;
memmove(tagStart, tagEnd, strlen(tagEnd) + 1);
}
// Free the compiled regular expression
regfree(®ex);
}
void iMan(char *cmd) {
int sockfd;
struct addrinfo hints, *servinfo, *p;
char buffer[BUFFER_SIZE];
int bytes_received;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(HOST, PORT, &hints, &servinfo) != 0) {
handle_error("Failed to get address info");
return;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
continue; // Try the next address
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
continue; // Try the next address
}
break; // Successfully connected
}
if (p == NULL) {
fprintf(stderr, "Failed to connect\n");
return;
}
freeaddrinfo(servinfo); // Free the linked list
char request[BUFFER_SIZE];
snprintf(request, sizeof(request),
"GET /?topic=%s§ion=all HTTP/1.1\r\n"
"Host: %s\r\n"
"Connection: close\r\n\r\n",
cmd, HOST);
if (send(sockfd, request, strlen(request), 0) == -1) {
handle_error("Failed to send request");
close(sockfd);
return;
}
// int header_ended = 0;
int i=0;
bool inside_tag = false;
int counter=0;
while ((bytes_received = recv(sockfd, buffer, BUFFER_SIZE - 1, 0)) > 0) {
buffer[bytes_received] = '\0';
if(counter==0){
while(buffer[i]!='<'){
i++;
}
while (i < bytes_received)
{
if (buffer[i] == '<')
{
inside_tag = true; // Entering an HTML tag
}
if (!inside_tag)
{
printf("%c", buffer[i]); // Only print characters outside of tags
}
if (buffer[i] == '>')
{
inside_tag = false; // Exiting an HTML tag
}
i++;
}
counter++;
}
}
remove_html_tags(buffer);
printf("%s", buffer); // Print the rest of the response
if (bytes_received == -1) {
handle_error("Failed to receive data");
}
close(sockfd); // Close the socket
}
void ping_process(pid_t pid, int signal_number) {
int actual_signal = signal_number % 32;
// Check if the process with given PID exists
if (kill(pid, 0) == -1) {
if (errno == ESRCH) {
handle_error("No such process found");
} else if (errno == EPERM) {
handle_error("Permission denied to signal the process");
} else {
handle_error("Failed to find process");
}
return;
}
// Send the signal to the process
if (kill(pid, actual_signal) == 0) {
printf("Sent signal %d (%s) to process with PID %d\n", actual_signal, strsignal(actual_signal), pid);
} else {
handle_error("Failed to send signal");
}
}
void fg_process(pid_t pid) {
int found = 0;
for (int i = 0; i < bg_count; i++) {
if (bg_processes[i].pid == pid) {
found = 1;
update_foreground_pid(pid);
strcpy(bg_processes[i].state, "Running");
printf("Bringing PID %d to the foreground...\n", pid);
// Remove the process from the background list
remove_background_process(pid);
// Continue the process if it was stopped
kill(pid, SIGCONT);
int status;
waitpid(pid, &status, WUNTRACED);
if (WIFEXITED(status)) {
printf("Foreground process with PID %d exited normally.\n", pid);
} else if (WIFSIGNALED(status)) {
// printf("Foreground process with PID %d was terminated by signal %d.\n", pid, WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
// printf("Foreground process with PID %d was stopped.\n", pid);
add_to_background_processes(pid, get_command_name(pid));
} else if (WIFCONTINUED(status)) {
// printf("Foreground process with PID %d continued.\n", pid);
}
// Reset the foreground PID after process completes
update_foreground_pid(-1);
return;
}
}
if (!found) {
fprintf(stderr, "No background process found with PID %d\n", pid);
}
}
void bg_process(pid_t pid) {
// Check if the process exists in the background list
for (int i = 0; i < bg_count; i++) {
if (bg_processes[i].pid == pid) {
// Send SIGCONT signal to continue the process
kill(pid, SIGCONT);
printf("Process with PID %d resumed in the background.\n", pid);
strcpy(bg_processes[i].state, "Running");
return;
}
}
printf("No such background process found with PID %d.\n", pid);
}