Пример #1
0
int fb_init() {
	if(gFbHasInit) return 0;
	gFbInfo = find_fbinfo();
	if (gFbInfo == NULL) {
		printf("Unable to find framebuffer info\n");
		return -1;
	}
	printf("Found framebuffer info at 0x%x\n", gFbInfo);
	printf("Framebuffer dimentions: %dx%d\n", gFbInfo->width, gFbInfo->height);

	fb_setup();
	fb_clear();
    fb_set_loc(0,0);
	fb_display_text(TRUE);

	fb_print_line('=');
	fb_print_center("greenpois0n\n");
	fb_print_center("http://www.greenpois0n.com\n");
	fb_print_line('=');

	cmd_add("fbecho", &fb_cmd, "write characters back to framebuffer");
	cmd_add("fbimg", &fbimg_cmd, "display image on framebuffer");
	gFbHasInit = TRUE;
	return 0;
}
Пример #2
0
void  lwm2m_command_init(void)
{
  cmd_add("lwm2m-client", lwm2m_client_command, "LWM2M Client specific command", CMD_MAN_LWM2M_CLIENT);
  cmd_alias_add("lwm2m-client-test-setup", "lwm2m-client setup --endpoint lwm2m-endpoint --type test --lifetime 3600");
  cmd_alias_add("lwm2m-client-test-device", "lwm2m-client device --manufacturer ARM --model_number 2015 --serial_number 12345");
  cmd_alias_add("lwm2m-client-test-bootstrap-object", "lwm2m-client bootstrap_object --address coap://10.45.3.10:5693");
  cmd_alias_add("lwm2m-client-test-register-object", "lwm2m-client register_object --address coap://10.45.3.10:5683");
  cmd_alias_add("lwm2m-client-test-object", "lwm2m-client object --name 10 --object_observable 1 --object_instance_observable 1 --object_operation 3 --object_instance_operation 3");
  cmd_alias_add("lwm2m-client-test-dynamic_resource", "lwm2m-client dynamic_resource --name 1 --resource_operation 3 --observable 0");
  cmd_alias_add("lwm2m-client-test-secure-register-object", "lwm2m-client register_object --address coap://10.45.3.10:5684 --secure 1");
  cmd_add("exit", exit_command, "exit command", EXIT_MANUAL);
}
Пример #3
0
void config_init()
{
  for (int i = 0; i < LENGTH(cmdtable); i++)
    cmd_add(&cmdtable[i]);
  for (int i = 0; i < LENGTH(compl_cmds); i++)
    compl_add_context(compl_cmds[i]);
}
Пример #4
0
int main(int argc, char *argv[])
{
    if ((argc < 3) || (strcmp(argv[1], "--help") == 0))
        help();

    f = open("/dev/rtnet", O_RDWR);

    if (f < 0) {
        perror("/dev/rtnet");
        exit(1);
    }

    memset(&cmd, 0, sizeof(cmd));
    strncpy(cmd.head.if_name, argv[1], IFNAMSIZ);

    if (strcmp(argv[2], "server") == 0)
        cmd_server(argc, argv);
    if (strcmp(argv[2], "add") == 0)
        cmd_add(argc, argv);
    if (strcmp(argv[2], "del") == 0)
        cmd_del(argc, argv);
    if (strcmp(argv[2], "wait") == 0)
        cmd_wait(argc, argv);

    if (strcmp(argv[2], "client") == 0)
        cmd_client(argc, argv);
    if (strcmp(argv[2], "announce") == 0)
        cmd_announce(argc, argv);

    help();

    return 0;
}
Пример #5
0
int fb_init() {
	if(gFbHasInit) return 0;
	fb_setup();
	fb_clear();
    fb_set_loc(0,0);
	fb_display_text(TRUE);

	fb_print("=====================================================");
#ifdef S5L8930X
	fb_print("=====================================================");
	fb_print("                          ");
#endif

	fb_print("                 Haifisch - AESPayload               ");

#ifdef S5L8930X
	fb_print("                                                     ");
#endif

	fb_print("                  http://haifisch.me                 ");

#ifdef S5L8930X
	fb_print("                           ");
	fb_print("=====================================================");
#endif
	fb_print("=====================================================");
	cmd_add("fbecho", &fb_cmd, "write characters back to framebuffer");
	gFbHasInit = TRUE;
	return 0;
}
Пример #6
0
void cmd_socket_init(void)
{
    cmd_add("socket", cmd_socket, "socket", MAN_SOCKET);
    cmd_alias_add("socket help", "socket -h");
    cmd_alias_add("socket --help", "socket -h");
    cmd_alias_add("ping server start", "socket echo-server new start");
}
Пример #7
0
int main(int argc, char **argv)
{
    cmd_init();
    cmd_add("ls", 5, 0, "ls_file usage", "ls_file from dir", do_ls);

    cmd_loop();

    return 0;
}
Пример #8
0
static void _shell_cmd_init()
{
    int i;
    int cmd_num;
    cmd_num = N_ELEMENTS(_G_shell_origin_cmds);

    for (i = 0; i < cmd_num; i++) {
        cmd_add(&_G_shell_origin_cmds[i]);
    }
}
Пример #9
0
static void highlight_init() {
    /* Let everyone know we're here. */
    scr_log_print(LPRINT_NORMAL, "highlight: plugin enabled.");

    /* Register our message handler so we can start processing incoming messages. */
    globals.hook = hk_add_handler(highlight_process_message, HOOK_PRE_MESSAGE_IN, G_PRIORITY_DEFAULT, NULL);

    /* Add our commands for highlighting. */
    cmd_add("highlight", "", 0, 0, highlight_command, NULL);
}
Пример #10
0
int nvram_init() {
	gNvramList = find_nvram_list();
	if(gNvramList == NULL) {
		puts("Unable to find gNvramList\n");
	} else {
		printf("Found gNvramList at 0x%x\n", gNvramList);
		cmd_add("nvram", &nvram_cmd, "view and modify nvram variables");
	}
	return 0;
}
Пример #11
0
void yaffs_cmd_init()
{
    int i;
    int cmd_num;
    cmd_num = N_ELEMENTS(_G_yaffs_cmds);

    for (i = 0; i < cmd_num; i++) {
        cmd_add(&_G_yaffs_cmds[i]);
    }
}
Пример #12
0
void do_line(char *ptr){/*process one line of input*/
	int cmd;
	tok_ptr = ptr;
	while((cmd=get_token())>0){
		switch(cmd){/*one case for each command*/
			case TOK_ADD:
				cmd_add();
				break;
		}
	}
}
Пример #13
0
void do_line(char *ptr)
{
	int cmd;
	tok_ptr = NULL;
	while((cmd=get_token())>0)
	{
		switch(cmd){
		case TOK_ADD:
			cmd_add();
			break;
		} 
	}
}
Пример #14
0
/* Run the database program interactively. Will repeatedly prompt for a command. */
void run_interactive() {
    printf("Welcome to FlatDB.\n");
    printf("Copyright 2013 Oracle Corporation\n");
    printf("\"We synergize your paradigms.\"\n");
    printf("\n");
    
    char path[255];
    printf("Enter the location of the database file. It does not need to exist; a blank one will be created for you if necessary.\n> ");
    fgets(path, 255, stdin);
    
    char command = 0;
    
    do {
        printf("\n");
        printf("Choose a command:\n");
        printf("    _a_dd an entry\n");
        printf("    _f_ind an ID\n");
        printf("    _r_remove an entry\n");
        printf("    _p_rint the database\n");
        printf("    _q_uit the application\n");
        printf("> ");
        
        command = fgetc(stdin);
        getchar();
        
        printf("\n");
        
        switch (command) {
            case 'a':
                cmd_add(path);
                break;
                
            case 'f':
                cmd_get(path);
                break;
                
            case 'r':
                cmd_remove(path);
                break;
                
            case 'p':
                cmd_print(path);
                break;
                
            default:
                break;
        }
    } while (command != 'q');
    
    printf("Thank you. Goodbye.\n");
}
Пример #15
0
void do_line(char *ptr)
{
    int cmd;

    tok_ptr = ptr;
    while ((cmd = get_token()) > 0)
    {
        switch (cmd)
        case TOK_ADD:
            cmd_add();
            printf("cmd add complete\n"); //this will not be printed out
            break;
    }
}
Пример #16
0
int cmd_insert (int argc, char ** argv, struct mpd_connection *conn )
{
	int ret;
	struct mpd_status *status = getStatus(conn);

	const int from = mpd_status_get_queue_length(status);

	ret = cmd_add(argc, argv, conn);
	const int cur_pos = mpd_status_get_song_pos(status);
	mpd_status_free(status);
	if (ret != 0) {
		return ret;
	}
	return mpd_run_move_range(conn, from, from+argc,
		cur_pos+1);
}
Пример #17
0
int kernel_init() {
	/* TODO: Detect this */
	gKernelPhyMem = SELF_KERNEL_PHYMEM;

	gBootArgs = find_kernel_bootargs();
	if(gBootArgs == NULL) {
		puts("Unable to find gBootArgs\n");
	} else {
		printf("Found gBootArgs at 0x%x\n", gBootArgs);
	}
	kernel_load = find_kernel_load();
	if(kernel_load == NULL) {
		puts("Unable to find kernel_load function\n");
	} else {
		printf("Found kernel_load at 0x%x\n", kernel_load);
	}
	cmd_add("kernel", &kernel_cmd, "operations for filesystem kernel");
	return 0;
}
Пример #18
0
int cmd_init() {
    if(gCmdHasInit) return 0;

    int i = 0;
    gCmdCount = 0;
    gCmdHasInit = TRUE;
    gCmdCommands = (CmdInfo**) (LOADADDR + 0x01800000);

    gCmdListBegin = find_cmd_list_begin();
    if(gCmdListBegin == NULL) {
        puts("Unable to find gCmdListBegin\n");
    } else {
        printf("Found gCmdListBegin at 0x%x\n", gCmdListBegin);
    }

    gCmdListEnd = find_cmd_list_end();
    if(gCmdListEnd == NULL) {
        puts("Unable to find gCmdListEnd\n");
    } else {
        printf("Found gCmdListEnd at 0x%x\n", gCmdListEnd);
    }

    // add all built in commands to our private commands
    if(gCmdListBegin && gCmdListEnd) {
        CmdInfo** current = (CmdInfo**) gCmdListBegin;
        for (i = 0; &current[i] < (CmdInfo**) gCmdListEnd; i++) {
            cmd_add(current[i]->name, current[i]->handler, current[i]->description);
        }
    }
    // add our essential commands
    cmd_add("help", &cmd_help, "display all available commands");
    cmd_add("echo", &cmd_echo, "write characters back to screen");
    cmd_add("hexdump", &cmd_hexdump, "dump section of memory to screen");
    cmd_add("mw", &cmd_mw, "write value to specified address");
    cmd_add("md", &cmd_md, "display value at specified address");
    cmd_add("call", &cmd_call, "calls a subroutine passing args to it");
    //cmd_add("rdboot", &cmd_rdboot, "patch and boot kernel with ramdisk");
    //cmd_add("test", &cmd_test, "test finding functions offsets");

    jump_to = find_jump_to();
    if(jump_to == NULL) {
        puts("Unable to find jump_to\n");
    } else {
        printf("Found jump_to at 0x%x\n", jump_to);
        cmd_add("jump", &cmd_jump, "shutdown current image and jump into another");
    }

    fsboot = find_fsboot();
    if(fsboot == NULL) {
        puts("Unable to find fsboot\n");
    } else {
        printf("Found fsboot at 0x%x\n", fsboot);
        cmd_add("fsboot", &cmd_fsboot, "patch and boot kernel from filesystem");
    }

    load_ramdisk = find_load_ramdisk();
    if(load_ramdisk == NULL) {
        puts("Unable to find load_ramdisk\n");
    } else {
        printf("Found load_ramdisk at 0x%x\n", load_ramdisk);
        cmd_add("ramdisk", &cmd_ramdisk, "create a ramdisk from the specified address");
    }

    return 0;
}
Пример #19
0
int main(int argc, const char *argv[]) {
	io_func* io;
	Volume* volume;
	
	TestByteOrder();
	
	if(argc < 3) {
		printf("usage: %s <image-file> <ls|cat|mv|symlink|mkdir|add|rm|chmod|extract|extractall|rmall|addall|grow|getattr|debug> <arguments>\n", argv[0]);
		return 0;
	}
	
	io = openFlatFile(argv[1]);
	if(io == NULL) {
		fprintf(stderr, "error: Cannot open image-file.\n");
		return 1;
	}
	
	volume = openVolume(io); 
	if(volume == NULL) {
		fprintf(stderr, "error: Cannot open volume.\n");
		CLOSE(io);
		return 1;
	}
	
	if(argc > 1) {
		if(strcmp(argv[2], "ls") == 0) {
			cmd_ls(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "cat") == 0) {
			cmd_cat(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "mv") == 0) {
			cmd_mv(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "symlink") == 0) {
			cmd_symlink(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "mkdir") == 0) {
			cmd_mkdir(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "add") == 0) {
			cmd_add(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "rm") == 0) {
			cmd_rm(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "chmod") == 0) {
			cmd_chmod(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "extract") == 0) {
			cmd_extract(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "extractall") == 0) {
			cmd_extractall(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "rmall") == 0) {
			cmd_rmall(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "addall") == 0) {
			cmd_addall(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "grow") == 0) {
			cmd_grow(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "getattr") == 0) {
			cmd_getattr(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "debug") == 0) {
			if(argc > 3 && strcmp(argv[3], "verbose") == 0) {
				debugBTree(volume->catalogTree, TRUE);
			} else {
				debugBTree(volume->catalogTree, FALSE);
			}
		}
	}
	
	closeVolume(volume);
	CLOSE(io);
	
	return 0;
}
Пример #20
0
int main (int argc, char *argv[]) {
    // Child's CMD line
    int m = sysconf(_SC_ARG_MAX);           // Maximum CMD line length
    char *cmd;                              // Store child's CMD line
    cmd = (char *) calloc(m, sizeof(char));

    // Child's parameters
    int *child_delay = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    *child_delay = 0;                       // Delay before starting (shared between parent and child)
    int child_pid = -1;                     // PID after the fork()
    int child_status = -1;                  // Used during waitpid()
    char *child_file = NULL;                // Binary file

    // Telnet server
    int ts_port = -1;                       // TCP (console) and UDP (serial converter) port
    int ts_socket = -1;                     // Telnet server socket
    char child_output = '\0';               // Store single char from child
    char client_input = '\0';               // Store single char from client
    char *xtitle = "Terminal Server";       // Title for telnet clients

    // Select parameters
    int *infd = calloc(2, sizeof(int));     // Array of integers [0] is for reading, [1] is for writing
    int *outfd = calloc(2, sizeof(int));    // Array of integers [0] is for reading, [1] is for writing
    int active_fd = -1;                     // Contains current active FD
    fd_set active_fd_set;                   // Contains active FD using in select()
    FD_ZERO(&active_fd_set);
    fd_set read_fd_set;                     // Contains FD selected in current loop
    FD_ZERO(&read_fd_set);

    // Wrapper parameters
    int child_afsocket = -1;                // Store AF_UNIX child socket
    int *eth_socket = calloc(64, sizeof(int));  // Store FD of ethernet intefaces
    int *ser_remoteid = calloc(64, sizeof(int));// Store Remote Device ID (used for UDP communication)
    int *ser_remoteif = calloc(64, sizeof(int));// Store Remote Interface ID (used for UDP communication)
    int *ser_socket = calloc(64, sizeof(int));  // Store FD of serial intefaces
    int udpserver_socket = -1;              // UDP socket for serial communications
    int wrapper_afsocket = -1;              // Store AF_UNIX wrapper socket

    // Other parameters
    int af_ready = 0;                       // 1 = AF_UNIX files are configured (needed if IOL is delayed)
    int i = -1;                             // Counter
    int j = -1;                             // Counter
    int opt = NULL;                         // Store CMD options
    int rc = -1;                            // Generic return code
    char *tmp = NULL;                       // Generic char string
    struct sigaction sa;                    // Manage signals (SIGHUP, SIGTERM...)

    setpgrp();

    // Check for iourc file
    tmp = (char *) malloc(m * sizeof(char));
    sprintf(tmp, "iourc");
    if (is_file(tmp) != 0) {
        printf("ERR: file '%s' does not exist.\n", tmp);
        exit(1);
    }
    free(tmp);

    // Adding options to child's CMD line
    while ((opt = getopt(argc, argv, ":vT:D:d:t:F:e:s:l:")) != -1) {
        switch (opt) {
            default:
                usage(argv[0]);
                exit(1);
            // Begin standard parameters
            case 'v':
                version();
                exit(0);
            case 'T':
                // Mandatory: Tenant ID
                tenant_id = atoi(optarg);
                if (tenant_id < 0) {
                    printf("ERR: tenant_id must be integer.\n");
                    exit(1);
                }
                break;
            case 'D':
                // Mandatory: Device ID
                device_id = atoi(optarg);
                if (tenant_id < 0) {
                    printf("ERR: device_id must be integer.\n");
                    exit(1);
                }
                break;
            case 'F':
                child_file = optarg;
                if (is_file(child_file) != 0) {
                    printf("ERR: file '%s' does not exist.\n", child_file);
                    exit(1);
                }
                break;
            case 'd':
                // Optional: child's startup delay (default 0)
                *child_delay = atoi(optarg);
                if (*child_delay < 0) {
                    printf("ERR: delay must be integer.\n");
                    exit(1);
                }
                break;
            case 't':
                // Optional: telnet window title (default "Terminal Server")
                xtitle = optarg;
                break;
            // End standard parameters
            // Optional: number of Ethernet progroups (default: 2)
            case 'e':
                child_eth = atoi(optarg);
                if (child_eth < 0) {
                    printf("ERR: Ethernet portgroup must be integer.\n");
                    exit(1);
                }
                break;
            // Optional: number of Serial progroups (default: 2)
            case 's':
                child_ser = atoi(optarg);
                if (child_ser < 0) {
                    printf("ERR: Serial portgroup must be numeric.\n");
                    exit(1);
                }
                break;
            // Optional: Serial link end-point (no default)
            case 'l':
                if (udpserver_socket == -1 && tenant_id != -1 && device_id != -1) {
                    // First Serial2UDP definition, must listen()
                    if ((rc = serial2udp_listen(32768 + 128 * tenant_id + device_id, &udpserver_socket)) != 0) {
                        printf("%u:%u ERR: failed to open UDP socket (%i).\n", tenant_id, device_id, rc);
                        exit(1);
                    }
                    // Now add serial end-point
                    if ((rc = serial2udp_add(ser_socket, ser_remoteid, ser_remoteif, optarg)) != 0) {
                        printf("%u:%u ERR: failed to add serial end-point (%i).\n", tenant_id, device_id, rc);
                        exit(1);
                    }
                } else if (udpserver_socket > 0) {
                    // Serial2UDP wrapper already started, add serial end-point
                    if ((rc = serial2udp_add(ser_socket, ser_remoteid, ser_remoteif, optarg)) != 0) {
                        printf("%u:%u ERR: failed to add serial end-point (%i).\n", tenant_id, device_id, rc);
                        exit(1);
                    }
                } else {
                    printf("ERR: flag '-l' must be after '-T' and '-D'.\n");
                    exit(1);
                }
                break;
        }
    }

    // Checking if tenant_id is set
    if (tenant_id < 0) {
        printf("ERR: tenant ID not set.\n");
        exit(1);
    }

    // Checking if device_id is set
    if (device_id < 0) {
        printf("ERR: device ID not set.\n");
        exit(1);
    }

    // Checking if child_file is set
    if (child_file == NULL) {
        printf("%u:%u ERR: subprocess executable not set.\n", tenant_id, device_id);
        exit(1);
    }

    // Checking total interfaces
    if (child_eth + child_ser > 16) {
        printf("%u:%u ERR: Ethernet + Serial portgroups must lower equal than 16.\n", tenant_id, device_id);
        exit(1);
    }

    // Building the CMD line
    cmd_add(&cmd, "LD_LIBRARY_PATH=/opt/unetlab/addons/iol/lib ");
    cmd_add(&cmd, child_file);

    // Adding interfaces
    tmp = (char *) malloc(m * sizeof(char));
    sprintf(tmp, " -e %i -s %i", child_eth, child_ser);
    cmd_add(&cmd, tmp);
    free(tmp);

    // Adding parameters after "--"
    j = 0;
    for (i = 1; i < argc; i++) {
        if (j == 1) {
            // Adding parameter given after "--"
            cmd_add(&cmd, " ");
            cmd_add(&cmd, argv[i]);
        }
        if (strcmp(argv[i], "--") == 0) {
            // Found "--"
            j = 1;
        }
    }

    // Adding device_id as last
    tmp = (char *) malloc(m * sizeof(char));
    sprintf(tmp, "%i", device_id);
    cmd_add(&cmd, " ");
    cmd_add(&cmd, tmp);
    free(tmp);

    // Creating NETMAP
    if ((rc = mk_netmap()) != 0) {
        printf("%u:%u ERR: failed to create NETMAP file (%i).\n", tenant_id, device_id, rc);
        exit(1);
    }

    // Creating PIPEs for select()
    if ((pipe(infd)) < 0 || pipe(outfd) < 0) {
         printf("%u:%u ERR: failed to create PIPEs (%s).\n", tenant_id, device_id, strerror(errno));
         exit(1);
    }

    // Telnet listen
    ts_port = 32768 + 128 * tenant_id + device_id;
    tsclients_socket[0] = 0;
    if ((rc = ts_listen(ts_port, &ts_socket)) != 0) {
        printf("%u:%u ERR: failed to open TCP socket (%i).\n", tenant_id, device_id, rc);
        exit(1);
    }

    // Creating TAP interfaces
    if ((rc = mk_tap(child_eth, eth_socket)) != 0) {
        printf("%u:%u ERR: failed to create TAP interfaces (%i).\n", tenant_id, device_id, rc);
        kill(0, SIGTERM);
        exit(1);
    }

    // Forking
    if ((rc = fork()) == 0) {
        // Child: starting subprocess
        if (DEBUG > 0) printf("DEBUG: starting child (%s).\n", cmd);
        if (*child_delay > 0) {
            // Delay is set, waiting
            for (; *child_delay > 0;) {
                rc = write(outfd[1], ".", 1);
                *child_delay = *child_delay - 1;
                sleep(1);
            }
            rc = write(outfd[1], "\n", 1);
        }
        close(STDIN_FILENO);            // Closing child's stdin
        close(STDOUT_FILENO);           // Closing child's stdout
        dup2(infd[0], STDIN_FILENO);    // Linking stdin to PIPE
        dup2(outfd[1], STDOUT_FILENO);  // Linking stdout to PIPE
        dup2(outfd[1], STDERR_FILENO);  // Redirect child's stderr to child's stdout
        close(infd[0]);
        close(infd[1]);
        close(outfd[0]);
        close(outfd[1]);
        // Start process
        rc = cmd_start(cmd);
        // Subprocess terminated, killing the parent
        printf("%u:%u ERR: child terminated (%i).\n", tenant_id, device_id, rc);
    } else if (rc > 0) {
        // Parent
        close(infd[0]);                     // Used by the child
        close(outfd[1]);                    // Used by the child

        // Handling Signals
        signal(SIGPIPE,SIG_IGN);            // Ignoring SIGPIPE when a client terminates
        sa.sa_handler = &signal_handler;    // Setup the sighub handler
        sa.sa_flags = SA_RESTART;           // Restart the system call, if at all possible
        sigemptyset(&sa.sa_mask);           // Signals blocked during the execution of the handler
        sigaddset(&sa.sa_mask, SIGHUP);     // Signal 1
        sigaddset(&sa.sa_mask, SIGINT);     // Signal 2
        sigaddset(&sa.sa_mask, SIGTERM);    // Signal 15
        sigfillset(&sa.sa_mask);

        // Intercept SIGHUP, SIGINT, SIGUSR1 and SIGTERM
        if (sigaction(SIGHUP, &sa, NULL) == -1) {
            printf("%u:%u ERR: cannot handle SIGHUP (%s).\n", tenant_id, device_id, strerror(errno));
        }
        if (sigaction(SIGINT, &sa, NULL) == -1) {
            printf("%u:%u ERR: cannot handle SIGINT (%s).\n", tenant_id, device_id, strerror(errno));
        }
        if (sigaction(SIGTERM, &sa, NULL) == -1) {
            printf("%u:%u ERR: cannot handle SIGTERM (%s).\n", tenant_id, device_id, strerror(errno));
        }

        // Preparing select()
        FD_ZERO(&active_fd_set);
        FD_ZERO(&read_fd_set);
        if (DEBUG > 0) printf("DEBUG: adding subprocess stdout descriptor (%i).\n", outfd[0]);
        FD_SET(outfd[0], &active_fd_set);         // Adding subprocess stdout
        if (DEBUG > 0) printf("DEBUG: adding telnet socket descriptor (%i).\n", ts_socket);
        FD_SET(ts_socket, &active_fd_set);        // Adding telnet socket
        if (udpserver_socket > 0) {
            if (DEBUG > 0) printf("DEBUG: adding UDP socket descriptor (%i).\n", udpserver_socket);
            FD_SET(udpserver_socket, &active_fd_set); // Adding UDP socket
        }

        // Adding TAP interfaces for select()
        for (i = 0; i <= 63; i++) {
            if (eth_socket[i] > 0) {
                if (DEBUG > 0) printf("DEBUG: adding TAP interface descriptor (%i).\n", eth_socket[i]);
                FD_SET(eth_socket[i], &active_fd_set);
            }
        }

        // While subprocess is running, check IO from subprocess, telnet clients, socket and network
        while (waitpid(child_pid, &child_status, WNOHANG|WUNTRACED) == 0) {
            // Creating AF communication from child
            if (af_ready == 0 && *child_delay == 0) {
                // wait 3 seconds for AF_UNIX
                sleep(3);
                if ((rc = mk_afsocket(&wrapper_afsocket, &child_afsocket)) != 0) {;
                    printf("%u:%u ERR: failed to create AF_UNIX socket file (%i).\n", tenant_id, device_id, rc);
                    kill(0, SIGTERM);
                    break;
                }
                af_ready = 1;
                if (DEBUG > 0) printf("DEBUG: adding wrapper socket descriptor (%i).\n", wrapper_afsocket);
                FD_SET(wrapper_afsocket, &active_fd_set);   // Adding subprocess AF_UNIX socket
            }

            // Check if select() is valid
            read_fd_set = active_fd_set;
            if ((active_fd = select(FD_SETSIZE, &read_fd_set, NULL, NULL, NULL)) <= 0) {
                printf("%u:%u ERR: failed to select().\n", tenant_id, device_id);
                kill(0, SIGTERM);
                break;
            }
            if (DEBUG > 2) printf("DEBUG: data from select descriptor (%i).\n", active_fd);

            // Check if output from child
            if (FD_ISSET(outfd[0], &read_fd_set)) {
                if (read(outfd[0], &child_output, 1) <= 0) {
                    printf("%u:%u ERR: error while reading data from the subprocess, killing it.\n", tenant_id, device_id);
                    kill(0, SIGTERM);
                    break;
                }
                // Writing to all telnet clients
                ts_broadcast(child_output, &active_fd_set, tsclients_socket);
            }

            // Check if new client is coming
            if (FD_ISSET(ts_socket, &read_fd_set)) {
                if ((rc = ts_accept(&active_fd_set, ts_socket, xtitle, tsclients_socket,1)) != 0) {
                    printf("%u:%u ERR: failed to accept a new client (%i).\n", tenant_id, device_id, rc);
                }
            }

            // Check for output from all telnet clients
            if (ts_receive(&client_input, &read_fd_set, &active_fd_set, tsclients_socket) == 0) {
                // Write to child
                rc = write(infd[1], &client_input, 1);
                if (rc < 0) {
                    printf("%u:%u ERR: error writing to the subprocess, closing.\n", tenant_id, device_id);
                    kill(0, SIGTERM);
                    break;
                }
            }

            // If AF, UDP and TAP sockets are configured, check for packets
            if (af_ready == 1) {
                // Check for packets from subprocess
                if (FD_ISSET(wrapper_afsocket, &read_fd_set)) {
                    if ((rc = packet_af(wrapper_afsocket, eth_socket, ser_socket, ser_remoteid, ser_remoteif)) != 0) {
                        printf("%u:%u ERR: error forwarding packet from AF_UNIX socket to TAP/UDP (%i).\n", tenant_id, device_id, rc);
                        kill(0, SIGTERM);
                        break;
                    }
                }

                // Check for packets from TAP interfaces
                for (i = 0; i <= 63; i++) {
                    if (eth_socket[i] > 0 && FD_ISSET(eth_socket[i], &read_fd_set)) {
                        if ((rc = packet_tap(eth_socket[i], child_afsocket, i)) != 0) {
                            if (rc == 3) {
                              af_ready = 0;
                              printf("Failed to forward TAP => AF_UNIX. Will try to recreate it later...\n");
                            } else {
                              printf("%u:%u ERR: error forwarding packet from TAP to AF_UNIX socket (%i).\n", tenant_id, device_id, rc);
                              kill(0, SIGTERM);
                              break;
                            }
                        }
                    }
                }

                // Check for incoming serial (UDP) packets
                if (udpserver_socket > 0) {
                    if (FD_ISSET(udpserver_socket, &read_fd_set)) {
                        if ((rc = packet_udp(udpserver_socket, child_afsocket)) != 0) {
                            if (rc == 3) {
                                af_ready = 0;
                                printf("Failed to forward UDP => AF_UNIX. Will try to recreate it later...\n");
                            } else {
                                printf("%u:%u ERR: error forwarding packet from UDP to AF_UNIX (%i).\n", tenant_id, device_id, rc);
                                kill(0, SIGTERM);
                                break;
                            }
                        }
                    }
                }
            }

            // We should not have other active dscriptor
        }

        // Child is no more running
        printf("%u:%u ERR: child is no more running.\n", tenant_id, device_id);
    } else {
        printf("%u:%u ERR: failed to fork.\n", tenant_id, device_id);
        exit(1);
    }
    close(ts_socket);
    close(wrapper_afsocket);
    exit(0);
}
Пример #21
0
int main(int argc, char **argv) {

        char *cmd;

        if (setlocale(LC_ALL, "") == NULL) {
                perror("setlocale");
        }

        if (argc < 3) {
                LOGERROR(CLI_USAGE_FMT, argv[0]);
                exit(EXIT_FAILURE);
        }

        cmd = argv[1];

        if (strcmp(cmd, "add") == 0) {
                if (cli_add(argc - 2, &argv[2]) != 0) {
                        LOGERROR("TLV addition failed.");
                        return EXIT_FAILURE;
                }
        } else if (strcmp(cmd, "extract") == 0) {
                if (cli_extract(argc - 2, &argv[2]) == -1) {
                        LOGERROR("TLV extraction failed.");
                        return EXIT_FAILURE;
                }
        } else if (strcmp(cmd, "dump") == 0) {
                if (cli_dump_dz(argc - 2, &argv[2]) == -1) {
                        LOGERROR("Dazibao dumping failed.");
                        return EXIT_FAILURE;
                }
        } else if (strcmp(cmd, "compact") == 0) {
                if (cli_compact_dz(argc - 2, &argv[2]) == -1) {
                        LOGERROR("Dazibao dumping failed.");
                        return EXIT_FAILURE;
                }
        } else if (strcmp(cmd, "rm") == 0) {
                if (cli_rm_tlv(argc - 2, &argv[2]) == -1) {
                        LOGERROR("Failed removing TLV.");
                        return EXIT_FAILURE;
                }
        } else if (strcmp(cmd, "create") == 0) {
                if (cli_create_dz(argc - 2, &argv[2]) == -1) {
                        LOGERROR("Failed creating dazibao.");
                        return EXIT_FAILURE;
                }
        } else if (!strcmp(cmd, "alt-add")) {
                if (cmd_add(argc - 2, &argv[2], argv[argc - 1]) != 0) {
                        LOGERROR("TLV addition failed.");
                        return EXIT_FAILURE;
                }
        } else if (!strcmp(argv[2], "alt-extract")) {
                if (cmd_extract(argc - 2, &argv[2], argv[argc - 1]) != 0) {
                        LOGERROR("Extraction failed");
                        return EXIT_FAILURE;
                }
        }  else {
                LOGERROR("%s is not a valid command.", cmd);
                return EXIT_FAILURE;
        }
        return EXIT_SUCCESS;
}
Пример #22
0
void handle_client ( CLIENT client ) {
	int num[1];
	PACKAGE outPackage, inPackage;

	signal(SIGPIPE,SIG_IGN);	/* instead of handling the signal, we handle write() error */

	errno = 0;
	read(client.fd,(void *)&inPackage,COM_SIZE);
	if (errno != EWOULDBLOCK){
		if( (errno == EAGAIN) || (errno == ENOTCONN) || (errno == ECONNRESET) || (errno == ETIMEDOUT) ){
			close(client.fd);
			remove_client(client.fd);
		}

/* DEMO */
		/*sscanf(inPackage.num,"%X", (unsigned int *) num);
		fprintf(stdout, "%c\t%d\n", inPackage.msg, *num);*/
/* DEMO */

		switch(inPackage.msg){
			case 'D':
					sscanf(inPackage.num,"%X", (unsigned int *) num);
					outPackage = cmd_D(num,client.stack_desc,outPackage);
					break;
			case '+':
					outPackage = cmd_add(client.stack_desc,outPackage);
					break;
			case '-':
					outPackage = cmd_sub(client.stack_desc,outPackage);
					break;
			case '*':
					outPackage = cmd_mult(client.stack_desc,outPackage);
					break;
			case '/':
					outPackage = cmd_div(client.stack_desc,outPackage);
					break;
			case '%':
					outPackage = cmd_reminder(client.stack_desc,outPackage);
					break;
			case 'R':
					outPackage = cmd_R(client.stack_desc,outPackage);
					break;
			case 'T':
					outPackage = cmd_T(client.stack_desc,outPackage);
					break;
			case 'P':
					outPackage = mountResponsePackage('V', client.stack_desc->count, outPackage);
					break;
			case 'I':
					resetStack(client.stack_desc);
					outPackage = mountResponsePackage('V',OK,outPackage);
					break;
			case 'K':
					close(client.fd);
					remove_client(client.fd);
					return;		/* nothing else to do */
			default:
					outPackage = mountResponsePackage('E',BAD_CMD,outPackage);	/* bad command */
		}

		errno = 0;
		write(client.fd,(void *)&outPackage,COM_SIZE);
		if( (errno == EPIPE) || (errno == EAGAIN) || (errno == ECONNRESET) ){
			close(client.fd);
			remove_client(client.fd);
		}
	}
}
Пример #23
0
int main (int argc, char *argv[]) {
    setpgrp();  // Become the leader of its group.
    // Child's CMD line
    int m = sysconf(_SC_ARG_MAX);           // Maximum CMD line length
    char *cmd;                              // Store child's CMD line
    cmd = (char *) calloc(m, sizeof(char));

    // Child's parameters
    char *child_file = NULL;                // Binary file
    int child_pid = -1;                     // PID after the fork()
    int child_status = -1;                  // Used during waitpid()

    // Telnet server
    int ts_socket = -1;                     // Telnet server socket
    int ts_port = -1;                       // TCP (console) and UDP (serial converter) port
    char child_output = '\0';               // Store single char from child
    unsigned char client_input = '\0';		// Store single char from client
    char *xtitle = "Terminal Server";       // Title for telnet clients

    // Select parameters
    int *infd = calloc(2, sizeof(int));     // Array of integers [0] is for reading, [1] is for writing
    int *outfd = calloc(2, sizeof(int));    // Array of integers [0] is for reading, [1] is for writing
    fd_set active_fd_set;                   // Contains active FD using in select()
    FD_ZERO(&active_fd_set);
    fd_set read_fd_set;                     // Contains FD selected in current loop
    FD_ZERO(&read_fd_set);

    // Other parameters
    int i = -1;                             // Counter
    int j = -1;                             // Counter
    int opt = NULL;                         // Store CMD options
    int rc = -1;                            // Generic return code
    struct sigaction sa;                    // Manage signals (SIGHUP, SIGTERM...)

    // Parsing options
    while ((opt = getopt(argc, argv, ":vT:D:t:F:")) != -1) {
        switch (opt) {
            default:
                usage(argv[0]);
                exit(1);
            // Begin standard parameters
            case 'v':
                printf("%s\n", VERSION);
                exit(0);
            case 'T':
                // Mandatory: Tenant ID
                tenant_id = atoi(optarg);
                if (tenant_id < 0) {
                    UNLLog(LLERROR,"Tenant_id must be integer.\n");
                    exit(1);
                }
                UNLLog(LLINFO, "Tennant_id = %i\n", tenant_id);
                break;
            case 'D':
                // Mandatory: Device ID
                device_id = atoi(optarg);
                if (device_id < 0) {
                    UNLLog(LLERROR,"Device_id must be integer.\n");
                    exit(1);
                }
                UNLLog(LLINFO, "Device_id = %i\n", device_id);
                break;
            case 'F':
                // Mandatory: subprocess executable
                child_file = optarg;
                if (is_file(child_file) != 0) {
                    UNLLog(LLERROR,"File '%s' does not exist.\n", child_file);
                    exit(1);
                }
                break;
            case 't':
                // Optional: telnet window title (default "Terminal Server")
                xtitle = optarg;
                break;
        }
    }

    // Checking if tenant_id is set
    if (tenant_id < 0) {
        UNLLog(LLERROR, "Tenant ID not set.\n");
        exit(1);
    }

    // Checking if device_id is set
    if (device_id < 0) {
        UNLLog(LLERROR, "Device ID not set.\n");
        exit(1);
    }

    // Checking if child_file is set
    if (child_file == NULL) {
        UNLLog(LLERROR, "Subprocess executable not set.\n");
        exit(1);
    }

    // Building the CMD line
    cmd_add(&cmd, child_file);

    // Adding parameters after "--"
    j = 0;
    for (i = 1; i < argc; i++) {
        if (j == 1) {
            // Adding parameter given after "--"
            cmd_add(&cmd, " ");
            cmd_add(&cmd, argv[i]);
        }
        if (strcmp(argv[i], "--") == 0) {
            // Found "--"
            j = 1;
        }
    }

    // Creating PIPEs for select()
    if ((pipe(infd)) < 0 || pipe(outfd) < 0) {
         UNLLog(LLERROR, "Failed to create PIPEs (%s).\n", strerror(errno));
         exit(1);
    }

    // Telnet listen
	ts_port = 32768 + 128 * tenant_id + device_id;
	tsclients_socket[0] = 0;
	if ((rc = ts_listen(ts_port, &ts_socket)) != 0) {
		UNLLog(LLERROR, "Failed to open TCP socket (%i).\n", rc);
		exit(1);
	}

    // Forking
    if ((rc = fork()) == 0) {
        // Child: stating subprocess
        UNLLog(LLINFO, "Starting child (%s).\n", cmd);
        close(STDIN_FILENO);            // Closing child's stdin
        close(STDOUT_FILENO);           // Closing child's stdout
        dup2(infd[0], STDIN_FILENO);    // Linking stdin to PIPE
        dup2(outfd[1], STDOUT_FILENO);  // Linking stdout to PIPE
        dup2(outfd[1], STDERR_FILENO);  // Redirect child's stderr to child's stdout
        close(infd[0]);
        close(infd[1]);
        close(outfd[0]);
        close(outfd[1]);
        // Start process
		while (rc == -1 || rc == 0) {
			// Start console until it fail
			rc = cmd_start(cmd);
		}
        // Subprocess terminated, killing the parent
        UNLLog(LLERROR, "Child terminated (%i).\n", rc);
    } else if (rc > 0) {
        // Parent
        close(infd[0]);     // Used by the child
        close(outfd[1]);    // Used by the child

        // Handling Signals
        signal(SIGPIPE,SIG_IGN);            // Ignoring SIGPIPE when a client terminates
        sa.sa_handler = &signal_handler;    // Setup the sighub handler
        sa.sa_flags = SA_RESTART;           // Restart the system call, if at all possible
        sigemptyset(&sa.sa_mask);           // Signals blocked during the execution of the handler
        sigaddset(&sa.sa_mask, SIGHUP);     // Signal 1
        sigaddset(&sa.sa_mask, SIGINT);     // Signal 2
        sigaddset(&sa.sa_mask, SIGTERM);    // Signal 15
        sigfillset(&sa.sa_mask);

        // Intercept SIGHUP, SIGINT, SIGUSR1 and SIGTERM
        if (sigaction(SIGHUP, &sa, NULL) == -1) {
            UNLLog(LLERROR, "Cannot handle SIGHUP (%s).\n", strerror(errno));
        }
        if (sigaction(SIGINT, &sa, NULL) == -1) {
            UNLLog(LLERROR, "Cannot handle SIGINT (%s).\n", strerror(errno));
        }
        if (sigaction(SIGTERM, &sa, NULL) == -1) {
            UNLLog(LLERROR, "Cannot handle SIGTERM (%s).\n", strerror(errno));
        }

        // Preparing select()
		FD_ZERO(&active_fd_set);
		FD_ZERO(&read_fd_set);
		FD_SET(outfd[0], &active_fd_set);         // Adding subprocess stdout
		FD_SET(ts_socket, &active_fd_set);        // Adding telnet socket

		// While subprocess is running, check IO from subprocess, telnet clients, socket and network
		while (waitpid(child_pid, &child_status, WNOHANG|WUNTRACED) == 0) {
			// Check if select() is valid
			read_fd_set = active_fd_set;
			if (select(FD_SETSIZE, &read_fd_set, NULL, NULL, NULL) <= 0) {
				UNLLog(LLERROR, "Failed to select().\n");
				kill(0, SIGTERM);
				break;
			}

			// Check if output from child
			if (FD_ISSET(outfd[0], &read_fd_set)) {
				if (read(outfd[0], &child_output, 1) <= 0) {
					UNLLog(LLERROR, "Error while reading data from the subprocess, killing it.\n");
					kill(0, SIGTERM);
					break;
				}
				// Writing to all telnet clients
				ts_broadcast(child_output, &active_fd_set, tsclients_socket);
			}

			// Check if new client is coming
			if (FD_ISSET(ts_socket, &read_fd_set)) {
				if ((rc = ts_accept(&active_fd_set, ts_socket, xtitle, tsclients_socket,1)) != 0) {
					UNLLog(LLERROR, "Failed to accept a new client (%i).\n", rc);
				}
			}

			// Check for output from all telnet clients
			if (ts_receive(&client_input, &read_fd_set, &active_fd_set, tsclients_socket) == 0) {
				// Write to child
				rc = write(infd[1], &client_input, 1);
				if (rc < 0) {
					UNLLog(LLERROR, "Error writing to the subprocess, closing.\n");
					kill(0, SIGTERM);
					break;
				}
			}
		}
    } else {
        UNLLog(LLERROR, "Failed to fork.\n" );
        exit(1);
    }
    close(ts_socket);
    exit(0);
}
Пример #24
0
void cmd_add_wrapper(const char *nickname)
{
    cmd_add(nickname);
}
Пример #25
0
int main (int argc, char *argv[]) {
    setpgrp();  // Become the leader of its group.
    // Child's CMD line
    int m = sysconf(_SC_ARG_MAX);           // Maximum CMD line length
    char *cmd;                              // Store child's CMD line
    cmd = (char *) calloc(m, sizeof(char));

    // Child's parameters
    int *child_delay = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    *child_delay = 0;                       // Delay before starting (shared between parent and child)
    int child_pid = -1;                     // PID after the fork()
    int child_status = -1;                  // Used during waitpid()
    char *child_file = NULL;                // Binary file

    // Telnet server
    int ts_port = -1;                       // TCP (console) and UDP (serial converter) port
    char *xtitle = "Terminal Server";       // Title for telnet clients

    // Select parameters
    int *infd = calloc(2, sizeof(int));     // Array of integers [0] is for reading, [1] is for writing
    int *outfd = calloc(2, sizeof(int));    // Array of integers [0] is for reading, [1] is for writing
    fd_set active_fd_set;                   // Contains active FD using in select()
    FD_ZERO(&active_fd_set);
    fd_set read_fd_set;                     // Contains FD selected in current loop
    FD_ZERO(&read_fd_set);

    // Other parameters
    int i = -1;                             // Counter
    int j = -1;                             // Counter
    int opt = NULL;                         // Store CMD options
    int rc = -1;                            // Generic return code
    char *tmp = NULL;                       // Generic char string
    struct sigaction sa;                    // Manage signals (SIGHUP, SIGTERM...)

    // Wrapper parameters
    int child_afsocket[100];                // Store AF_UNIX child sockets
    memset(&child_afsocket, 0, sizeof(child_afsocket));
    int ser_remoteid[64];                   // Store Remote Device ID (used for UDP communication)
    memset(&ser_remoteid, 0, sizeof(ser_remoteid));
    int ser_remoteif[64];                   // Store Remote Interface ID (used for UDP communication)
    memset(&ser_remoteif, 0, sizeof(ser_remoteif));
    int udpserver_socket = -1;              // UDP socket for serial communications
    int wrapper_afsocket[100];              // Store AF_UNIX wrapper sockets
    memset(&wrapper_afsocket, 0, sizeof(wrapper_afsocket));

    // Parsing options
    while ((opt = getopt(argc, argv, ":vT:D:d:t:F:x")) != -1) {
        switch (opt) {
            default:
                usage(argv[0]);
                exit(1);
            // Begin standard parameters
            case 'v':
                printf("%s\n", VERSION);
                exit(0);
            case 'T':
                // Mandatory: Tenant ID
                tenant_id = atoi(optarg);
                if (tenant_id < 0) {
                    UNLLog(LLERROR,"Tenant_id must be integer.\n");
                    exit(1);
                }
                UNLLog(LLINFO, "Tennant_id = %i\n", tenant_id);
                break;
            case 'D':
                // Mandatory: Device ID
                device_id = atoi(optarg);
                if (tenant_id < 0) {
                    UNLLog(LLERROR,"Device_id must be integer.\n");
                    exit(1);
                }
                UNLLog(LLINFO, "Device_id = %i\n", device_id);
                break;
            case 'F':
                // Mandatory: IOS
                child_file = optarg;
                if (is_file(child_file) != 0) {
                    UNLLog(LLERROR,"File '%s' does not exist.\n", child_file);
                    exit(1);
                }
                break;
            case 'd':
                // Optional: child's startup delay (default 0)
                *child_delay = atoi(optarg);
                if (*child_delay < 0) {
                    UNLLog(LLERROR,"Delay must be integer.\n");
                    exit(1);
                }
                break;
            case 't':
                // Optional: telnet window title (default "Terminal Server")
                xtitle = optarg;
                break;
        }
    }

    // Checking if tenant_id is set
    if (tenant_id < 0) {
        UNLLog(LLERROR,"Tenant ID not set.\n");
        exit(1);
    }

    // Checking if device_id is set
    if (device_id < 0) {
        UNLLog(LLERROR,"Device ID not set.\n");
        exit(1);
    }

    // Checking if child_file is set
    if (child_file == NULL) {
        UNLLog(LLERROR,"Subprocess executable not set.\n");
        exit(1);
    }

    // Building the CMD line
    ts_port = 32768 + 128 * tenant_id + device_id;
    tmp = (char *) malloc(m * sizeof(char));
    sprintf(tmp, "/usr/bin/dynamips -N '%s' -T %i", xtitle, ts_port);
    cmd_add(&cmd, tmp);
    free(tmp);

    // Adding parameters after "--"
    j = 0;
    for (i = 1; i < argc; i++) {
        if (j == 1) {
            // Adding parameter given after "--"
            cmd_add(&cmd, " ");
            cmd_add(&cmd, argv[i]);
        }
        if (strcmp(argv[i], "--") == 0) {
            // Found "--"
            j = 1;
        }
    }

    // Adding the IOS filename
    cmd_add(&cmd, " ");
    cmd_add(&cmd, child_file);

    // Creating PIPEs for select()
    if ((pipe(infd)) < 0 || pipe(outfd) < 0) {
         UNLLog(LLERROR, "Failed to create PIPEs (%s).\n", strerror(errno));
         exit(1);
    }

    // Forking
    if ((rc = fork()) == 0) {
        // Child: stating subprocess
        UNLLog(LLINFO, "Starting child (%s).\n", cmd);
        if (*child_delay > 0) {
            // Delay is set, waiting
            for (; *child_delay > 0;) {
                rc = write(outfd[1], ".", 1);
                *child_delay = *child_delay - 1;
                sleep(1);
            }
            rc = write(outfd[1], "\n", 1);
        }
        close(STDIN_FILENO);            // Closing child's stdin
        close(STDOUT_FILENO);           // Closing child's stdout
        dup2(infd[0], STDIN_FILENO);    // Linking stdin to PIPE
        dup2(outfd[1], STDOUT_FILENO);  // Linking stdout to PIPE
        dup2(outfd[1], STDERR_FILENO);  // Redirect child's stderr to child's stdout
        close(infd[0]);
        close(infd[1]);
        close(outfd[0]);
        close(outfd[1]);
        // Start process
        rc = cmd_start(cmd);
        // Subprocess terminated, killing the parent
        UNLLog(LLERROR,"Child terminated (%i).\n", rc);
    } else if (rc > 0) {
        // Parent
        close(infd[0]);                     // Used by the child
        close(outfd[1]);                    // Used by the child

        // Handling Signals
        signal(SIGPIPE,SIG_IGN);            // Ignoring SIGPIPE when a client terminates
        sa.sa_handler = &signal_handler;    // Setup the sighub handler
        sa.sa_flags = SA_RESTART;           // Restart the system call, if at all possible
        sigemptyset(&sa.sa_mask);           // Signals blocked during the execution of the handler
        sigaddset(&sa.sa_mask, SIGHUP);     // Signal 1
        sigaddset(&sa.sa_mask, SIGINT);     // Signal 2
        sigaddset(&sa.sa_mask, SIGTERM);    // Signal 15
        sigfillset(&sa.sa_mask);

        // Intercept SIGHUP, SIGINT, SIGUSR1 and SIGTERM
        if (sigaction(SIGHUP, &sa, NULL) == -1) {
            UNLLog(LLERROR, "Cannot handle SIGHUP (%s).\n", strerror(errno));
        }
        if (sigaction(SIGINT, &sa, NULL) == -1) {
            UNLLog(LLERROR, "Cannot handle SIGINT (%s).\n", strerror(errno));
        }
        if (sigaction(SIGTERM, &sa, NULL) == -1) {
            UNLLog(LLERROR, "Cannot handle SIGTERM (%s).\n", strerror(errno));
        }

        // Preparing select()
        FD_ZERO(&active_fd_set);
        FD_ZERO(&read_fd_set);
        if (udpserver_socket > 0) {
            FD_SET(udpserver_socket, &active_fd_set); // Adding UDP socket
        }

        // While subprocess is running, check IO from subprocess, telnet clients, socket and network
        waitpid(child_pid, &child_status, 0);
        // Child is no more running
        UNLLog(LLERROR, "Child is no more running.\n");
    } else {
        UNLLog(LLERROR, "Failed to fork (%s).\n", strerror(errno));
        exit(1);
    }
    exit(0);
}
Пример #26
0
Файл: ur-cmd.c Проект: spolu/ur
int
cmd_add (const char *path, bool recursive)
{
  char *prt_dir = NULL, *fname = NULL, *dname = NULL;
  struct stat64 st_buf;
  state_t ur = STATE_INITIALIZER;
  struct index index = INDEX_INITIALIZER; 
  int status;

  if (lstat64 (path, &st_buf) != 0) fail("%s does not exist", path);

  prt_dir = (char *) malloc (strlen (path) + 4);
  parent_dir (path, prt_dir);

  if (st_buf.st_mode & S_IFREG) {

    fname = (char *) malloc (strlen (path) + 4);
    filename (path, fname);	

    if (ur_check (prt_dir) == 0) 
      {
	if (state_init (&ur, prt_dir) != 0) fail ("fail reading state of %s", prt_dir);
	if (index_read (&ur, &index) != 0) fail ("fail reading index of %s", prt_dir);
	
	status = index_entry_get_status (&index, fname);
	status |= S_IADD;
	if (!(status & S_IPST))
	  status |= S_IPST;
	index_entry_set_status (&index, fname, status);

	if (index_write (&ur, &index) != 0) fail ("fail writing index of %s", prt_dir);

	index_destroy (&index);
	state_destroy (&ur);
      }
    else
      fail ("%s initialization failed", prt_dir);	

    free (fname); fname = NULL;    
  }

  if (st_buf.st_mode & S_IFDIR) 
    {
      dname = (char *) malloc (strlen (path) + 4);
      dirname (path, dname);	

      if (ur_check (path) == 0) {
	if (ur_check (prt_dir) == 0) 
	  {
	    if (state_init (&ur, prt_dir) != 0) fail ("fail reading state of %s", prt_dir);
	    if (index_read (&ur, &index) != 0) fail ("fail reading index of %s", prt_dir);
	    
	    status = index_entry_get_status (&index, dname);
	    status |= S_IADD;
	    if (!(status & S_IPST))
	      status |= S_IPST;	
	    index_entry_set_status (&index, dname, status);

	    if (index_write (&ur, &index) != 0) fail ("fail writing index of %s", prt_dir);
	    index_destroy (&index);
	    state_destroy (&ur);
	}
      }
      else {

	if (ur_create (path) != 0) fail ("%s initialization failed", path);	
	output ("init: %s", path);
	
	if (ur_check (prt_dir) == 0) {
	    if (state_init (&ur, prt_dir) != 0) fail ("fail reading state of %s", prt_dir);
	    if (index_read (&ur, &index) != 0) fail ("fail reading index of %s", prt_dir);
	    
	    status = index_entry_get_status (&index, dname);
	    status |= S_IADD;
	    if (!(status & S_IPST))
	      status |= S_IPST;	
	    index_entry_set_status (&index, dname, status);

	    if (index_write (&ur, &index) != 0) fail ("fail writing index of %s", prt_dir);
	    index_destroy (&index);
	    state_destroy (&ur);
	}
      }

      free (dname); dname = NULL;    
    }
  
  free (prt_dir); prt_dir = NULL;

  /*
   * recursion
   */
  if ((st_buf.st_mode & S_IFDIR) && recursive) 
    {
      DIR *dp;
      struct dirent *ep;
      
      dp = opendir (path);
      if (dp != NULL)
	{
	  while ((ep = readdir (dp))) {
	    if (ep->d_name[0] != '.') 
	      {		
		char *npath;
		npath = (char *) malloc (strlen (path) +
					 strlen (ep->d_name) + 2);
		if (path[strlen (path) -1] == '/')
		  sprintf (npath, "%s%s", path, ep->d_name);
		else
		  sprintf (npath, "%s/%s", path, ep->d_name);
		cmd_add (npath, recursive);
		free (npath);
	      }	    
	  }
	  (void) closedir (dp);
	}
      else
	fail ("could not open directory %s", path);      
    }
  
  return 0;
}
Пример #27
0
void dllInit()
{
	cmd_add("+forward", c_test_bgnforward);
	cmd_add("-forward", c_test_endforward);
	cmd_add("+back", c_test_bgnback);
	cmd_add("-back", c_test_endback);
	cmd_add("+strafeleft", c_test_bgnstrafeleft);
	cmd_add("-strafeleft", c_test_endstrafeleft);
	cmd_add("+straferight", c_test_bgnstraferight);
	cmd_add("-straferight", c_test_endstraferight);
	cmd_add("+moveup", c_test_bgnmoveup);
	cmd_add("-moveup", c_test_endmoveup);
	cmd_add("+movedown", c_test_bgnmovedown);
	cmd_add("-movedown", c_test_endmovedown);
	cmd_add("+spinleft", c_test_bgnspinleft);
	cmd_add("-spinleft", c_test_endspinleft);
	cmd_add("+spinright", c_test_bgnspinright);
	cmd_add("-spinright", c_test_endspinright);	
	cmd_add("testdraw", c_testdraw);

	vu_bgn("hello");
	{
		vu_cmd("testdraw");

		vu_kcmd('a', "strafeleft");
		vu_kcmd('d', "straferight");
		vu_kcmd('w', "forward");
		vu_kcmd('s', "back");
		vu_kcmd(SDLK_UP, "moveup");
		vu_kcmd(SDLK_DOWN, "movedown");
		vu_kcmd(SDLK_LEFT, "spinleft");
		vu_kcmd(SDLK_RIGHT, "spinright");
	}
	vu_end();

	v3_t target={-10,5,15};

	cam3_add("testcam3", target, add(target,vec(0,2.5,-10)), 7, 1);

	shaderpdm=vfs_load("shaders/pdm.c");

	
	int w,h,comp;

	uchar *normal_data=stbi_load("wall_n.tga", &w, &h, &comp, 3);
	texrelief=tex3b(w,h, 011, normal_data);
	free(normal_data);
	
	uchar *color_data=stbi_load("wall_d.tga", &w, &h, &comp, 3);
	texcolor=tex3b(w,h, 011, color_data);
	free(color_data);

	uchar *depth_data=stbi_load("wall_h.tga", &w,&h,&comp,1);
	texpyramid=tex1b(w,h, 100, depth_data);
	
#if 1
	uchar *mem=alloca(w*h/2);
	uchar *level[10];
	level[0]=depth_data;
	level[1]=mem;
	int L=1;
	for (int sz=w/2; sz; sz>>=1) {
		uchar *p=level[L];

		for (int i=0; i<sz; i++) {
			for (int j=0; j<sz; j++) {
				uchar d[4];
				int w=2*sz;
				int x,y;

				x=2*i; y=2*j;
				d[0]=level[L-1][y*w+x];
				x=2*i+1; y=2*j;
				d[1]=level[L-1][y*w+x];
				x=2*i; y=2*j+1;
				d[2]=level[L-1][y*w+x];
				x=2*i+1; y=2*j+1;
				d[3]=level[L-1][y*w+x];

				level[L][j*sz+i] = min(min(d[0],d[1]),min(d[2],d[3]));
			}
		}

/*
		image_t img;
		img.width=img.height=sz;
		img.type=1;
		img.depth=8;
		img.data=level[L];

		char nam[32];
		sprintf(nam, "pyramid%i.tga", L);
		writetga(&img, nam);
*/

		glTexImage2D(GL_TEXTURE_2D, L/*level*/, GL_ALPHA8, sz,sz, 0/*border*/,
			     GL_ALPHA, GL_UNSIGNED_BYTE, level[L]);

		level[L+1]=level[L]+sz*sz;
		++L;
	}
#endif


#if 1
	texdepth=tex1b(w,h, 211, depth_data);
//	glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); /* hardware mipmap generation */	
	assert(!gluBuild2DMipmaps(GL_TEXTURE_2D, GL_ALPHA8, w, h, GL_ALPHA, GL_UNSIGNED_BYTE, depth_data));

#endif
	free(depth_data);
	
}
Пример #28
0
int ShopSysCostomer::receive_command(string _cmd)
{
	vector<string> cmd_analysis = str_Split_not_add_zero(_cmd);

	/* add command */
	if (cmd_analysis[0] == "add")
	{
		return cmd_add(cmd_analysis);
	}
	else if (cmd_analysis[0] == "rmv")
	{
		return cmd_rmv(cmd_analysis);
	}
	else if (cmd_analysis[0] == "chk")
	{
		return cmd_chk(cmd_analysis);
	}
	else if (cmd_analysis[0] == "ls")
	{
		return cmd_productlist(cmd_analysis);
	}
	else if (cmd_analysis[0] == "login")
	{
		return cmd_login(cmd_analysis);
	}
	else if ((cmd_analysis[0] == "logout") && (cmd_analysis.size() == 1))
	{
		return logout_action();
	}
	else if ((cmd_analysis[0] == "pay") && (cmd_analysis.size() == 1))
	{
		return cmd_settle_account();
	}
	else if (cmd_analysis[0] == "")
	{
		return 0;
	}
	else if ((cmd_analysis[0] == "exit") && (cmd_analysis.size() == 1))
	{
		if (is_member)
		{
			fstream fmember;
			fmember.open(".\\members\\" + p_identity->get_id() + ".txt", ios::trunc | ios::out);
			fmember << p_identity->get_id() << ','
				<< p_identity->get_name() << ','
				<< p_identity->get_gender() << ','
				<< p_identity->get_phone() << ','
				<< p_identity->get_points() << ','
				<< password_mem;
			fmember.close();
			//Refresh file done
			delete p_identity;
			p_identity = NULL;
			is_member = false;
		}
		cout << endl << "Bye!";
		return 2;
	}
	else if ((cmd_analysis[0] == "help") && (cmd_analysis.size() == 1))
	{
		cout << "Command mannual : " << endl;
		cout << "ls [number each page] : List all the goods." << endl;
		cout << "add <Goods ID> [number] : add [number(default 1)] goods into your cart." << endl;
		cout << "rmv <Goods ID> [number] : remove [number(default all of this ID)] goods from your cart." << endl;
		cout << "login : Log in command." << endl;
		cout << "logout : Log out command." << endl;
		cout << "chk : Check your carts of goods." << endl;
		cout << "pay : Settle account." << endl;
		cout << "info : (Only used when logged in)Check member info." << endl;
		return 0;
	}
	else if ((cmd_analysis[0] == "info") && (cmd_analysis.size() == 1))
	{
		if (!is_member)
		{
			cout << "You have to login first." << endl;
			return 0;
		}

		cout << "Your info : " << endl;
		cout << "Member ID : " << p_identity->get_id() << endl;
		cout << "Name : " << p_identity->get_name() << endl;
		cout << "Gender : " << p_identity->get_gender() << endl;
		cout << "Phone : " << p_identity->get_phone() << endl;
		cout << "Member type : " << p_identity->get_member_type() << endl;
		cout << "Points : " << p_identity->get_points() << endl;
		return 0;
	}
	else
	{
		return 1;
	}
}
Пример #29
0
int main(int argc, const char *argv[]) {
	io_func* io;
	Volume* volume;
	AbstractFile* image;
	int argOff;
	
	TestByteOrder();
	
	if(argc < 3) {
		printf("usage: %s <image-file> (-k <key>) <ls|cat|mv|mkdir|add|rm|chmod|extract|extractall|rmall|addall|grow|untar> <arguments>\n", argv[0]);
		return 0;
	}

	argOff = 2;
	
	if(strstr(argv[1], ".dmg")) {
		image = createAbstractFileFromFile(fopen(argv[1], "rb"));
		if(argc > 3) {
			if(strcmp(argv[2], "-k") == 0) {
				image = createAbstractFileFromFileVault(image, argv[3]);
				argOff = 4;
			}
		}
		io = openDmgFilePartition(image, -1);
	} else {
		io = openFlatFile(argv[1]);
	}

	if(io == NULL) {
		fprintf(stderr, "error: Cannot open image-file.\n");
		return 1;
	}
	
	volume = openVolume(io); 
	if(volume == NULL) {
		fprintf(stderr, "error: Cannot open volume.\n");
		CLOSE(io);
		return 1;
	}
	
	if(argc > argOff) {
		if(strcmp(argv[argOff], "ls") == 0) {
			cmd_ls(volume, argc - argOff, argv + argOff);
		} else if(strcmp(argv[argOff], "cat") == 0) {
			cmd_cat(volume, argc - argOff, argv + argOff);
		} else if(strcmp(argv[argOff], "mv") == 0) {
			cmd_mv(volume, argc - argOff, argv + argOff);
		} else if(strcmp(argv[2], "symlink") == 0) {
			cmd_symlink(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[argOff], "mkdir") == 0) {
			cmd_mkdir(volume, argc - argOff, argv + argOff);
		} else if(strcmp(argv[argOff], "add") == 0) {
			cmd_add(volume, argc - argOff, argv + argOff);
		} else if(strcmp(argv[argOff], "rm") == 0) {
			cmd_rm(volume, argc - argOff, argv + argOff);
		} else if(strcmp(argv[argOff], "chmod") == 0) {
			cmd_chmod(volume, argc - argOff, argv + argOff);
		} else if(strcmp(argv[argOff], "extract") == 0) {
			cmd_extract(volume, argc - argOff, argv + argOff);
		} else if(strcmp(argv[argOff], "extractall") == 0) {
			cmd_extractall(volume, argc - argOff, argv + argOff);
		} else if(strcmp(argv[argOff], "rmall") == 0) {
			cmd_rmall(volume, argc - argOff, argv + argOff);
		} else if(strcmp(argv[argOff], "addall") == 0) {
			cmd_addall(volume, argc - argOff, argv + argOff);
		} else if(strcmp(argv[argOff], "grow") == 0) {
			cmd_grow(volume, argc - argOff, argv + argOff);
		} else if(strcmp(argv[argOff], "untar") == 0) {
			cmd_untar(volume, argc - argOff, argv + argOff);
		}
	}
	
	closeVolume(volume);
	CLOSE(io);
	
	return 0;
}