Beispiel #1
0
int cmd_app(struct CONSOLE *cons, int *fat, char *cmdline)
{
	struct MEMMAN *memman = (struct MEMMAN *) MEMMAN_ADDR;
	struct FILEINFO *finfo;
	struct SEGMENT_DESCRIPTOR *gdt = (struct SEGMENT_DESCRIPTOR *) ADR_GDT;
	char name[18], *p, *q;
	struct TASK *task = task_now();
	int i;

	/* コマンドラインからファイル名を生成 */
	for (i = 0; i < 13; i++) {
		if (cmdline[i] <= ' ') {
			break;
		}
		name[i] = cmdline[i];
	}
	name[i] = 0; /* とりあえずファイル名の後ろを0にする */

	/* ファイルを探す */
	finfo = file_search(name, (struct FILEINFO *) (ADR_DISKIMG + 0x002600), 224);
	if (finfo == 0 && name[i - 1] != '.') {
		/* 見つからなかったので後ろに".HRB"をつけてもう一度探してみる */
		name[i    ] = '.';
		name[i + 1] = 'H';
		name[i + 2] = 'R';
		name[i + 3] = 'B';
		name[i + 4] = 0;
		finfo = file_search(name, (struct FILEINFO *) (ADR_DISKIMG + 0x002600), 224);
	}

	if (finfo != 0) {
		/* ファイルが見つかった場合 */
		p = (char *) memman_alloc_4k(memman, finfo->size);
		q = (char *) memman_alloc_4k(memman, 64 * 1024);
		*((int *) 0xfe8) = (int) p;
		file_loadfile(finfo->clustno, finfo->size, p, fat, (char *) (ADR_DISKIMG + 0x003e00));
		set_segmdesc(gdt + 1003, finfo->size - 1, (int) p, AR_CODE32_ER + 0x60);
		set_segmdesc(gdt + 1004, 64 * 1024 - 1,   (int) q, AR_DATA32_RW + 0x60);
		if (finfo->size >= 8 && strncmp(p + 4, "Hari", 4) == 0) {
			start_app(0x1b, 1003 * 8, 64 * 1024, 1004 * 8, &(task->tss.esp0));
		} else {
			start_app(0, 1003 * 8, 64 * 1024, 1004 * 8, &(task->tss.esp0));
		}
		memman_free_4k(memman, (int) p, finfo->size);
		memman_free_4k(memman, (int) q, 64 * 1024);
		cons_newline(cons);
		return 1;
	}
	/* ファイルが見つからなかった場合 */
	return 0;
}
Beispiel #2
0
void SIGALRM_handler(int s)
{
    SWI_LOG("APPMON", DEBUG, "SIGALRM_handler: pid=%d ======>\n", getpid());
    app_t* app = NULL;
    unsigned int size = 0, i = 0;
    PointerList_GetSize(apps, &size, NULL);
    SWI_LOG("APPMON", DEBUG, "SIGALRM_handler: started_apps size = %d\n", size);
    for (i = 0; i < size; i++)
    {
        PointerList_Peek(apps, i, (void**) &app);
        if (NULL != app && app->status == TO_BE_RESTARTED)
        {
            SWI_LOG("APPMON", DEBUG, "SIGALRM_handler: needs to restart %s\n", app->prog);
            char * res = start_app(app);
            if (!strcmp(res, "ok"))
            {
                SWI_LOG("APPMON", DEBUG, "SIGALRM_handler: %s restarted, new pid=%d\n", app->prog, app->pid);
            }
            else
            {
                SWI_LOG("APPMON", ERROR, "SIGALRM_handler: Cannot restart app id=%d, prog=%s, err=%s\n", app->id, app->prog, res);
                PointerList_Remove(apps, i, (void**) &app);
            }
        }
    }
    SWI_LOG("APPMON", DEBUG, "SIGALRM_handler: pid=%d ======<\n", getpid());
    fflush(stdout);
}
Beispiel #3
0
int cmd_app(struct CONSOLE *cons, int *fat, char *cmdline)
{
	struct MEMMAN *memman = (struct MEMMAN *) MEMMAN_ADDR;
	struct FILEINFO *finfo;
	struct SEGMENT_DESCRIPTOR *gdt = (struct SEGMENT_DESCRIPTOR *) ADR_GDT;
	char name[13], *p, *q;
	struct TASK *task = task_now();
	int i, segsiz, datsiz, esp, dathrb;

	/* コマンドラインからファイル名を生成 */
	for (i = 0; i < 8; i++) {
		if (cmdline[i] <= ' ') {
			break;
		}
		name[i] = cmdline[i];
	}
	name[i] = 0; /* とりあえずファイル名の後ろを0にする */

	/* ファイルを探す */
	finfo = file_search(name, (struct FILEINFO *) (ADR_DISKIMG + 0x002600), 224);
	if (finfo == 0) {
		/* 見つからなかったので後ろに".HRB"をつけてもう一度探してみる */
		name[i    ] = '.';
		name[i + 1] = 'H';
		name[i + 2] = 'R';
		name[i + 3] = 'B';
		name[i + 4] = 0;
		finfo = file_search(name, (struct FILEINFO *) (ADR_DISKIMG + 0x002600), 224);
	}

	if (finfo != 0) {
		/* ファイルが見つかった場合 */
		p = (char *) memman_alloc_4k(memman, finfo->size);
		file_loadfile(finfo->clustno, finfo->size, p, fat, (char *) (ADR_DISKIMG + 0x003e00));
		if (finfo->size >= 36 && strncmp(p + 4, "Hari", 4) == 0 && *p == 0x00) {
			segsiz = *((int *) (p + 0x0000));
			esp    = *((int *) (p + 0x000c));
			datsiz = *((int *) (p + 0x0010));
			dathrb = *((int *) (p + 0x0014));
			q = (char *) memman_alloc_4k(memman, segsiz);
			*((int *) 0xfe8) = (int) q;
			set_segmdesc(gdt + 1003, finfo->size - 1, (int) p, AR_CODE32_ER + 0x60);
			set_segmdesc(gdt + 1004, segsiz - 1,      (int) q, AR_DATA32_RW + 0x60);
			for (i = 0; i < datsiz; i++) {
				q[esp + i] = p[dathrb + i];
			}
			start_app(0x1b, 1003 * 8, esp, 1004 * 8, &(task->tss.esp0));
			memman_free_4k(memman, (int) q, segsiz);
		} else {
			cons_putstr0(cons, ".hrb file format error.\n");
		}
		memman_free_4k(memman, (int) p, finfo->size);
		cons_newline(cons);
		return 1;
	}
	/* ファイルが見つからなかった場合 */
	return 0;
}
Beispiel #4
0
/* Main Program Routine */
int
main(void)
{
    uint16_t pgm_crc, count, cmp_crc;
	uint8_t crcgood=0;
#ifdef UART_DEBUG
    char sout[8];    
#endif

	init();
#ifdef UART_DEBUG
	uart_write("\nStart Node ", 12);
	itoa(node_id,sout, 16);
	uart_write(sout, strlen(sout));
	uart_write("\n", 1);
#endif

    /* Find the firmware size and checksum */
	count   = pgm_read_word_near(PGM_LENGTH);
    cmp_crc = pgm_read_word_near(PGM_CRC);

	/* Retrieve the Program Checksum */
	pgm_crc = pgmcrc(count);
	/* If it matches then set the good flag */
	if(pgm_crc == cmp_crc) {
	    crcgood = 1;
    }
#ifdef UART_DEBUG
    itoa(pgm_crc,sout,16);
	uart_write("Checksum ", 9);
	uart_write(sout,strlen(sout));
	uart_write("\n",1);
#endif
	/* This timer expires at roughly one second after startup */
	while(TCNT1 <= 0x2B00) /* Run this for about a second */
        bload_check();
    TCNT1 = 0x0000;
#ifdef UART_DEBUG
	uart_write("TIMEOUT\n",8);
#endif
	if(crcgood) {
	   start_app(); /* When we go here we ain't never comin' back */
    }
	
    /* If CRC is no good we sit here and look for a firmware update command
       forever. */
    PORTB |= (1<<PB0);
    while(1) { 

        bload_check();
        _delay_loop_2(0xFFFF); /* Delay */
	}	
}
Beispiel #5
0
int cmd_app (struct CONSOLE *cons, int *fat, char *cmdline)
{
  struct MEMMAN *memman = (struct MEMMAN *)MEMMAN_ADDR;
  struct FILEINFO *finfo;
  struct SEGMENT_DESCRIPTOR *gdt = (struct SEGMENT_DESCRIPTOR *)ADR_GDT;
  char name [18];
  int i;
  struct TASK *task = task_now ();
  
  for (i = 0; i < 13; i++) {
    if (cmdline[i] <= ' ') {
      break;
    }
    name[i] = cmdline[i];
  }
  name[i] = 0;
  finfo = file_search (name, (struct FILEINFO *)(ADR_DISKIMG + 0x002600), 224);
  if (finfo == 0 && name[i-1] != '.') {
    name [i+0]  = '.';
    name [i+1]  = 'H';
    name [i+2]  = 'R';
    name [i+3]  = 'B';
    name [i+4]  = 0;
    finfo = file_search (name, (struct FILEINFO *)(ADR_DISKIMG + 0x002600), 224);
  }

  if (finfo != 0) {
    char *p = (char *)memman_alloc_4k (memman, finfo->size);
	char *q = (char *)memman_alloc_4k (memman, 64 * 1024);
    *((int *) 0xfe8) = (int) p;
    file_loadfile (finfo->clustno, finfo->size, p, fat, (char *) (ADR_DISKIMG + 0x003e00));
    set_segmdesc (gdt + 1003, finfo->size - 1, (int) p, AR_CODE32_ER + 0x60);
	set_segmdesc (gdt + 1004, 64 * 1024 - 1,   (int) q, AR_DATA32_RW + 0x60);
    if (finfo->size >= 8 && strncmp (p + 4, "Hari", 4) == 0) {
      p[0] = 0xe8;
      p[1] = 0x16;
      p[2] = 0x00;
      p[3] = 0x00;
      p[4] = 0x00;
      p[5] = 0xcb;
    }
	start_app (0, 1003 * 8, 64 * 1024, 1004 * 8, &(task->tss.esp0));
    memman_free_4k (memman, (int) p, finfo->size);
	memman_free_4k (memman, (int) q, 64 * 1024);
    cons_newline (cons);
    return 1;
  }

  return 0;
}
Beispiel #6
0
Datei: app.c Projekt: dankex/lk
/* one time setup */
void apps_init(void)
{
	const struct app_descriptor *app;

	/* call all the init routines */
	for (app = &__apps_start; app != &__apps_end; app++) {
		if (app->init)
			app->init(app);
	}

	/* start any that want to start on boot */
	for (app = &__apps_start; app != &__apps_end; app++) {
		if (app->entry && (app->flags & APP_FLAG_DONT_START_ON_BOOT) == 0) {
			start_app(app);
		}
	}
}
Beispiel #7
0
int main(int argc, char **argv)
{
    int c_sock;/*client socket*/
    int rc;
    char buf[BUFFER_SIZE];
    motor_opts_t motor;
    agv2Buffer(argv, argc, buf);
/*Decode argv and init connection to server*/
    rc = start_app(buf, BUFFER_SIZE, &c_sock);
    if(rc < 0)
    {
	    perror("client: Failed to start c-app");
	    return -1;
    }
    else
	    printf("c-app: client app start-up complete\n");
    /*Prepare bt_packets to send with data from app_options_t
     * For now prepare only motor opts*/
    comm_handler(c_sock);
    return 0;
}
Beispiel #8
0
int main(int argc, char const *argv[])
{
    switch_on_hse();
    construct_exceptions();
    construct_nvic();
    construct_systick();
    construct_scheduler();
    construct_app();
    construct_rcc();
    construct_gpio();
    construct_tim14();

    start_exceptions();
    start_nvic();
    start_systick();
    start_rcc();
    start_gpio();
    start_tim14();

    start_app();
    /* must be last */
    start_scheduler();
}
Beispiel #9
0
int main()
{
    LPWSTR *argv; int argc;

    argv = CommandLineToArgvW(GetCommandLineW(), &argc);
    if(argv == NULL) {
        error("Error parsing commandline options!\n");
    }

    if(argc < 4) {
        error(
            "Usage: %S <options..>\n"
            "Options:\n"
            "  --crt                  CreateRemoteThread injection\n"
            "  --apc                  QueueUserAPC injection\n"
            "  --free                 Do not inject our monitor\n"
            "  --dll <dll>            DLL to inject\n"
            "  --app <app>            Path to application to start\n"
            "  --args <args>          Command-line arguments\n"
            "                         Excluding the application path!\n"
            "  --curdir <dirpath>     Current working directory\n"
            "  --maximize             Maximize the newly created GUI\n"
            "  --pid <pid>            Process identifier to inject\n"
            "  --process-name <name>  Process name to inject\n"
            "  --tid <tid>            Thread identifier to inject\n"
            "  --from <pid>           Inject from another process\n"
            "  --from-process <name>  "
            "Inject from another process, resolves pid\n"
            "  --only-start           "
            "Start the application and print pid/tid\n"
            "  --resume-thread        "
            "Resume the thread of the pid/tid target\n"
            "  --config <path>        "
            "Configuration file for the monitor\n"
            "  --dbg <path>           "
            "Attach debugger to target process\n"
            "  --dump <filepath>      "
            "Dump process memory with --pid to filepath\n"
            "  --verbose              Verbose switch\n",
            argv[0]
        );
    }

    const wchar_t *dll_path = NULL, *app_path = NULL, *arguments = L"";
    const wchar_t *config_file = NULL, *from_process = NULL, *dbg_path = NULL;
    const wchar_t *curdir = NULL, *process_name = NULL, *dump_path = NULL;
    uint32_t pid = 0, tid = 0, from = 0, inj_mode = INJECT_NONE;
    uint32_t show_window = SW_SHOWNORMAL, only_start = 0, resume_thread_ = 0;

    for (int idx = 1; idx < argc; idx++) {
        if(wcscmp(argv[idx], L"--crt") == 0) {
            inj_mode = INJECT_CRT;
            continue;
        }

        if(wcscmp(argv[idx], L"--apc") == 0) {
            inj_mode = INJECT_APC;
            continue;
        }

        if(wcscmp(argv[idx], L"--free") == 0) {
            inj_mode = INJECT_FREE;
            continue;
        }

        if(wcscmp(argv[idx], L"--dll") == 0) {
            dll_path = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--app") == 0) {
            app_path = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--args") == 0) {
            arguments = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--curdir") == 0) {
            curdir = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--maximize") == 0) {
            show_window = SW_MAXIMIZE;
            continue;
        }

        if(wcscmp(argv[idx], L"--pid") == 0) {
            pid = wcstol(argv[++idx], NULL, 10);
            continue;
        }

        if(wcscmp(argv[idx], L"--process-name") == 0) {
            process_name = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--tid") == 0) {
            tid = wcstol(argv[++idx], NULL, 10);
            continue;
        }

        if(wcscmp(argv[idx], L"--from") == 0) {
            from = wcstol(argv[++idx], NULL, 10);
            continue;
        }

        if(wcscmp(argv[idx], L"--from-process") == 0) {
            from_process = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--only-start") == 0) {
            only_start = 1;
            continue;
        }

        if(wcscmp(argv[idx], L"--resume-thread") == 0) {
            resume_thread_ = 1;
            continue;
        }

        if(wcscmp(argv[idx], L"--config") == 0) {
            config_file = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--dbg") == 0) {
            dbg_path = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--dump") == 0) {
            dump_path = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--verbose") == 0) {
            verbose = 1;
            continue;
        }

        error("[-] Found unsupported argument: %S\n", argv[idx]);
        return 1;
    }

    // Dump memory of a process.
    if(dump_path != NULL && pid != 0) {
        dump(pid, dump_path);
        return 0;
    }

    if(inj_mode == INJECT_NONE) {
        error("[-] No injection method has been provided!\n");
    }

    if(inj_mode == INJECT_CRT && pid == 0 && process_name == NULL &&
            app_path == NULL) {
        error("[-] No injection target has been provided!\n");
    }

    if(inj_mode == INJECT_APC && tid == 0 && process_name == NULL &&
            app_path == NULL) {
        error("[-] No injection target has been provided!\n");
    }

    if(inj_mode == INJECT_FREE && app_path == NULL) {
        error("[-] An app path is required when not injecting!\n");
    }

    if(pid != 0 && process_name != NULL) {
        error("[-] Both pid and process-name were set!\n");
    }

    static wchar_t dllpath[MAX_PATH_W];

    if(inj_mode == INJECT_FREE) {
        if(dll_path != NULL || tid != 0 || pid != 0) {
            error("[-] Unused --tid/--pid/--dll provided in --free mode!\n");
        }
    }

    if(inj_mode != INJECT_FREE) {
        if(PathFileExistsW(dll_path) == FALSE) {
            error("[-] Invalid DLL filepath has been provided\n");
        }

        if(GetFullPathNameW(dll_path, MAX_PATH_W, dllpath, NULL) == 0) {
            error("[-] Invalid DLL filepath has been provided\n");
        }

        if(GetLongPathNameW(dllpath, dllpath, MAX_PATH_W) == 0) {
            error("[-] Error obtaining the dll long path name\n");
        }
    }

    if(from != 0 && from_process != NULL) {
        error("[-] Both --from and --from-process are specified\n");
    }

    grant_debug_privileges(GetCurrentProcessId());

    if(app_path != NULL) {
        // If a process name has been provided as source process, then find
        // its process identifier (or first, if multiple).
        if(from_process != NULL) {
            from = pid_from_process_name(from_process);
        }

        // If no source process has been specified, then we use our
        // own process.
        if(from == 0) {
            from = GetCurrentProcessId();
        }

        if(PathFileExistsW(app_path) == FALSE) {
            error("[-] Invalid app filepath has been provided\n");
        }

        static wchar_t dirpath[MAX_PATH_W], filepath[MAX_PATH_W];

        // If a current working directory has been set then we use that
        // current working directory. Otherwise default to $TEMP.
        if(curdir != NULL) {
            // Allow the current working directory to be
            // specified as, e.g., %TEMP%.
            if(ExpandEnvironmentStringsW(curdir, dirpath, MAX_PATH_W) == 0) {
                error("[-] Error expanding environment variables\n");
            }

            curdir = dirpath;
        }
        else {
            // We don't want to be expanding the environment variable buffer
            // as that will probably corrupt the heap or so.
            curdir = wcscpy(dirpath, _wgetenv(L"TEMP"));
        }

        if(GetLongPathNameW(dirpath, dirpath, MAX_PATH_W) == 0) {
            error("[-] Error obtaining the curdir long path name\n");
        }

        if(GetFullPathNameW(app_path, MAX_PATH_W, filepath, NULL) == 0) {
            error("[-] Invalid app filepath has been provided\n");
        }

        if(GetLongPathNameW(filepath, filepath, MAX_PATH_W) == 0) {
            error("[-] Error obtaining the app long path name\n");
        }

        pid = start_app(from, filepath, arguments, curdir, &tid, show_window);
    }

    if(pid == 0 && process_name != NULL) {
        pid = pid_from_process_name(process_name);
    }

    // Drop the configuration file if available.
    if(config_file != NULL) {
        static wchar_t filepath[MAX_PATH_W];

        wsprintfW(filepath, L"C:\\cuckoo_%d.ini", pid);
        if(MoveFileW(config_file, filepath) == FALSE) {
            error("[-] Error dropping configuration file: %ld\n",
                GetLastError());
        }
    }

    // Do not do actual injection here, just have the application launched.
    if(only_start != 0) {
        printf("%d %d", pid, tid);
        return 0;
    }

    switch (inj_mode) {
    case INJECT_CRT:
        load_dll_crt(pid, dllpath);
        break;

    case INJECT_APC:
        load_dll_apc(pid, tid, dllpath);
        break;

    case INJECT_FREE:
        break;

    default:
        error("[-] Unhandled injection mode: %d\n", inj_mode);
    }

    if(dbg_path != NULL) {
        wchar_t buf[1024];
        wsprintfW(buf, L"\"%s\" -p %d", dbg_path, pid);

        start_app(GetCurrentProcessId(), dbg_path, buf,
            NULL, NULL, SW_SHOWNORMAL);

        Sleep(5000);
    }

    if((app_path != NULL || resume_thread_ != 0) && tid != 0) {
        resume_thread(tid);
    }

    // Report the process identifier.
    printf("%d", pid);
    return 0;
}
Beispiel #10
0
int main(int argc, char** argv)
{
    char *buffer = NULL;
    int portno = 0, stop, optval;
    socklen_t clilen;
    struct sockaddr_in serv_addr, cli_addr;
    struct sigaction action_CHLD;
    struct sigaction action_ALRM;

    /* Preliminary signal configuration:
     * SIGCHLD and SIGALRM are used with different handler
     * configure each handler to mask the other signal during it's process
     * Note: within a handler called upon a signal SIGX, the SIGX signal is
     * automatically de-activated.
     */

    sigemptyset(&block_sigs);
    sigaddset(&block_sigs, SIGCHLD);
    sigaddset(&block_sigs, SIGALRM);

    action_CHLD.sa_flags = SA_RESTART;
    action_CHLD.sa_handler = SIGCHLD_handler;
    sigemptyset(&(action_CHLD.sa_mask));
    sigaddset(&(action_CHLD.sa_mask), SIGALRM);

    action_ALRM.sa_flags = SA_RESTART;
    action_ALRM.sa_handler = SIGALRM_handler;
    sigemptyset(&(action_ALRM.sa_mask));
    sigaddset(&(action_ALRM.sa_mask), SIGCHLD);

    PointerList_Create(&apps, 0);
    if (NULL == apps)
        err_exit("PointerList_Create");

    /* Command line arguments Parsing
     * Options
     * a : privileged app path
     * w : privileged app working directory
     * v : user id to use to start privileged app
     * h : group id to use to start privileged app
     * p : TCP port to receive commands
     * u : user id to use to start regular apps
     * g : group id to use to start regular apps
     * n : nice value (process priority) for regular apps
     */
    char* init_app = NULL;
    char* init_app_wd = NULL;
    app_t* privileged_app = NULL;
    int opt;
    char useropt_given = 0;
    char grpopt_given = 0;
    //optarg is set by getopt
    while ((opt = getopt(argc, argv, "a:w:v:h:p:u:g:n:")) != -1)
    {
        switch (opt)
        {
        case 'a':
            init_app = optarg;
            SWI_LOG("APPMON", DEBUG, "Command line arguments parsing: init_app %s\n", init_app);
            break;
        case 'w':
            init_app_wd = optarg;
            SWI_LOG("APPMON", DEBUG, "Command line arguments parsing: init_app_wd %s\n", init_app_wd);
            break;
        case 'p':
            parse_arg_integer(optarg, &portno, "Command line arguments parsing: bad format for port argument");
            SWI_LOG("APPMON", DEBUG, "Command line arguments parsing: port =%d\n", portno);
            if (portno > UINT16_MAX)
            {
                err_exit("Command line arguments parsing: bad value for port, range=[0, 65535]");
            }
            break;
        case 'u':
            useropt_given = 1; //used to set default value after cmd line option parsing
            get_uid_option(&uid);
            break;
        case 'v':
            get_uid_option(&puid);
            break;
        case 'g':
            grpopt_given = 1; //used to set default value after cmd line option parsing
            get_gid_option(&gid);
            break;
        case 'h':
            get_gid_option(&pgid);
            break;
        case 'n':
            parse_arg_integer(optarg, &app_priority,
                              "Command line arguments parsing: app process priority must be an integer");
            if (19 < app_priority || -20 > app_priority)
            {
                err_exit("Command line arguments parsing: app process priority must be between -20 and 19");
            }
            SWI_LOG("APPMON", DEBUG, "Command line arguments parsing: nice increment =%d\n", app_priority);
            break;
        default: /* '?' */
            SWI_LOG("APPMON", ERROR, "Command line arguments parsing: unknown argument\n");
            break;
        }

    }
    if (NULL != init_app)
    {

        if (NULL == init_app_wd)
        {   //using current working directory as privileged app wd.
            cwd = malloc(PATH_MAX);
            if (NULL == cwd)
            {
                err_exit("Cannot malloc init_app_wd");
            }
            cwd = getcwd(cwd, PATH_MAX);
            if (NULL == cwd)
            {
                err_exit("getcwd failed to guess privileged app default wd");
            }
            init_app_wd = cwd;
        }
        char * res = check_params(init_app_wd, init_app);
        if (NULL != res)
        {
            SWI_LOG("APPMON", ERROR, "check_params on privileged app failed: %s\n", res);
            err_exit("check_params on privileged app failed");
        }
        privileged_app = add_app(init_app_wd, init_app, 1);
        if (NULL == privileged_app)
        {
            err_exit("add_app on privileged app failed");
        }
    }

    if (!uid && !useropt_given)
    {   //get default "nobody" user.
        uid = 65534;
    }

    if (!gid && !grpopt_given)
    {   //get default "nogroup" group.
        gid = 65534;
    }

    SWI_LOG("APPMON", DEBUG, "Command line arguments parsing: will use uid=%d and gid=%d to run unprivileged apps\n",
            uid, gid);

    /* configuring signals handling */
    if (sigaction(SIGCHLD, &action_CHLD, NULL))
        err_exit("configuring signals handling: sigaction SIGCHLD call error");

    if (sigaction(SIGALRM, &action_ALRM, NULL))
        err_exit("configuring signals handling: sigaction SIGCHLD call error");

    srv_skt = socket(AF_INET, SOCK_STREAM, 0);
    if (srv_skt < 0)
        err_exit("socket configuration: opening socket error");

    // set SO_REUSEADDR on socket:
    optval = 1;
    if (setsockopt(srv_skt, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
        err_exit("socket configuration: setting SO_REUSEADDR on socket failed");

    bzero((char *) &serv_addr, sizeof(serv_addr));
    portno = portno ? portno : DEFAULT_LISTENING_PORT;

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(portno);

    if (bind(srv_skt, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
        err_exit("socket configuration: error on binding");

    if (listen(srv_skt, 5))
        err_exit("socket configuration: error on listen");

    clilen = sizeof(cli_addr);
    stop = 0;

    SWI_LOG("APPMON", DEBUG, "Init successful, now running as daemon.\n");
    /* daemonize the later possible to enhance sync error reporting*/
    daemonize();
    /* Now we are a simple daemon */
    SWI_LOG("APPMON", DEBUG, "Daemon pid=%d, Listening port = %d\n", getpid(), portno);

    if (privileged_app)
    {
        SWI_LOG("APPMON", DEBUG, "Autostarting privileged app\n");
        start_app(privileged_app);
    }

    while (!stop)
    {
        fflush(stdout);
        client_skt = accept(srv_skt, (struct sockaddr *) &cli_addr, &clilen);
        if (client_skt < 0)
        {
            SWI_LOG("APPMON", ERROR, "socket configuration: error on accept: %s\n", strerror(errno));
            SWI_LOG("APPMON", ERROR, "Now going to crippled mode: cannot use socket API anymore!\n");
            if (client_skt)
                close(client_skt);
            if (srv_skt)
                close(srv_skt);
            // Sleep for 1.5 sec
            // sleep() function not used here, as it may disrupt the use of SIGALRM made in this program.
            struct timeval tv;
            while (1)
            {
                tv.tv_sec = 1;
                tv.tv_usec = 0;
                int res = select(0, NULL, NULL, NULL, &tv);
                SWI_LOG("APPMON", DEBUG, "crippled mode: select, res = %d\n", res);
            }
            //never returning from here, need to kill the daemon
            // but apps should still be managed.
        }

        SWI_LOG("APPMON", DEBUG, "new client ...\n");
        buffer = readline(client_skt);

        //deal with all the requests coming from the new client
        while (NULL != buffer && !stop)
        {
            SWI_LOG("APPMON", DEBUG, "NEW cmd=[%s]\n", buffer);
            do
            {
                if (!strncmp(buffer, STOP_DAEMON, strlen(STOP_DAEMON)))
                {
                    stop = 1;
                    send_result("ok, destroy is in progress, stopping aps, closing sockets.");
                    break;
                }
                if (!strncmp(buffer, PCONFIG, strlen(PCONFIG)))
                {
                    send_result(
                        fill_output_buf(
                            "appmon_daemon: version[%s], uid=[%d], gid=[%d], puid=[%d], pgid=[%d], app_priority=[%d]",
                            GIT_REV, uid, gid, puid, pgid, app_priority));
                    break;
                }
                if (!strncmp(buffer, SETUP_APP, strlen(SETUP_APP)))
                {
                    char* buf = buffer;
                    strsep(&buf, " ");
                    char* wd = strsep(&buf, " ");
                    char* prog = strsep(&buf, " ");

                    SWI_LOG("APPMON", DEBUG, "SETUP wd =%s, prog = %s\n", wd, prog);
                    if (NULL == wd || NULL == prog)
                    {
                        send_result("Bad command format, must have wd and prog params");
                        break;
                    }
                    char *res = check_params(wd, prog);
                    if (res)
                    {
                        send_result(res);
                        break;
                    }
                    sigprocmask(SIG_BLOCK, &block_sigs, NULL);
                    app_t* app = add_app(wd, prog, 0);
                    if (NULL == app)
                        send_result("Cannot add app");
                    else
                        send_result(fill_output_buf("%d", app->id));

                    sigprocmask(SIG_UNBLOCK, &block_sigs, NULL);

                    break;
                }
                if (!strncmp(buffer, START_APP, strlen(START_APP)))
                {
                    char* str_id = buffer + strlen(START_APP);
                    int id = atoi(str_id);
                    SWI_LOG("APPMON", DEBUG, "START_APP, id =%d\n", id);
                    if (id == 0)
                    {
                        send_result("Bad command format, start called with invalid app id");
                        break;
                    }
                    sigprocmask(SIG_BLOCK, &block_sigs, NULL);
                    app_t* app = find_by_id(id);
                    if (app == NULL)
                    {
                        send_result("Unknown app");
                        sigprocmask(SIG_UNBLOCK, &block_sigs, NULL);
                        break;
                    }
                    if (app->privileged)
                    {
                        send_result("Privileged App, cannot act on it through socket.");
                        sigprocmask(SIG_UNBLOCK, &block_sigs, NULL);
                        break;
                    }
                    if (app->status != KILLED)
                    {
                        send_result("App already running (or set to be restarted), start command discarded");
                        sigprocmask(SIG_UNBLOCK, &block_sigs, NULL);
                        break;
                    }
                    send_result(start_app(app));
                    sigprocmask(SIG_UNBLOCK, &block_sigs, NULL);
                    break;
                }

                if (!strncmp(buffer, STOP_APP, strlen(STOP_APP)))
                {
                    char* str_id = buffer + strlen(STOP_APP);
                    int id = atoi(str_id);
                    if (id == 0)
                    {
                        send_result("Bad command format, stop called with invalid app id");
                        break;
                    }
                    sigprocmask(SIG_BLOCK, &block_sigs, NULL);
                    app_t* app = find_by_id(id);
                    if (NULL == app)
                        send_result("Unknown app");
                    else
                    {
                        if (app->privileged)
                        {
                            send_result("Privileged App, cannot act on it through socket.");
                            sigprocmask(SIG_UNBLOCK, &block_sigs, NULL);
                            break;
                        }

                        //stop command has effect only if application is running.
                        if (app->status == STARTED || app->status == TO_BE_KILLED)
                        {
                            send_result(stop_app(app));
                        }
                        else
                        {   //application is already stopped (app->status could be KILLED or TO_BE_RESTARTED)
                            app->status = KILLED; //force app->status =  KILLED, prevent app to be restarted if restart was scheduled. (see SIG ALRM handler)
                            send_result("ok, already stopped, won't be automatically restarted anymore");
                        }

                    }
                    sigprocmask(SIG_UNBLOCK, &block_sigs, NULL);
                    break;
                }

                if (!strncmp(buffer, REMOVE_APP, strlen(REMOVE_APP)))
                {
                    char* str_id = buffer + strlen(REMOVE_APP);
                    int id = atoi(str_id);
                    if (id == 0)
                    {
                        send_result("Bad command format, remove called with invalid app id");
                        break;
                    }
                    sigprocmask(SIG_BLOCK, &block_sigs, NULL);
                    app_t* app = find_by_id(id);
                    if (NULL == app)
                        send_result("Unknown app");
                    else
                    {
                        if (app->privileged)
                        {
                            send_result("Privileged App, cannot act on it through socket.");
                            sigprocmask(SIG_UNBLOCK, &block_sigs, NULL);
                            break;
                        }
                        //stop command has effect only if application is running.
                        if (app->status == STARTED || app->status == TO_BE_KILLED)
                        {
                            stop_app(app); //trying to stop, no big deal with it fails
                        }

                        app_t* app = NULL;
                        unsigned int size, i = 0;
                        PointerList_GetSize(apps, &size, NULL);
                        for (i = 0; i < size; i++)
                        {
                            PointerList_Peek(apps, i, (void**) &app);
                            if (app->id == id)
                            {
                                rc_ReturnCode_t res = 0;
                                if (RC_OK != (res = PointerList_Remove(apps, i, (void**) &app)))
                                {
                                    send_result(fill_output_buf("Remove: PointerList_Remove failed, AwtStatus =%d", res));
                                }
                                else
                                {
                                    free(app);
                                    send_result("ok");
                                }
                                break;
                            }
                        }
                    }
                    sigprocmask(SIG_UNBLOCK, &block_sigs, NULL);
                    break;
                }

                if (!strncmp(buffer, STATUS_APP, strlen(STATUS_APP)))
                {
                    char* str_id = buffer + strlen(STATUS_APP);
                    int id = atoi(str_id);
                    if (id == 0)
                    {
                        send_result("Bad command format, status called with invalid app id");
                        break;
                    }

                    sigprocmask(SIG_BLOCK, &block_sigs, NULL);
                    app_t* app = find_by_id(id);
                    if (NULL == app)
                        send_result("Unknown app");
                    else
                    {
                        SWI_LOG("APPMON", DEBUG, "sending app status...\n");
                        send_result(create_app_status(app));
                    }
                    sigprocmask(SIG_UNBLOCK, &block_sigs, NULL);
                    break;
                }
                if (!strncmp(buffer, LIST_APPS, strlen(LIST_APPS)))
                {
                    SWI_LOG("APPMON", DEBUG, "sending app list ...\n");
                    sigprocmask(SIG_BLOCK, &block_sigs, NULL);
                    app_t* app = NULL;
                    unsigned int size, i = 0;
                    PointerList_GetSize(apps, &size, NULL);
                    for (i = 0; i < size; i++)
                    {
                        PointerList_Peek(apps, i, (void**) &app);
                        char* app_status_tmp = create_app_status(app);
                        if (strlen(app_status_tmp) != write(client_skt, app_status_tmp, strlen(app_status_tmp)))
                        {
                            SWI_LOG("APPMON", ERROR, "list: cannot write res to socket\n");
                        }
                        SWI_LOG("APPMON", DEBUG, "list: send status, app_status_tmp=%s\n", app_status_tmp);
                        char* statussep = "\t";
                        if (strlen(statussep) != write(client_skt, statussep, strlen(statussep)))
                        {
                            SWI_LOG("APPMON", ERROR, "list: cannot write statussep: %s\n", statussep);
                        }
                    }
                    send_result("");
                    sigprocmask(SIG_UNBLOCK, &block_sigs, NULL);
                    break;
                }
                if (!strncmp(buffer, SETENV, strlen(SETENV)))
                {
                    char *arg, *varname, *tmp;

                    arg = buffer + strlen(SETENV);
                    varname = arg;
                    tmp = strchr(arg, '=');
                    *tmp++ = '\0';

                    SWI_LOG("APPMON", DEBUG, "Setting Application framework environment variable %s = %s...\n", varname, tmp);
                    setenv(varname, tmp, 1);

                    send_result("");
                    break;
                }

                //command not found
                send_result("command not found");
                SWI_LOG("APPMON", DEBUG, "Command not found\n");
            } while (0);

            if (stop)
                break;

            //read some data again to allow to send several commands with the same socket
            buffer = readline(client_skt);

        } //end while buffer not NULL: current client has no more data to send

        //current client exited, let's close client skt, wait for another connexion
        close(client_skt);
    }

    sigprocmask(SIG_BLOCK, &block_sigs, NULL);
    int exit_status_daemon = clean_all();
    SWI_LOG("APPMON", DEBUG, "appmon daemon end, exit_status_daemon: %d\n", exit_status_daemon);
    return exit_status_daemon;
}
Beispiel #11
0
int cmd_app(struct CONSOLE *cons, int *fat, char *cmdline)
{
	struct MEMMAN *memman = (struct MEMMAN *) MEMMAN_ADDR;
	struct FILEINFO *finfo;
	char name[18], *p, *q;
	struct TASK *task = task_now();
	int i, segsiz, datsiz, esp, dathrb;
	struct SHTCTL *shtctl;
	struct SHEET *sht;

	/* コマンドラインからファイル名を生成 */
	for (i = 0; i < 13; i++) {
		if (cmdline[i] <= ' ') {
			break;
		}
		name[i] = cmdline[i];
	}
	name[i] = 0; /* とりあえずファイル名の後ろを0にする */

	/* ファイルを探す */
	finfo = file_search(name, (struct FILEINFO *) (ADR_DISKIMG + 0x002600), 224);
	if (finfo == 0 && name[i - 1] != '.') {
		/* 見つからなかったので後ろに".HRB"をつけてもう一度探してみる */
		name[i    ] = '.';
		name[i + 1] = 'H';
		name[i + 2] = 'R';
		name[i + 3] = 'B';
		name[i + 4] = 0;
		finfo = file_search(name, (struct FILEINFO *) (ADR_DISKIMG + 0x002600), 224);
	}

	if (finfo != 0) {
		/* ファイルが見つかった場合 */
		p = (char *) memman_alloc_4k(memman, finfo->size);
		file_loadfile(finfo->clustno, finfo->size, p, fat, (char *) (ADR_DISKIMG + 0x003e00));
		if (finfo->size >= 36 && strncmp(p + 4, "Hari", 4) == 0 && *p == 0x00) {
			segsiz = *((int *) (p + 0x0000));
			esp    = *((int *) (p + 0x000c));
			datsiz = *((int *) (p + 0x0010));
			dathrb = *((int *) (p + 0x0014));
			q = (char *) memman_alloc_4k(memman, segsiz);
			task->ds_base = (int) q;
			set_segmdesc(task->ldt + 0, finfo->size - 1, (int) p, AR_CODE32_ER + 0x60);
			set_segmdesc(task->ldt + 1, segsiz - 1,      (int) q, AR_DATA32_RW + 0x60);
			for (i = 0; i < datsiz; i++) {
				q[esp + i] = p[dathrb + i];
			}
			start_app(0x1b, 0 * 8 + 4, esp, 1 * 8 + 4, &(task->tss.esp0));
			shtctl = (struct SHTCTL *) *((int *) 0x0fe4);
			for (i = 0; i < MAX_SHEETS; i++) {
				sht = &(shtctl->sheets0[i]);
				if ((sht->flags & 0x11) == 0x11 && sht->task == task) {
					/* アプリが開きっぱなしにした下じきを発見 */
					sheet_free(sht);	/* 閉じる */
				}
			}
			for (i = 0; i < 8; i++) {	/* クローズしてないファイルをクローズ */
				if (task->fhandle[i].buf != 0) {
					memman_free_4k(memman, (int) task->fhandle[i].buf, task->fhandle[i].size);
					task->fhandle[i].buf = 0;
				}
			}
			timer_cancelall(&task->fifo);
			memman_free_4k(memman, (int) q, segsiz);
		} else {
			cons_putstr0(cons, ".hrb file format error.\n");
		}
		memman_free_4k(memman, (int) p, finfo->size);
		cons_newline(cons);
		return 1;
	}
	/* ファイルが見つからなかった場合 */
	return 0;
}
Beispiel #12
0
//专门运行应用程序的命令函数,根据命令行来判断是哪个应用程序,并且运行它,如果没有找到这个应用程序,就返回0报错
int cmd_app(CONSOLE *console, int *fat, char *cmdline)
{
	MEMMANAGE *memmanage = (MEMMANAGE *)MEMMANAGE_ADDR;
	FILEINFO *finfo;
	SEGMENT_DESCRIPTOR *gdt = (SEGMENT_DESCRIPTOR *)ADR_GDT;
	TASK *task = task_now();
	char name[30], *img_adr, *data_adr;
	int i;
	//根据命令行生成文件名
	for(i = 0; cmdline[i] != 0; i++)
	{
		name[i] = cmdline[i];
	}
	/*
	//这是原版的代码,真心看不懂这是在干啥……所以写成自己的了,上面那个循环就是
	for(i = 0; i < 13; i++)
	{
		if(cmdline[i] <= ' ')
		{
			break;
		}
		name[i] = cmdline[i];
	}
	name[i] = 0;		//字符串结尾必须是0,所以这里手动加上0
	*/
	finfo = file_search(name, (FILEINFO *)(ADR_DISKIMG + 0x002600), 224);
	//如果因为用户输入没有加上后缀名而找不到,就在这里加上后缀名之后再找
	if(finfo == 0 && name[i] != '.')
	{
		name[i] = '.';
		name[i + 1] = 'H';
		name[i + 2] = 'R';
		name[i + 3] = 'B';
		name[i + 4] = 0;
		finfo = file_search(name, (FILEINFO *)(ADR_DISKIMG + 0x002600), 224);
	}
	//找到文件的情况
	if(0 != finfo)
	{
		//文件内容开始的地址赋值给img_adr
		img_adr = (char *)memmanage_alloc_4K(memmanage, finfo->size);
		*((int *) 0xfe8) = (int)img_adr;		//由于在hello2.nas中没有指定段指针,导致读取数据的时候用了DS寄存器,读到了错误的数据,所以这里特别指定一下地址,并存储到指定位置
		data_adr = (char *)memmanage_alloc_4K(memmanage, 64 * 1024);
		//把可能有间断的文件内容复制到一块儿连续的内存中去,这样就可以直接到这块儿内存进行连续的读取了
		file_loadfile(finfo->clusterno, finfo->size, img_adr, fat, (char *)(0x003e00 + ADR_DISKIMG));
		//为这个任务分配一个内存段,将访问权限加上0x60之后,就可以将段设置成为应用程序专用
		set_segmdesc(gdt + 1003, finfo->size - 1, (int)img_adr, AR_CODE32_ER + 0x60);
		//为应用程序分配的数据段
		set_segmdesc(gdt + 1004, 64 * 1024 - 1, (int)data_adr, AR_DATA32_RW + 0x60);
		//如果应用程序是用C语言写的,那么就要在这里把它调整为从HariMain主函数开始运行,改写最初的6个字节即可
		if(finfo->size >= 8 && 0 == strncmp(img_adr + 4, "Hari", 4))
		{
			img_adr[0] = 0xe8;
			img_adr[1] = 0x16;
			img_adr[2] = 0x00;
			img_adr[3] = 0x00;
			img_adr[4] = 0x00;
			img_adr[5] = 0xcb;
		}
		//跳转到这个hlt任务所在的内存开始执行
		start_app(0, 1003 * 8, 64 * 1024, 1004 * 8, &(task->tss.esp0));
		//任务执行完之后就把这块儿内存释放掉
		memmanage_free_4K(memmanage, (int)img_adr, finfo->size);
		memmanage_free_4K(memmanage, (int)data_adr, 64 * 1024);
		console_newline(console);
		return 1;
	}
	//没找到文件的话直接返回0
	return 0;
}
Beispiel #13
0
int cmd_app(struct CONSOLE *cons, int *fat, char *cmdline)
{
	struct MEMMAN *memman = (struct MEMMAN *) MEMMAN_ADDR;
	struct FILEINFO *finfo;
	char name[18], *p, *q;
	struct TASK *task = task_now();
	int i, segsiz, datsiz, esp, dathrb, appsiz;
	struct SHTCTL *shtctl;
	struct SHEET *sht;

	/* Ŀ�ǵ� �������κ��� ���ϸ��� ���� */
	for (i = 0; i < 13; i++) {
		if (cmdline[i] <= ' ') {
			break;
		}
		name[i] = cmdline[i];
	}
	name[i] = 0; /* �켱 ���ϸ��� �ڸ� 0���� �Ѵ� */

	/* ������ �� */
	finfo = file_search(name, (struct FILEINFO *) (ADR_DISKIMG + 0x002600), 224);
	if (finfo == 0 && name[i - 1] != '.') {
		/* �߰ߵ��� �ʾұ� ������ �ڷ� ".HRB"�� �ٿ� �ѹ� �� ã�� ���� */
		name[i    ] = '.';
		name[i + 1] = 'H';
		name[i + 2] = 'R';
		name[i + 3] = 'B';
		name[i + 4] = 0;
		finfo = file_search(name, (struct FILEINFO *) (ADR_DISKIMG + 0x002600), 224);
	}

	if (finfo != 0) {
		/* ������ �߰ߵǾ��� ��� */
		appsiz = finfo->size;
		p = file_loadfile2(finfo->clustno, &appsiz, fat);
		if (appsiz >= 36 && strncmp(p + 4, "Hari", 4) == 0 && *p == 0x00) {
			segsiz = *((int *) (p + 0x0000));
			esp    = *((int *) (p + 0x000c));
			datsiz = *((int *) (p + 0x0010));
			dathrb = *((int *) (p + 0x0014));
			q = (char *) memman_alloc_4k(memman, segsiz);
			task->ds_base = (int) q;
			set_segmdesc(task->ldt + 0, appsiz - 1, (int) p, AR_CODE32_ER + 0x60);
			set_segmdesc(task->ldt + 1, segsiz - 1, (int) q, AR_DATA32_RW + 0x60);
			for (i = 0; i < datsiz; i++) {
				q[esp + i] = p[dathrb + i];
			}
			start_app(0x1b, 0 * 8 + 4, esp, 1 * 8 + 4, &(task->tss.esp0));
			strcpy(task->name, "console");
			shtctl = (struct SHTCTL *) *((int *) 0x0fe4);
			for (i = 0; i < MAX_SHEETS; i++) {
				sht = &(shtctl->sheets0[i]);
				if ((sht->flags & 0x11) == 0x11 && sht->task == task) {
					/* ���ø����̼� open & ���̾� �߰� */
					sheet_free(sht);	/* �ݴ´� */
				}
			}
			for (i = 0; i < 8; i++) {	/* Ŭ�ο��� ���� �ʴ� ������ Ŭ�ο��� */
				if (task->fhandle[i].buf != 0) {
					memman_free_4k(memman, (int) task->fhandle[i].buf, task->fhandle[i].size);
					task->fhandle[i].buf = 0;
				}
			}
			timer_cancelall(&task->fifo);
			memman_free_4k(memman, (int) q, segsiz);
			task->langbyte1 = 0;
		} else {
			cons_putstr0(cons, ".hrb file format error.\n");
		}
		memman_free_4k(memman, (int) p, appsiz);
		cons_newline(cons);
		return 1;
	}
	/* ������ �߰ߵ��� �ʾ��� ��� */
	return 0;
}