-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimplesh.c
More file actions
1964 lines (1716 loc) · 61.6 KB
/
simplesh.c
File metadata and controls
1964 lines (1716 loc) · 61.6 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
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Shell `simplesh` (basado en el shell de xv6)
*
* Ampliación de Sistemas Operativos
* Departamento de Ingeniería y Tecnología de Computadores
* Facultad de Informática de la Universidad de Murcia
*
* Alumnos: García Martínez, Alejandro (G2.1)
* Pérez Martínez, Eduardo (G2.2)
*
* Convocatoria: FEBRERO
*/
/*
* Ficheros de cabecera
*/
// bloquear sigchild antes del fork y desbloquearla después de salir de el o bien antes del run_cmd bloquear y desbloquear despues del run_cmd
// el codigo para bloquear e ignorar una señal (b4) se debe añadir justo al inicio del programa
#define _POSIX_C_SOURCE 200809L /* IEEE 1003.1-2008 (véase /usr/include/features.h) */
//#define NDEBUG /* Traduce asertos y DMACROS a 'no ops' */
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
//getuid/pwuid
#include <sys/types.h>
#include <pwd.h>
//getcwd
#include <limits.h>
//basename
#include <libgen.h>
// Biblioteca readline
#include <readline/readline.h>
#include <readline/history.h>
// cwd
#include <unistd.h>
//psplit
#include <ctype.h>
//señales
#include <signal.h>
#include <math.h>
//man 2 llamadas al sistema y man 3 funciones de biblioteca
/******************************************************************************
* Constantes, macros y variables globales
******************************************************************************/
const int BSIZEMAX = 1048576;
static const int intersNumber = 5;
static const char* internCommands[] = {"cwd","exit", "cd", "psplit", "bjobs"};
static const char* VERSION = "0.19";
int oldpwddefined = 0;
#define NMAXPROCCES 31
int childsproc[NMAXPROCCES];
int childs_act = 0;
sigset_t blocked_signals ;
// Niveles de depuración
#define DBG_CMD (1 << 0)
#define DBG_TRACE (1 << 1)
// . . .
static int g_dbg_level = 0;
#ifndef NDEBUG
#define DPRINTF(dbg_level, fmt, ...) \
do { \
if (dbg_level & g_dbg_level) \
fprintf(stderr, "%s:%d:%s(): " fmt, \
__FILE__, __LINE__, __func__, ##__VA_ARGS__); \
} while ( 0 )
#define DBLOCK(dbg_level, block) \
do { \
if (dbg_level & g_dbg_level) \
block; \
} while( 0 );
#else
#define DPRINTF(dbg_level, fmt, ...)
#define DBLOCK(dbg_level, block)
#endif
#define TRY(x) \
do { \
int __rc = (x); \
if( __rc < 0 ) { \
fprintf(stderr, "%s:%d:%s: TRY(%s) failed\n", \
__FILE__, __LINE__, __func__, #x); \
fprintf(stderr, "ERROR: rc=%d errno=%d (%s)\n", \
__rc, errno, strerror(errno)); \
exit(EXIT_FAILURE); \
} \
} while( 0 )
// Número máximo de argumentos de un comando
#define MAX_ARGS 16
// Delimitadores
static const char WHITESPACE[] = " \t\r\n\v";
// Caracteres especiales
static const char SYMBOLS[] = "<|>&;()";
/******************************************************************************
* Funciones auxiliares
******************************************************************************/
// Imprime el mensaje
void info(const char *fmt, ...)
{
va_list arg;
fprintf(stdout, "%s: ", __FILE__);
va_start(arg, fmt);
vfprintf(stdout, fmt, arg);
va_end(arg);
}
// Imprime el mensaje de error
void error(const char *fmt, ...)
{
va_list arg;
fprintf(stderr, "%s: ", __FILE__);
va_start(arg, fmt);
vfprintf(stderr, fmt, arg);
va_end(arg);
}
// Imprime el mensaje de error y aborta la ejecución
void panic(const char *fmt, ...)
{
va_list arg;
fprintf(stderr, "%s: ", __FILE__);
va_start(arg, fmt);
vfprintf(stderr, fmt, arg);
va_end(arg);
exit(EXIT_FAILURE);
}
// `fork()` que muestra un mensaje de error si no se puede crear el hijo
int fork_or_panic(const char* s)
{
int pid;
pid = fork();
if(pid == -1)
panic("%s failed: errno %d (%s)", s, errno, strerror(errno));
return pid;
}
/******************************************************************************
* Estructuras de datos `cmd`
******************************************************************************/
// Las estructuras `cmd` se utilizan para almacenar información que servirá a
// simplesh para ejecutar líneas de órdenes con redirecciones, tuberías, listas
// de comandos y tareas en segundo plano. El formato es el siguiente:
// |----------+--------------+--------------|
// | (1 byte) | ... | ... |
// |----------+--------------+--------------|
// | type | otros campos | otros campos |
// |----------+--------------+--------------|
// Nótese cómo las estructuras `cmd` comparten el primer campo `type` para
// identificar su tipo. A partir de él se obtiene un tipo derivado a través de
// *casting* forzado de tipo. Se consigue así polimorfismo básico en C.
// Valores del campo `type` de las estructuras de datos `cmd`
enum cmd_type { EXEC=1, REDR=2, PIPE=3, LIST=4, BACK=5, SUBS=6, INV=7 };
struct cmd { enum cmd_type type; };
// Comando con sus parámetros
struct execcmd {
enum cmd_type type;
char* argv[MAX_ARGS];
char* eargv[MAX_ARGS];
int argc;
};
// Comando con redirección
struct redrcmd {
enum cmd_type type;
struct cmd* cmd;
char* file;
char* efile;
int flags;
mode_t mode;
int fd;
};
// Comandos con tubería
struct pipecmd {
enum cmd_type type;
struct cmd* left;
struct cmd* right;
};
// Lista de órdenes
struct listcmd {
enum cmd_type type;
struct cmd* left;
struct cmd* right;
};
// Tarea en segundo plano (background) con `&`
struct backcmd {
enum cmd_type type;
struct cmd* cmd;
};
// Subshell
struct subscmd {
enum cmd_type type;
struct cmd* cmd;
};
/******************************************************************************
* Funciones para construir las estructuras de datos `cmd`
******************************************************************************/
// Construye una estructura `cmd` de tipo `EXEC`
struct cmd* execcmd(void)
{
struct execcmd* cmd;
if ((cmd = malloc(sizeof(*cmd))) == NULL)
{
perror("execcmd: malloc");
exit(EXIT_FAILURE);
}
memset(cmd, 0, sizeof(*cmd));
cmd->type = EXEC;
return (struct cmd*) cmd;
}
// Construye una estructura `cmd` de tipo `REDR`
struct cmd* redrcmd(struct cmd* subcmd,
char* file, char* efile,
int flags, mode_t mode, int fd)
{
struct redrcmd* cmd;
if ((cmd = malloc(sizeof(*cmd))) == NULL)
{
perror("redrcmd: malloc");
exit(EXIT_FAILURE);
}
memset(cmd, 0, sizeof(*cmd));
cmd->type = REDR;
cmd->cmd = subcmd;
cmd->file = file;
cmd->efile = efile;
cmd->flags = flags;
cmd->mode = mode;
cmd->fd = fd;
return (struct cmd*) cmd;
}
// Construye una estructura `cmd` de tipo `PIPE`
struct cmd* pipecmd(struct cmd* left, struct cmd* right)
{
struct pipecmd* cmd;
if ((cmd = malloc(sizeof(*cmd))) == NULL)
{
perror("pipecmd: malloc");
exit(EXIT_FAILURE);
}
memset(cmd, 0, sizeof(*cmd));
cmd->type = PIPE;
cmd->left = left;
cmd->right = right;
return (struct cmd*) cmd;
}
// Construye una estructura `cmd` de tipo `LIST`
struct cmd* listcmd(struct cmd* left, struct cmd* right)
{
struct listcmd* cmd;
if ((cmd = malloc(sizeof(*cmd))) == NULL)
{
perror("listcmd: malloc");
exit(EXIT_FAILURE);
}
memset(cmd, 0, sizeof(*cmd));
cmd->type = LIST;
cmd->left = left;
cmd->right = right;
return (struct cmd*)cmd;
}
// Construye una estructura `cmd` de tipo `BACK`
struct cmd* backcmd(struct cmd* subcmd)
{
struct backcmd* cmd;
if ((cmd = malloc(sizeof(*cmd))) == NULL)
{
perror("backcmd: malloc");
exit(EXIT_FAILURE);
}
memset(cmd, 0, sizeof(*cmd));
cmd->type = BACK;
cmd->cmd = subcmd;
return (struct cmd*)cmd;
}
// Construye una estructura `cmd` de tipo `SUB`
struct cmd* subscmd(struct cmd* subcmd)
{
struct subscmd* cmd;
if ((cmd = malloc(sizeof(*cmd))) == NULL)
{
perror("subscmd: malloc");
exit(EXIT_FAILURE);
}
memset(cmd, 0, sizeof(*cmd));
cmd->type = SUBS;
cmd->cmd = subcmd;
return (struct cmd*) cmd;
}
/******************************************************************************
* Funciones para realizar el análisis sintáctico de la línea de órdenes
******************************************************************************/
// `get_token` recibe un puntero al principio de una cadena (`start_of_str`),
// otro puntero al final de esa cadena (`end_of_str`) y, opcionalmente, dos
// punteros para guardar el principio y el final del token, respectivamente.
//
// `get_token` devuelve un *token* de la cadena de entrada.
int get_token(char** start_of_str, char const* end_of_str,
char** start_of_token, char** end_of_token)
{
char* s;
int ret;
// Salta los espacios en blanco
s = *start_of_str;
while (s < end_of_str && strchr(WHITESPACE, *s))
s++;
// `start_of_token` apunta al principio del argumento (si no es NULL)
if (start_of_token)
*start_of_token = s;
ret = *s;
switch (*s)
{
case 0:
break;
case '|':
case '(':
case ')':
case ';':
case '&':
case '<':
s++;
break;
case '>':
s++;
if (*s == '>')
{
ret = '+';
s++;
}
break;
default:
// El caso por defecto (cuando no hay caracteres especiales) es el
// de un argumento de un comando. `get_token` devuelve el valor
// `'a'`, `start_of_token` apunta al argumento (si no es `NULL`),
// `end_of_token` apunta al final del argumento (si no es `NULL`) y
// `start_of_str` avanza hasta que salta todos los espacios
// *después* del argumento. Por ejemplo:
//
// |-----------+---+---+---+---+---+---+---+---+---+-----------|
// | (espacio) | a | r | g | u | m | e | n | t | o | (espacio)
// |
// |-----------+---+---+---+---+---+---+---+---+---+-----------|
// ^ ^
// start_o|f_token end_o|f_token
ret = 'a';
while (s < end_of_str &&
!strchr(WHITESPACE, *s) &&
!strchr(SYMBOLS, *s))
s++;
break;
}
// `end_of_token` apunta al final del argumento (si no es `NULL`)
if (end_of_token)
*end_of_token = s;
// Salta los espacios en blanco
while (s < end_of_str && strchr(WHITESPACE, *s))
s++;
// Actualiza `start_of_str`
*start_of_str = s;
return ret;
}
// `peek` recibe un puntero al principio de una cadena (`start_of_str`), otro
// puntero al final de esa cadena (`end_of_str`) y un conjunto de caracteres
// (`delimiter`).
//
// El primer puntero pasado como parámero (`start_of_str`) avanza hasta el
// primer carácter que no está en el conjunto de caracteres `WHITESPACE`.
//
// `peek` devuelve un valor distinto de `NULL` si encuentra alguno de los
// caracteres en `delimiter` justo después de los caracteres en `WHITESPACE`.
int peek(char** start_of_str, char const* end_of_str, char* delimiter)
{
char* s;
s = *start_of_str;
while (s < end_of_str && strchr(WHITESPACE, *s))
s++;
*start_of_str = s;
return *s && strchr(delimiter, *s);
}
// Definiciones adelantadas de funciones
struct cmd* parse_line(char**, char*);
struct cmd* parse_pipe(char**, char*);
struct cmd* parse_exec(char**, char*);
struct cmd* parse_subs(char**, char*);
struct cmd* parse_redr(struct cmd*, char**, char*);
struct cmd* null_terminate(struct cmd*);
// `parse_cmd` realiza el *análisis sintáctico* de la línea de órdenes
// introducida por el usuario.
//
// `parse_cmd` utiliza `parse_line` para obtener una estructura `cmd`.
struct cmd* parse_cmd(char* start_of_str)
{
char* end_of_str;
struct cmd* cmd;
DPRINTF(DBG_TRACE, "STR\n");
end_of_str = start_of_str + strlen(start_of_str);
cmd = parse_line(&start_of_str, end_of_str);
// Comprueba que se ha alcanzado el final de la línea de órdenes
peek(&start_of_str, end_of_str, "");
if (start_of_str != end_of_str)
error("%s: error sintáctico: %s\n", __func__);
DPRINTF(DBG_TRACE, "END\n");
return cmd;
}
// `parse_line` realiza el análisis sintáctico de la línea de órdenes
// introducida por el usuario.
//
// `parse_line` comprueba en primer lugar si la línea contiene alguna tubería.
// Para ello `parse_line` llama a `parse_pipe` que a su vez verifica si hay
// bloques de órdenes y/o redirecciones. A continuación, `parse_line`
// comprueba si la ejecución de la línea se realiza en segundo plano (con `&`)
// o si la línea de órdenes contiene una lista de órdenes (con `;`).
struct cmd* parse_line(char** start_of_str, char* end_of_str)
{
struct cmd* cmd;
int delimiter;
cmd = parse_pipe(start_of_str, end_of_str);
while (peek(start_of_str, end_of_str, "&"))
{
// Consume el delimitador de tarea en segundo plano
delimiter = get_token(start_of_str, end_of_str, 0, 0);
assert(delimiter == '&');
// Construye el `cmd` para la tarea en segundo plano
cmd = backcmd(cmd);
}
if (peek(start_of_str, end_of_str, ";"))
{
if (cmd->type == EXEC && ((struct execcmd*) cmd)->argv[0] == 0)
error("%s: error sintáctico: no se encontró comando\n", __func__);
// Consume el delimitador de lista de órdenes
delimiter = get_token(start_of_str, end_of_str, 0, 0);
assert(delimiter == ';');
// Construye el `cmd` para la lista
cmd = listcmd(cmd, parse_line(start_of_str, end_of_str));
}
return cmd;
}
// `parse_pipe` realiza el análisis sintáctico de una tubería de manera
// recursiva si encuentra el delimitador de tuberías '|'.
//
// `parse_pipe` llama a `parse_exec` y `parse_pipe` de manera recursiva para
// realizar el análisis sintáctico de todos los componentes de la tubería.
struct cmd* parse_pipe(char** start_of_str, char* end_of_str)
{
struct cmd* cmd;
int delimiter;
cmd = parse_exec(start_of_str, end_of_str);
if (peek(start_of_str, end_of_str, "|"))
{
if (cmd->type == EXEC && ((struct execcmd*) cmd)->argv[0] == 0)
error("%s: error sintáctico: no se encontró comando\n", __func__);
// Consume el delimitador de tubería
delimiter = get_token(start_of_str, end_of_str, 0, 0);
assert(delimiter == '|');
// Construye el `cmd` para la tubería
cmd = pipecmd(cmd, parse_pipe(start_of_str, end_of_str));
}
return cmd;
}
// `parse_exec` realiza el análisis sintáctico de un comando a no ser que la
// expresión comience por un paréntesis, en cuyo caso se llama a `parse_subs`.
//
// `parse_exec` reconoce las redirecciones antes y después del comando.
struct cmd* parse_exec(char** start_of_str, char* end_of_str)
{
char* start_of_token;
char* end_of_token;
int token, argc;
struct execcmd* cmd;
struct cmd* ret;
// ¿Inicio de un bloque?
if (peek(start_of_str, end_of_str, "("))
return parse_subs(start_of_str, end_of_str);
// Si no, lo primero que hay en una línea de órdenes es un comando
// Construye el `cmd` para el comando
ret = execcmd();
cmd = (struct execcmd*) ret;
// ¿Redirecciones antes del comando?
ret = parse_redr(ret, start_of_str, end_of_str);
// Bucle para separar los argumentos de las posibles redirecciones
argc = 0;
while (!peek(start_of_str, end_of_str, "|)&;"))
{
if ((token = get_token(start_of_str, end_of_str,
&start_of_token, &end_of_token)) == 0)
break;
// El siguiente token debe ser un argumento porque el bucle
// para en los delimitadores
if (token != 'a')
error("%s: error sintáctico: se esperaba un argumento\n", __func__);
// Almacena el siguiente argumento reconocido. El primero es
// el comando
cmd->argv[argc] = start_of_token;
cmd->eargv[argc] = end_of_token;
cmd->argc = ++argc;
if (argc >= MAX_ARGS)
panic("%s: demasiados argumentos\n", __func__);
// ¿Redirecciones después del comando?
ret = parse_redr(ret, start_of_str, end_of_str);
}
// El comando no tiene más parámetros
cmd->argv[argc] = 0;
cmd->eargv[argc] = 0;
return ret;
}
// `parse_subs` realiza el análisis sintáctico de un bloque de órdenes
// delimitadas por paréntesis o `subshell` llamando a `parse_line`.
//
// `parse_subs` reconoce las redirecciones después del bloque de órdenes.
struct cmd* parse_subs(char** start_of_str, char* end_of_str)
{
int delimiter;
struct cmd* cmd;
struct cmd* scmd;
// Consume el paréntesis de apertura
if (!peek(start_of_str, end_of_str, "("))
error("%s: error sintáctico: se esperaba '('", __func__);
delimiter = get_token(start_of_str, end_of_str, 0, 0);
assert(delimiter == '(');
// Realiza el análisis sintáctico hasta el paréntesis de cierre
scmd = parse_line(start_of_str, end_of_str);
// Construye el `cmd` para el bloque de órdenes
cmd = subscmd(scmd);
// Consume el paréntesis de cierre
if (!peek(start_of_str, end_of_str, ")"))
error("%s: error sintáctico: se esperaba ')'", __func__);
delimiter = get_token(start_of_str, end_of_str, 0, 0);
assert(delimiter == ')');
// ¿Redirecciones después del bloque de órdenes?
cmd = parse_redr(cmd, start_of_str, end_of_str);
return cmd;
}
// `parse_redr` realiza el análisis sintáctico de órdenes con
// redirecciones si encuentra alguno de los delimitadores de
// redirección ('<' o '>').
struct cmd* parse_redr(struct cmd* cmd, char** start_of_str, char* end_of_str)
{
int delimiter;
char* start_of_token;
char* end_of_token;
// Si lo siguiente que hay a continuación es delimitador de
// redirección...
while (peek(start_of_str, end_of_str, "<>"))
{
// Consume el delimitador de redirección
delimiter = get_token(start_of_str, end_of_str, 0, 0);
assert(delimiter == '<' || delimiter == '>' || delimiter == '+');
// El siguiente token tiene que ser el nombre del fichero de la
// redirección entre `start_of_token` y `end_of_token`.
if ('a' != get_token(start_of_str, end_of_str, &start_of_token, &end_of_token))
error("%s: error sintáctico: se esperaba un fichero", __func__);
// Construye el `cmd` para la redirección
switch(delimiter)
{
case '<':
cmd = redrcmd(cmd, start_of_token, end_of_token, O_RDONLY, S_IRWXU, STDIN_FILENO); // permisos 700
break;
case '>':
cmd = redrcmd(cmd, start_of_token, end_of_token, O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU, STDOUT_FILENO);
break;
case '+': // >>
cmd = redrcmd(cmd, start_of_token, end_of_token, O_WRONLY|O_CREAT|O_APPEND, S_IRWXU, STDOUT_FILENO);
break;
}
}
return cmd;
}
// Termina en NULL todas las cadenas de las estructuras `cmd`
struct cmd* null_terminate(struct cmd* cmd)
{
struct execcmd* ecmd;
struct redrcmd* rcmd;
struct pipecmd* pcmd;
struct listcmd* lcmd;
struct backcmd* bcmd;
struct subscmd* scmd;
int i;
if(cmd == 0)
return 0;
switch(cmd->type)
{
case EXEC:
ecmd = (struct execcmd*) cmd;
for(i = 0; ecmd->argv[i]; i++)
*ecmd->eargv[i] = 0;
break;
case REDR:
rcmd = (struct redrcmd*) cmd;
null_terminate(rcmd->cmd);
*rcmd->efile = 0;
break;
case PIPE:
pcmd = (struct pipecmd*) cmd;
null_terminate(pcmd->left);
null_terminate(pcmd->right);
break;
case LIST:
lcmd = (struct listcmd*) cmd;
null_terminate(lcmd->left);
null_terminate(lcmd->right);
break;
case BACK:
bcmd = (struct backcmd*) cmd;
null_terminate(bcmd->cmd);
break;
case SUBS:
scmd = (struct subscmd*) cmd;
null_terminate(scmd->cmd);
break;
case INV:
default:
panic("%s: estructura `cmd` desconocida\n", __func__);
}
return cmd;
}
/******************************************************************************
* Lectura de la línea de órdenes con la biblioteca libreadline
******************************************************************************/
// `get_cmd` muestra un *prompt* y lee lo que el usuario escribe usando la
// biblioteca readline. Ésta permite mantener el historial, utilizar las flechas
// para acceder a las órdenes previas del historial, búsquedas de órdenes, etc.
char* get_cmd()
{
// buscamos el usuario
uid_t user = getuid();
struct passwd* username = getpwuid(user);
if (!username){
perror("getpwuid");
exit(EXIT_FAILURE);
}
char* usuario = username->pw_name;
//printf("%s", usuario);
char path[PATH_MAX];
if (! getcwd(path, PATH_MAX)){
perror("getcwd");
exit(EXIT_FAILURE);
}
//printf("%s", path); //ruta absoluta
char * dir = basename(path);
//printf("%s", dir); // directorio actual
//char* ruta;
//ruta = getwd();
//printf("cwd: %s", ruta);
char prompt[strlen(usuario) + strlen(dir) + 4];
sprintf(prompt, "%s@%s> ", usuario, dir);
// Lee la orden tecleada por el usuario
char * buf = readline(prompt);
// Si el usuario ha escrito una orden, almacenarla en la historia.
if(buf)
add_history(buf);
return buf;
}
/******************************************************************************
* Funciones para la ejecución de la línea de órdenes
******************************************************************************/
void exec_cmd(struct execcmd* ecmd)
{
assert(ecmd->type == EXEC);
if (ecmd->argv[0] == NULL) exit(EXIT_SUCCESS);
execvp(ecmd->argv[0], ecmd->argv);
panic("no se encontró el comando '%s'\n", ecmd->argv[0]);
}
void run_cwd(){
char path[PATH_MAX];
if (!getcwd(path,PATH_MAX)){
perror("getcwd at run_cwd\n");
exit(EXIT_FAILURE);
}
printf("cwd: %s\n", path);
}
void run_cd(struct execcmd* ecmd){
int argc = ecmd->argc;
//char* argv[MAX_ARGS] = ecmd->argv;
optind = 1;
char* path[argc];
int length = 0;
int i;
for (i = optind ; i < argc ; i++){
path[i - 1] = (ecmd->argv[i]);
length++;
}
if (length > 1){
printf("run_cd: Demasiados argumentos\n");
return;
}
// caso de "cd ", vamos al directorio almacenado en la variable de entorno $HOME
if (length == 0){
char* home = getenv("HOME");
char* pwd = getenv("PWD");
//char* oldpwd;
//= getenv("OLDPWD");
//printf("$HOME = %s\n$PWD = %s\n$OLDPWD=%s\n", home, pwd,oldpwd);
setenv("OLDPWD", pwd, 1);
oldpwddefined = 1;
setenv("PWD", home, 1);
chdir(home);
//printf("$HOME = %s\n$PWD = %s\n$OLDPWD=%s\n", getenv("HOME"), getenv("PWD"), getenv("OLDPWD"));
// caso de volvemos al directorio anterior
} else if (length == 1 && *path[0] == '-'){
char* pwd = getenv("PWD");
char* oldpwd = getenv("OLDPWD");
if (oldpwd != NULL && oldpwddefined != 0){
//printf("futuro pwd: %s, oldpwd:%s\n", pwd, oldpwd);
if (chdir(oldpwd)) printf("error\n");
oldpwddefined = 1;
setenv("OLDPWD", pwd, 1);
setenv("PWD", oldpwd, 1);
} else {
printf("run_cd: Variable OLDPWD no definida\n");
return;
}
}
else {
char * destino = *path;
if (chdir(destino)){
printf("run_cd: No existe el directorio '%s'\n", destino);
return;
}
oldpwddefined = 1;
char current[PATH_MAX];
setenv("OLDPWD", getenv("PWD"), 1);
setenv("PWD", getcwd(current, sizeof(current)), 1);
//printf("$HOME = %s\n$PWD = %s\n$OLDPWD=%s\n", getenv("HOME"), getenv("PWD"), getenv("OLDPWD"));
}
}
// mira si una cadena es estrictamente numerica y si lo es devuelve 0, si no lo es devuelve 1
int String_is_a_digit(char* ch){
for (int i = 0; ch[i] != '\0'; i++){
if (! isdigit(ch[i])){
//printf("No es un numero\n");
return 1;
}
}
return 0;
}
void run_psplit(struct execcmd* ecmd){
int opt , flag_l, flag_b, flag_s, flag_p, flag_h , lines, size, bytesfich, procs;
flag_l = flag_b = flag_p =flag_s = flag_h = 0;
int argc = ecmd->argc;
char* argv[argc];
for (int i = 0; i<argc; i++) argv[i] = ecmd->argv[i];
char* ficheros_entrada[argc];
int numero_ficheros_entrada = 0;
optind = 0;
while (( opt = getopt ( ecmd->argc, ecmd->argv , "l:b:p:s:h")) != -1) {
switch (opt)
{
case 'l':
//printf("l flag\n");
flag_l = 1;
if (optarg == NULL){
printf("psplit: invalid number of aruments for -l\n");
return;
} else {
//vemos el numero de lineas en que queremos dividir (parametro obligatorio)
if (String_is_a_digit(optarg)){
printf("invalid number of lines for -l <<%s>>\n", optarg);
return;
}
lines = atoi(optarg);
//printf("%s %d\n",ecmd->argv[i],lines);
//mirar si es un numero valido
if (lines <= 0){
printf("invalid number of lines for -l <<%s>>\n", optarg);
return;
}
//printf("lines %d", lines);
}
break;
case 'b':
flag_b = 1;
//TODO mirar si hay un numero o algo que mirar despues para evitar el core
if (optarg == NULL){
printf("psplit: invalid number of aruments for -b\n");
return;
} else {
if (String_is_a_digit(optarg)){
printf("invalid number of bytes for -b <<%s>>\n",optarg);
return;
}
bytesfich = atoi(optarg);
//mirar si es un numero valido
if (bytesfich <= 0){
printf("invalid number of bytes for -b <<%s>>\n",optarg);
return;
}
}
break;
case 's':
flag_s = 1;
//miramos si hay parametro
//TODO mirar si hay un numero o algo que mirar despues para evitar el core
if (optarg == NULL){
printf("psplit: invalid number of aruments for -s\n");
return;
} else {
if (String_is_a_digit(optarg)){
printf("psplit: Opción -s no válida\n");
return;
}
size = atoi(optarg);
//mirar si es un numero valido
if (size <= 0 || size > BSIZEMAX){
printf("psplit: Opción -s no válida\n");
return;
}
}
break;
case 'p':
flag_p = 1;
if (optarg == NULL){
printf("psplit: invalid number of aruments for -p\n");
return;
} else {
if (String_is_a_digit(optarg)){
printf("psplit: Opción -p no válida\n");
return;
}
procs = atoi(optarg);
//mirar si es un numero valido
if (procs <= 0){
printf("psplit: Opción -p no válida\n");
return;
}
}
break;