-
Notifications
You must be signed in to change notification settings - Fork 0
/
aux.c
700 lines (574 loc) · 18.1 KB
/
aux.c
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
#include "aux.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pwd.h>
#include <errno.h>
#include <dirent.h>
#include <grp.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/wait.h>
#define TAMANO 2048
#define MAX 100
/* Funciones de ayuda */
char LetraTF (mode_t m) {
switch (m&S_IFMT) { /* And bit a bit con los bits de formato, 0170000 */
case S_IFSOCK: return 's'; /* socket */
case S_IFLNK: return 'l'; /* symbolic link */
case S_IFREG: return '-'; /* fichero normal */
case S_IFBLK: return 'b'; /* block device */
case S_IFDIR: return 'd'; /* directorio */
case S_IFCHR: return 'c'; /* char device */
case S_IFIFO: return 'p'; /* pipe */
default: return '?'; /* desconocido, no deberia aparecer */
}
}
/* Funcion de permisos */
char * ConvierteModo2 (mode_t m) {
static char permisos[12];
strcpy (permisos,"---------- ");
permisos[0]=LetraTF(m);
if (m&S_IRUSR) permisos[1]='r'; /* propietario */
if (m&S_IWUSR) permisos[2]='w';
if (m&S_IXUSR) permisos[3]='x';
if (m&S_IRGRP) permisos[4]='r'; /* grupo */
if (m&S_IWGRP) permisos[5]='w';
if (m&S_IXGRP) permisos[6]='x';
if (m&S_IROTH) permisos[7]='r'; /* resto */
if (m&S_IWOTH) permisos[8]='w';
if (m&S_IXOTH) permisos[9]='x';
if (m&S_ISUID) permisos[3]='s'; /* setuid, setgid y stickybit */
if (m&S_ISGID) permisos[6]='s';
if (m&S_ISVTX) permisos[9]='t';
return permisos;
}
/* Mostrar informacion de un fichero */
bool list_file(char *file, const int op[]){
struct stat buf;
if (stat(file, &buf) == -1) {
printf(" * Error: %s\n", strerror(errno));
return false;
}
else if(op[0] == 1) { // stat [-long]
char *permisos;
struct passwd *p;
struct group *g;
if((p = getpwuid(buf.st_uid)) == NULL) // Usuario
return -1;
if((g = getgrgid(buf.st_gid)) == NULL) // Grupo
return -1;
permisos = ConvierteModo2(buf.st_mode); // Obtener permisos
printf(" %s %lu (%lu) User name: %s GID: %s %s %ld %s\n",
ctime(&buf.st_mtime), buf.st_nlink, buf.st_ino, p->pw_name,
g->gr_name, permisos, buf.st_size, file);
if(op[1] == 1) { // stat [-link]
if (buf.st_mode &S_IFLNK)
printf(" Symbolic link = true\n");
else
printf(" Symbolic link = false\n");
}
if(op[2] == 1) // stat [-acc]
printf(" Last access: %s\n", ctime(&buf.st_atime));
} else
printf("\t%ld %s\n", buf.st_size, file);
return true;
}
/* Mostrar informacion de directorios */
bool list_dir(char *name, int op[]) {
DIR *dir;
struct dirent *entry;
char aux[MAX];
struct stat buf;
if((dir = opendir(name)) == NULL)
return false;
if (dir == NULL) {
perror("opendir() error");
return false;
}
if(op[4] == 1 && op[3] == 1) // Si es [-reca] y [-recb] entonces [-recb] tiene prefencia
op[3] = 0;
if(op[4] == 1){ // [-recb] Mostrar archivos despues (desde el final hasta donde estoy)
if(!list_dirB(name, op))
return -1;
}
else {
if(op [6] == 0)
printf("************* %s\n", name);
while ((entry = readdir(dir)) != NULL) { // Recorrer archivos del directorio
strcpy(aux, name);
strcat(strcat(aux, "/"), entry->d_name);
stat(aux, &buf);
if (entry->d_name[0] == '.' && op[5] == 1) { // [-hid] Mostrar directorios / archivos ocultos
if (!list_file(aux, op))
return false;
} else if (entry -> d_name[0] != '.' && op[3] == 0 && op[4] == 0) {
if (!list_file(aux, op))
return false;
} else if (S_ISDIR(buf.st_mode) && entry->d_name[0] != '.' && op[3] == 1) { // Si es un directorio y [-reca]
if (entry -> d_name[0] != '.' && (op[0] == 1 || op[1] == 1 || op[2] == 1)) {
if (!list_file(aux, op))
return false;
}
if (!list_dirA(aux, op)) // [-reca] Mostrar archivos antes (desde donde estoy hasta el final)
return false;
} else {
if (entry -> d_name[0] != '.')
printf("\t%ld %s\n", buf.st_size, entry -> d_name);
}
}
}
closedir(dir); // Cerrar directorio
return true;
}
/* Funcion auxiliar para list [-reca] */
int list_dirA(char *name, int op[]){
DIR *dir;
struct dirent *entry;
struct stat buf;
stat(name, &buf);
char aux[MAX];
dir = opendir(name);
if (op[0] == 0 && op[1] == 0 && op[2] == 0)
printf("\t%ld %s\n", buf.st_size, name);
printf("\n************ %s\n", name);
if (dir == NULL) {
printf(" * Error: %s\n", strerror(errno));
return false;
}
else {
while ((entry = readdir(dir)) != NULL) { // Recorrer archivos del directorio
strcpy(aux, name);
strcat(strcat(aux, "/"), entry->d_name);
stat(aux, &buf);
if (entry->d_name[0] == '.' && op[5] == 1) { // [-hid] Mostrar directorios / archivos ocultos
if (!list_file(aux, op))
return false;
}
if (S_ISDIR(buf.st_mode) && entry->d_name[0] != '.' && op[3] == 1) { // Si es un directorio y [-reca]
if (!list_dirA(aux, op))
return false;
}
if (entry->d_name[0] != '.' && (op[3] == 1 || op[4] == 1) && !S_ISDIR(buf.st_mode)) {
if (!list_file(aux, op))
return false;
}
}
}
closedir(dir); // Cerrar directorio
return true;
}
/* Funcion auxiliar para list [-recb] */
bool list_dirB(char *name, int op[]){
DIR *dir;
struct dirent *entry;
struct stat buf;
stat(name, &buf);
char aux[MAX];
int i = 0;
dir = opendir(name);
if (dir == NULL) {
perror("opendir() error");
return false;
}
else {
while ((entry = readdir(dir)) != NULL) { // Recorrer archivos del directorio
strcpy(aux, name);
strcat(strcat(aux, "/"), entry->d_name);
stat(aux, &buf);
if (entry->d_name[0] != '.' && op[4] == 1) { // Si es un directorio y [-recb]
if (S_ISDIR(buf.st_mode)) {
i++;
list_dirB(aux, op);
op[4] = 0; // Desactivar [-recb] para que no sea un bucle infinito
op[6] = 1; // opcion aux
printf("************* %s\n", name);
list_dir(name, op);
}
if (entry->d_name[0] == '.' && op[5] == 1) { // [-hid]
if (!list_file(aux, op))
return false;
}
} else {
if (entry->d_name[0] != '.')
printf("\t%ld %s\n", buf.st_size, entry->d_name);
}
}
if(i == 0) { // Ultima entrada
printf("************* %s\n", name);
op[4] = 0;
op[6] = 1;
list_dir(name, op);
}
}
closedir(dir); // Cerrar directorio
return true;
}
int pimplarDir(char *name){
DIR *dir;
struct dirent *entry;
struct stat buf;
stat(name, &buf);
char aux[MAX];
dir = opendir(name);
if (dir == NULL) {
return false;
}
else {
while ((entry = readdir(dir)) != NULL) { // Recorrer archivos del directorio
strcpy(aux, name);
strcat(strcat(aux, "/"), entry->d_name);
stat(aux, &buf);
if (entry->d_name[0] != '.') {
pimplarDir(aux);
if(buf.st_size != 0){ // Si no esta vacio -> vaciar
stat(entry -> d_name, &buf);
remove(entry -> d_name);
}
remove(aux);
}
}
}
return true;
}
void *ObtenerMemoriaShmget (key_t clave, size_t tam, MemList *L) {
void *p;
int aux,id,flags = 0777;
struct shmid_ds s;
if (tam) /* tam distinto de 0 indica crear */
flags = flags | IPC_CREAT | IPC_EXCL;
if (clave == IPC_PRIVATE) { /*no nos vale*/
errno = EINVAL;
return NULL;
}
if ((id = shmget(clave, tam, flags)) == -1)
return (NULL);
if ((p = shmat(id,NULL,0)) == (void*) -1) {
aux = errno;
if (tam)
shmctl(id,IPC_RMID,NULL);
errno = aux;
return (NULL);
}
shmctl (id,IPC_STAT,&s);
InsertarNodoShared (L, p, s.shm_segsz, clave);
return (p);
}
void do_AllocateCreateshared (char *tr[], MemList L) {
key_t cl;
size_t tam;
void *p;
if (tr[2] == NULL || tr[3] == NULL) {
printMemList(L, 1);
return;
}
cl = (key_t) strtoul(tr[2],NULL,10);
tam = (size_t) strtoul(tr[3],NULL,10);
if (tam == 0) {
printf ("No se asignan bloques de 0 bytes\n");
return;
}
if ((p = ObtenerMemoriaShmget(cl, tam, &L)) != NULL) {
printf("Asignados %lu bytes en %p\n", (unsigned long) tam, p);
LlenarMemoria(p, 26, 0, 0);
}
else
printf ("Imposible asignar memoria compartida clave %lu: %s\n",(unsigned long) cl,strerror(errno));
}
void *MapearFichero (char *fichero, int protection, MemList *MP) {
int df, map = MAP_PRIVATE, modo = O_RDONLY;
struct stat s;
void *p;
if (protection &PROT_WRITE)
modo = O_RDWR;
if (stat(fichero,&s) == -1 || (df = open(fichero, modo)) == -1)
return NULL;
if ((p = mmap(NULL,s.st_size, protection,map,df,0)) == MAP_FAILED)
return NULL;
InsertarNodoMmap(MP, p, s.st_size, df, fichero); // Insertar en la lista
return p;
}
void do_AllocateMmap(char *arg[], MemList *MP) {
char *perm;
void *p;
int protection = 0;
if (arg[2] == NULL){
printMemList(*MP, 2);
return;
}
if ((perm = arg[3]) != NULL && strlen(perm) < 4) {
if (strchr(perm,'r') != NULL) protection|=PROT_READ;
if (strchr(perm,'w') != NULL) protection|=PROT_WRITE;
if (strchr(perm,'x') != NULL) protection|=PROT_EXEC;
}
if ((p = MapearFichero(arg[2], protection, MP)) == NULL)
perror("Imposible mapear fichero\n");
else
printf("Fichero %s mapeado en %p\n", arg[2], p);
}
void do_DeallocateDelkey (char *args[]) {
key_t clave;
int id;
char *key = args[2];
if (key == NULL || (clave = (key_t) strtoul(key,NULL,10)) == IPC_PRIVATE){
printf ("delkey necesita clave_valida\n");
return;
}
if ((id = shmget(clave,0,0666)) == -1){
perror ("shmget: imposible obtener memoria compartida");
return;
}
if (shmctl(id,IPC_RMID,NULL) == -1)
perror ("shmctl: imposible eliminar memoria compartida\n");
}
ssize_t LeerFichero (char *f, void *p, size_t cont) {
struct stat s;
ssize_t n;
int df,aux;
if (stat(f,&s) == -1 || (df = open(f,O_RDONLY)) == -1)
return -1;
if (cont == -1) /* si pasamos -1 como bytes a leer lo leemos entero*/
cont=s.st_size;
if ((n = read(df,p,cont)) == -1){
aux = errno;
close(df);
errno = aux;
return -1;
}
close (df);
return n;
}
void *cadtop(char *c){
void *p;
sscanf(c, "%p", &p);
return p;
}
void do_I_O_read (char *ar[]) {
void *p;
size_t cont = -1;
ssize_t n;
if (ar[2] == NULL || ar[3] == NULL){
printf ("Faltan parametros\n");
return;
}
p = cadtop(ar[3]); /*convertimos de cadena a puntero*/
if (ar[3] != NULL)
cont = (size_t) atoll(ar[4]);
if ((n = LeerFichero(ar[2], p, cont)) == -1)
perror("Imposible leer fichero");
else
printf ("Leidos %lld bytes de %s en %p\n",(long long) n, ar[2], p);
}
ssize_t EscribirFichero (char *f, void *p, size_t cont, int overwrite) {
ssize_t n;
int df,aux, flags = O_CREAT | O_EXCL | O_WRONLY;
if (overwrite == 1)
flags = O_CREAT | O_WRONLY | O_TRUNC;
if ((df = open(f,flags, 0777)) == -1)
return -1;
if ((n = write(df,p,cont)) == -1){
aux = errno;
close(df);
errno = aux;
return -1;
}
close (df);
return n;
}
void LlenarMemoria (void *p, size_t cont, unsigned char byte, int op) {
unsigned char *arr = (unsigned char *) p;
size_t i;
if(op == 1)
printf("Llenando %zu bytes de memoria con el byte (%d) a partir de la direccion %p\n", cont, byte, arr);
for (i = 0; i < cont; i++)
arr[i] = byte;
}
void Do_pmap (void){ /*sin argumentos*/
pid_t pid; /*hace el pmap (o equivalente) del proceso actual*/
char elpid[32];
char *argv[4] = {"pmap",elpid,NULL};
sprintf (elpid,"%d", (int) getpid());
if ((pid = fork()) == -1){
perror ("Imposible crear proceso");
return;
}
if (pid == 0){
if (execvp(argv[0],argv) == -1)
perror("cannot execute pmap (linux, solaris)");
argv[0] = "procstat";
argv[1] = "vm";
argv[2] = elpid;
argv[3] = NULL;
if (execvp(argv[0],argv) == -1)/*No hay pmap, probamos procstat FreeBSD */
perror("cannot execute procstat (FreeBSD)");
argv[0] = "procmap", argv[1] = elpid;
argv[2] = NULL;
if (execvp(argv[0],argv) == -1) /*probamos procmap OpenBSD*/
perror("cannot execute procmap (OpenBSD)");
argv[0] = "vmmap";
argv[1] = "-interleave";
argv[2] = elpid;argv[3] = NULL;
if (execvp(argv[0],argv) == -1) /*probamos vmmap Mac-OS*/
perror("cannot execute vmmap (Mac-OS)");
exit(1);
}
waitpid (pid,NULL,0);
}
void Recursiva (int n) {
char automatico[TAMANO];
static char estatico[TAMANO];
printf ("parametro:%3d(%p) array %p, arr estatico %p\n",n, &n, automatico, estatico);
if (n > 0)
Recursiva(n-1);
}
void Cmd_fork (char *tr[]) {
pid_t pid;
if ((pid = fork()) == 0){
/* VaciarListaProcesos(&LP); Depende de la implementación de cada uno*/
printf ("ejecutando proceso %d\n", getpid());
}
else if (pid != -1)
waitpid (pid,NULL,0);
}
int BuscarVariable (char *var, char *e[]) { /* busca una variable en el entorno que se le pasa como parámetro */
int pos = 0;
char aux[MAXVAR];
strcpy (aux,var);
strcat (aux,"=");
while (e[pos] != NULL)
if (!strncmp(e[pos], aux, strlen(aux)))
return (pos);
else
pos++;
errno = ENOENT; /*no hay tal variable */
return(-1);
}
int CambiarVariable(char * var, char * valor, char *e[]) { /*cambia una variable en el entorno que se le pasa como parámetro*/
char *aux; /*lo hace directamente, no usa putenv*/
int pos;
if ((pos = BuscarVariable(var,e)) == -1)
return(-1);
if ((aux = (char *)malloc(strlen(var)+strlen(valor)+2)) == NULL)
return -1;
strcpy(aux,var);
strcat(aux,"=");
strcat(aux,valor);
e[pos] = aux;
return (pos);
}
/* para sistemas donde no hay (o no queremos usar) execvpe */
char * Ejecutable (char *s){
char path[MAXNAME];
static char aux2[MAXNAME];
struct stat st;
char *p;
if (s == NULL || (p = getenv("PATH")) == NULL)
return s;
if (s[0] == '/' || !strncmp (s,"./",2) || !strncmp (s,"../",3))
return s; /* is an absolute pathname */
strncpy (path, p, MAXNAME);
for (p = strtok(path,":"); p != NULL; p = strtok(NULL,":")){
sprintf (aux2,"%s/%s", p, s);
if (lstat(aux2,&st) != -1)
return aux2;
}
return s;
}
int OurExecvpe(const char *file, char *const argv[], char *const envp[]) {
return (execve(Ejecutable(file),argv, envp));
}
struct SEN{
char *nombre;
int senal;
};
/* las siguientes funciones nos permiten obtener el nombre de una senal a partir
del número y viceversa */
static struct SEN sigstrnum[]={
{"HUP", SIGHUP},
{"INT", SIGINT},
{"QUIT", SIGQUIT},
{"ILL", SIGILL},
{"TRAP", SIGTRAP},
{"ABRT", SIGABRT},
{"IOT", SIGIOT},
{"BUS", SIGBUS},
{"FPE", SIGFPE},
{"KILL", SIGKILL},
{"USR1", SIGUSR1},
{"SEGV", SIGSEGV},
{"USR2", SIGUSR2},
{"PIPE", SIGPIPE},
{"ALRM", SIGALRM},
{"TERM", SIGTERM},
{"CHLD", SIGCHLD},
{"CONT", SIGCONT},
{"STOP", SIGSTOP},
{"TSTP", SIGTSTP},
{"TTIN", SIGTTIN},
{"TTOU", SIGTTOU},
{"URG", SIGURG},
{"XCPU", SIGXCPU},
{"XFSZ", SIGXFSZ},
{"VTALRM", SIGVTALRM},
{"PROF", SIGPROF},
{"WINCH", SIGWINCH},
{"IO", SIGIO},
{"SYS", SIGSYS},
/* senales que no hay en todas partes */
#ifdef SIGPOLL
{"POLL", SIGPOLL},
#endif
#ifdef SIGPWR
{"PWR", SIGPWR},
#endif
#ifdef SIGEMT
{"EMT", SIGEMT},
#endif
#ifdef SIGINFO
{"INFO", SIGINFO},
#endif
#ifdef SIGSTKFLT
{"STKFLT", SIGSTKFLT},
#endif
#ifdef SIGCLD
{"CLD", SIGCLD},
#endif
#ifdef SIGLOST
{"LOST", SIGLOST},
#endif
#ifdef SIGCANCEL
{"CANCEL", SIGCANCEL},
#endif
#ifdef SIGTHAW
{"THAW", SIGTHAW},
#endif
#ifdef SIGFREEZE
{"FREEZE", SIGFREEZE},
#endif
#ifdef SIGLWP
{"LWP", SIGLWP},
#endif
#ifdef SIGWAITING
{"WAITING", SIGWAITING},
#endif
{NULL,-1},
}; /* fin array sigstrnum */
int ValorSenal(char * sen){ /*devuelve el numero de senial a partir del nombre */
int i;
for (i = 0; sigstrnum[i].nombre != NULL; i++)
if (!strcmp(sen, sigstrnum[i].nombre))
return sigstrnum[i].senal;
return -1;
}
char *NombreSenal(int sen){ /*devuelve el nombre senal a partir de la senal */
/* para sitios donde no hay sig2str */
int i;
for (i = 0; sigstrnum[i].nombre != NULL; i++)
if (sen == sigstrnum[i].senal)
return sigstrnum[i].nombre;
return ("SIGUNKNOWN");
}