示例#1
0
int		fill_tree(t_shell *shell, char *command_line)
{
  t_tree	*up;
  char		**commands;
  int		i;

  if ((commands = my_str_to_wordtab(command_line, " \t")) == NULL)
    return (nothing_more(shell));
  i = -1;
  while (commands != NULL && commands[++i] != NULL)
    {
      if ((is_token(shell->tokens, commands[i]) >= 0) &&
	  ((shell->tree->right = malloc(sizeof(t_tree))) != NULL))
	{
	  shell->tree->token = is_token(shell->tokens, commands[i]);
	  if ((shell->tree->left = get_left(commands, i)) == NULL)
	    return (-1);
	  up = shell->tree;
	  shell->tree = shell->tree->right;
	  shell->tree->up = up;
	  return (fill_tree(shell, new_command(commands, i)));
	}
    }
  return (last_command(shell, commands, i));
}
示例#2
0
void Database::ExecSongTablesCommands(QSqlDatabase& db,
                                      const QStringList& song_tables,
                                      const QStringList& commands) {
    for (const QString& command : commands) {
        // There are now lots of "songs" tables that need to have the same schema:
        // songs, magnatune_songs, and device_*_songs.  We allow a magic value
        // in the schema files to update all songs tables at once.
        if (command.contains(kMagicAllSongsTables)) {
            for (const QString& table : song_tables) {
                // Another horrible hack: device songs tables don't have matching _fts
                // tables, so if this command tries to touch one, ignore it.
                if (table.startsWith("device_") &&
                        command.contains(QString(kMagicAllSongsTables) + "_fts")) {
                    continue;
                }

                qLog(Info) << "Updating" << table << "for" << kMagicAllSongsTables;
                QString new_command(command);
                new_command.replace(kMagicAllSongsTables, table);
                QSqlQuery query(db.exec(new_command));
                if (CheckErrors(query))
                    qFatal("Unable to update music library database");
            }
        } else {
            QSqlQuery query(db.exec(command));
            if (CheckErrors(query)) qFatal("Unable to update music library database");
        }
    }
}
示例#3
0
int
main(int argc, char *argv[])
{
    int ch;
    char buffer[80];
    attr_t underline;
    bool i_option = FALSE;

    setlocale(LC_ALL, "");

    while ((ch = getopt(argc, argv, "i")) != -1) {
	switch (ch) {
	case 'i':
	    i_option = TRUE;
	    break;
	default:
	    usage();
	}
    }

    printf("starting filter program using %s...\n",
	   i_option ? "initscr" : "newterm");
    filter();
    if (i_option) {
	initscr();
    } else {
	(void) newterm((char *) 0, stdout, stdin);
    }
    cbreak();
    keypad(stdscr, TRUE);

    if (has_colors()) {
	int background = COLOR_BLACK;
	start_color();
#if HAVE_USE_DEFAULT_COLORS
	if (use_default_colors() != ERR)
	    background = -1;
#endif
	init_pair(1, COLOR_CYAN, (short) background);
	underline = (attr_t) COLOR_PAIR(1);
    } else {
	underline = A_UNDERLINE;
    }

    while (new_command(buffer, sizeof(buffer) - 1, underline) != ERR
	   && strlen(buffer) != 0) {
	reset_shell_mode();
	printf("\n");
	fflush(stdout);
	IGNORE_RC(system(buffer));
	reset_prog_mode();
	touchwin(stdscr);
	erase();
	refresh();
    }
    printw("done");
    refresh();
    endwin();
    ExitProgram(EXIT_SUCCESS);
}
示例#4
0
static void go_to_dialog(void)
{
    if (read_stdin) return;
    if (delete_input_file() == 0) return;
    read_stdin = 1;
    read_file = 0;
    new_command();
}
示例#5
0
int command_install(struct command_head_t *cmd_head, char *cmd_name, exec_fun_t exec)
{
	int ret = -1;
	struct command_t *cmd;
	cmd = new_command(cmd_name, exec);
	if (cmd)
		ret = command_add(cmd_head, cmd, 0);
	return ret;
}
示例#6
0
void BC_Synchronous::quit()
{
	command_lock->lock("BC_Synchronous::quit");
	BC_SynchronousCommand *command = new_command();
	commands.append(command);
	command->command = BC_SynchronousCommand::QUIT;
	command_lock->unlock();

	next_command->unlock();
}
示例#7
0
/*
** generate exec command
** @params self, parser, request, io
** @return success -> command, error -> false
*/
t_command	*exec_generate(t_schema *self, t_parser *parser, char **request,
				t_io *io)
{
  if (request == NULL || request[0] == NULL)
    {
      fprintf(stderr, "Invalid null command.\n");
      return (NULL);
    }
  return (new_command(request));
  (void)io;
  (void)parser;
  (void)self;
}
示例#8
0
void BC_Synchronous::delete_window(BC_WindowBase *window)
{
#ifdef HAVE_GL
	BC_SynchronousCommand *command = new_command();
	command->command = BC_SynchronousCommand::DELETE_WINDOW;
	command->window_id = window->get_id();
	command->display = window->get_display();
	command->win = window->win;
	command->gl_context = window->gl_win_context;

	send_garbage(command);
#endif
}
示例#9
0
void BC_Synchronous::delete_pixmap(BC_WindowBase *window, 
	GLXPixmap pixmap, 
	GLXContext context)
{
	BC_SynchronousCommand *command = new_command();
	command->command = BC_SynchronousCommand::DELETE_PIXMAP;
	command->window_id = window->get_id();
	command->display = window->get_display();
	command->win = window->win;
	command->gl_pixmap = pixmap;
	command->gl_context = context;

	send_garbage(command);
}
示例#10
0
 void ConsoleWidget::enterClicked()
 {
         static QString console_hide("console hide");
         static QString console_windowmode("console windowmode");
         QString command = input_->text();
         if ( command.compare(console_hide) == 0)
         {
                 this->hide();
                 qDebug() << "Console hidden.";
         }
         else
         if ( command.compare(console_windowmode) == 0)
                 this->setWindowState( this->windowState() ^ Qt::WindowFullScreen );
         else
                 emit new_command( input_->text() );
         //console_->on_new_command(this->input->text());
 }
示例#11
0
int BC_Synchronous::send_command(BC_SynchronousCommand *command)
{
	command_lock->lock("BC_Synchronous::send_command");
	BC_SynchronousCommand *command2 = new_command();
	commands.append(command2);
	command2->copy_from(command);
	command_lock->unlock();

	next_command->unlock();
//printf("BC_Synchronous::send_command 1 %d\n", next_command->get_value());

// Wait for completion
	command2->command_done->lock("BC_Synchronous::send_command");
	int result = command2->result;
	delete command2;
	return result;
}
示例#12
0
文件: main.c 项目: shalvin/itsh
// Takes a tokenized command string and prepares a command structures which are
// then executed.
exec_error prepare_command(int argc, char **cmdTokens) {
    int pipeIndex, argSplit1Len, argSplit2Len;
    char **argSplit1;
    char **argSplit2;
    Command *cmd1;
    Command *cmd2;
    exec_error error = NONE;

    pipeIndex = index_of(cmdTokens, argc, "|");

    if (pipeIndex > 0) {
        // Split arguments into two for each side of the pipe.
        argSplit1Len = pipeIndex;
        argSplit1 = copy_token_array(cmdTokens, argSplit1Len);
        argSplit1[argSplit1Len] = '\0';
        argSplit2Len = argc - pipeIndex - 1;
        argSplit2 = copy_token_array(cmdTokens + pipeIndex + 1, argSplit2Len);
        argSplit2[argSplit2Len] = '\0';
        
        // Prepare input (left) side of pipe. First command will take
        // arguments from left of pipe. REDIRECT_TBA allows fd to be allocated
        // by command_redirect for possible input files. REDIRECT_NONE makes 
        // sure redirection is not done to the output as this will be piped 
        // later.
        cmd1 = new_command(argSplit1Len, argSplit1, REDIRECT_TBA, REDIRECT_NONE);
        error = command_redirect(&cmd1);
        if (error != NONE) {
            free(cmd1);
            return error;
        }

        // Prepare output (right) side of pipe taking the remaining arguments
        // on the RHS of the pipe. REDIRECT constants are switched as this 
        // will be executed on the other half of the pipe.
        cmd2 = new_command(argSplit2Len, argSplit2, REDIRECT_NONE, REDIRECT_TBA);
        error = command_redirect(&cmd2);
        if (error != NONE) {
            free(cmd1);
            free(cmd2);
            return error;
        }

        // Execute piped command
        error = execute_piped(cmd1, cmd2);
        
        free_token_array(&argSplit1, argSplit1Len);
        free_token_array(&argSplit2, argSplit2Len);
    
    } else {
        // No pipe found. Prepare any redirects.
        cmd1 = new_command(argc, cmdTokens, REDIRECT_TBA, REDIRECT_TBA);
        error = command_redirect(&cmd1);

        if (error != NONE) {
            free(cmd1);
            return error;
        }

        error = execute_unpiped(cmd1);
    }

    return error;
}
示例#13
0
ret_code_t cmd_parser(char *mes, int as, int new_cmd, int *redirect)
// as = 0  - get command
// as = 1  - may be exit with empty command
// new_cmd = 1 - new command
// new_cmd = 0 - get added items
//     returned redirect value (for new_cmd = 1):
//   0 - no redirect output
//   1 - redirect to the empty file
//   2 - add output to the existent file
{
    char	*cmd, *str, *beg, *tmp;
    term_t	type;
    int	i;
    char	new_line[LINE_BUF_SIZE];

    *redirect = 0;
    for (;;) {
        if (new_cmd) {
            new_command();
            type = CMD_TERM;
        } else type = ITEM_TERM;
        cmd = get_input_line(mes, new_cmd);
        if (cmd == (char *)NULL) {
            go_to_dialog();
            continue;
        };
        strcpy(new_cmd_line, cmd);
        str = new_cmd_line;
        while (isspace(*str)) str++;
        if (strlen(str) == 0) {
            if (as) return HPI_SHELL_OK;
            continue;
        };
        beg = str;
        if (*beg == '#') continue;
        while (*str != 0) {
            if (isspace(*str)) {
                *str++ = 0;
                if (strlen(beg) > 0) {
                    add_term(beg, type);
                    type = ITEM_TERM;
                };
                while (isspace(*str)) str++;
                add_to_cmd_line(beg);
                beg = str;
                continue;
            };
            if (*str == '\"') {
                str++;
                while ((*str != 0) && (*str != '\"')) str ++;
                if (*str == 0) {
                    add_to_cmd_line(beg);
                    add_term(beg, type);
                    if (read_file)
                        add_term(";", CMD_ERROR_TERM);
                    break;
                };
                if (*beg == '\"') {
                    beg++;
                    *str = 0;
                    add_term(beg, type);
                    type = ITEM_TERM;
                    add_to_cmd_line(beg);
                    beg = str + 1;
                };
                str++;
                continue;
            };
            if (*str == '>') {
                *str++ = 0;
                if (strlen(beg) > 0) {
                    add_to_cmd_line(beg);
                    add_term(beg, type);
                };
                if (*str == '>') {
                    add_to_cmd_line(">>");
                    add_term(">>", CMD_REDIR_TERM);
                    str++;
                } else {
                    add_to_cmd_line(">");
                    add_term(">", CMD_REDIR_TERM);
                };
                type = ITEM_TERM;
                beg = str;
                continue;
            };
            if ((*str == '!') && read_stdin) {
                if (str[1] == '!') {
                    i = 2;
                    tmp = get_last_history();
                } else {
                    i = 1;
                    tmp = get_def_history(str + 1, &i);
                };
                if (tmp == (char *)NULL) {
                    str += i;
                    continue;
                };
                *str = 0;
                str += i;
                snprintf(new_line, LINE_BUF_SIZE, "%s%s%s", beg, tmp, str);
                str = new_cmd_line + strlen(beg);
                strcpy(new_cmd_line, new_line);
                beg = new_cmd_line;
                continue;
            };
            if (*str == ';') {
                *str++ = 0;
                add_to_cmd_line(beg);
                break;
            };
            str++;
        };
        if (strlen(beg) > 0) {
            add_to_cmd_line(beg);
            add_term(beg, type);
        };
        if (read_file)
            add_term(";", CMD_END_TERM);
        if (read_stdin) set_current_history(cmd_line);
        if (new_cmd == 0)
            return(HPI_SHELL_OK);
        *redirect = check_cmd_for_redirect();
        return(HPI_SHELL_OK);
    }
}
示例#14
0
文件: zedit.c 项目: vedicveko/Aarait
void zedit_parse(struct descriptor_data *d, char *arg)
{
  int pos, i = 0;

  switch (OLC_MODE(d)) {
/*-------------------------------------------------------------------*/
  case ZEDIT_CONFIRM_SAVESTRING:
    switch (*arg) {
    case 'y':
    case 'Y':
      /*
       * Save the zone in memory, hiding invisible people.
       */
      SEND_TO_Q("Saving zone info in memory.\r\n", d);
      zedit_save_internally(d);
      sprintf(buf, "OLC: %s edits zone info for room %d.", GET_NAME(d->character), OLC_NUM(d));
      mudlog(buf, CMP, MAX(LVL_BUILDER, GET_INVIS_LEV(d->character)), TRUE);
      /* FALL THROUGH */
    case 'n':
    case 'N':
      cleanup_olc(d, CLEANUP_ALL);
      break;
    default:
      SEND_TO_Q("Invalid choice!\r\n", d);
      SEND_TO_Q("Do you wish to save the zone info? : ", d);
      break;
    }
    break;
   /* End of ZEDIT_CONFIRM_SAVESTRING */

/*-------------------------------------------------------------------*/
  case ZEDIT_MAIN_MENU:
    switch (*arg) {
    case 'q':
    case 'Q':
      if (OLC_ZONE(d)->age || OLC_ZONE(d)->number) {
	SEND_TO_Q("Do you wish to save the changes to the zone info? (y//n) : ", d);
	OLC_MODE(d) = ZEDIT_CONFIRM_SAVESTRING;
      } else {
	SEND_TO_Q("No changes made.\r\n", d);
	cleanup_olc(d, CLEANUP_ALL);
      }
      break;
    case 'n':
    case 'N':
      /*
       * New entry.
       */
      SEND_TO_Q("What number in the list should the new command be? : ", d);
      OLC_MODE(d) = ZEDIT_NEW_ENTRY;
      break;
    case 'e':
    case 'E':
      /*
       * Change an entry.
       */
      SEND_TO_Q("Which command do you wish to change? : ", d);
      OLC_MODE(d) = ZEDIT_CHANGE_ENTRY;
      break;
    case 'd':
    case 'D':
      /*
       * Delete an entry.
       */
      SEND_TO_Q("Which command do you wish to delete? : ", d);
      OLC_MODE(d) = ZEDIT_DELETE_ENTRY;
      break;
    case 'z':
    case 'Z':
      /*
       * Edit zone name.
       */
      SEND_TO_Q("Enter new zone name : ", d);
      OLC_MODE(d) = ZEDIT_ZONE_NAME;
      break;
    case 't':
    case 'T':
      /*
       * Edit top of zone.
       */
      if (GET_LEVEL(d->character) < LVL_IMPL)
	zedit_disp_menu(d);
      else {
	SEND_TO_Q("Enter new top of zone : ", d);
	OLC_MODE(d) = ZEDIT_ZONE_TOP;
      }
      break;
    case 'l':
    case 'L':
      /*
       * Edit zone lifespan.
       */
      SEND_TO_Q("Enter new zone lifespan : ", d);
      OLC_MODE(d) = ZEDIT_ZONE_LIFE;
      break;
    case 'r':
    case 'R':
      /*
       * Edit zone reset mode.
       */
      SEND_TO_Q("\r\n"
		"0) Never reset\r\n"
		"1) Reset only when no players in zone\r\n"
		"2) Normal reset\r\n"
		"Enter new zone reset type : ", d);
      OLC_MODE(d) = ZEDIT_ZONE_RESET;
      break;
    default:
      zedit_disp_menu(d);
      break;
    }
    break;
    /* End of ZEDIT_MAIN_MENU */

/*-------------------------------------------------------------------*/
  case ZEDIT_NEW_ENTRY:
    /*
     * Get the line number and insert the new line.
     */
    pos = atoi(arg);
    if (isdigit(*arg) && new_command(OLC_ZONE(d), pos)) {
      if (start_change_command(d, pos)) {
	zedit_disp_comtype(d);
	OLC_ZONE(d)->age = 1;
      }
    } else
      zedit_disp_menu(d);
    break;

/*-------------------------------------------------------------------*/
  case ZEDIT_DELETE_ENTRY:
    /*
     * Get the line number and delete the line.
     */
    pos = atoi(arg);
    if (isdigit(*arg)) {
      delete_command(OLC_ZONE(d), pos);
      OLC_ZONE(d)->age = 1;
    }
    zedit_disp_menu(d);
    break;

/*-------------------------------------------------------------------*/
  case ZEDIT_CHANGE_ENTRY:
    /*
     * Parse the input for which line to edit, and goto next quiz.
     */
    pos = atoi(arg);
    if (isdigit(*arg) && start_change_command(d, pos)) {
      zedit_disp_comtype(d);
      OLC_ZONE(d)->age = 1;
    } else
      zedit_disp_menu(d);
    break;

/*-------------------------------------------------------------------*/
  case ZEDIT_COMMAND_TYPE:
    /*
     * Parse the input for which type of command this is, and goto next
     * quiz.
     */
    OLC_CMD(d).command = toupper(*arg);
    if (!OLC_CMD(d).command || (strchr("MOPEDGR", OLC_CMD(d).command) == NULL)) {
      SEND_TO_Q("Invalid choice, try again : ", d);
    } else {
      if (OLC_VAL(d)) {	/* If there was a previous command. */
	SEND_TO_Q("Is this command dependent on the success of the previous one? (y//n)\r\n", d);
	OLC_MODE(d) = ZEDIT_IF_FLAG;
      } else {	/* 'if-flag' not appropriate. */
	OLC_CMD(d).if_flag = 0;
	zedit_disp_arg1(d);
      }
    }
    break;

/*-------------------------------------------------------------------*/
  case ZEDIT_IF_FLAG:
    /*
     * Parse the input for the if flag, and goto next quiz.
     */
    switch (*arg) {
    case 'y':
    case 'Y':
      OLC_CMD(d).if_flag = 1;
      break;
    case 'n':
    case 'N':
      OLC_CMD(d).if_flag = 0;
      break;
    default:
      SEND_TO_Q("Try again : ", d);
      return;
    }
    zedit_disp_arg1(d);
    break;

/*-------------------------------------------------------------------*/
  case ZEDIT_ARG1:
    /*
     * Parse the input for arg1, and goto next quiz.
     */
    if (!isdigit(*arg)) {
      SEND_TO_Q("Must be a numeric value, try again : ", d);
      return;
    }
    switch (OLC_CMD(d).command) {
    case 'M':
      if ((pos = real_mobile(atoi(arg))) >= 0) {
	OLC_CMD(d).arg1 = pos;
	zedit_disp_arg2(d);
      } else
	SEND_TO_Q("That mobile does not exist, try again : ", d);
      break;
    case 'O':
    case 'P':
    case 'E':
    case 'G':
      if ((pos = real_object(atoi(arg))) >= 0) {
	OLC_CMD(d).arg1 = pos;
	zedit_disp_arg2(d);
      } else
	SEND_TO_Q("That object does not exist, try again : ", d);
      break;
    case 'D':
    case 'R':
    default:
      /*
       * We should never get here.
       */
      cleanup_olc(d, CLEANUP_ALL);
      mudlog("SYSERR: OLC: zedit_parse(): case ARG1: Ack!", BRF, LVL_BUILDER, TRUE);
      SEND_TO_Q("Oops...\r\n", d);
      break;
    }
    break;

/*-------------------------------------------------------------------*/
  case ZEDIT_ARG2:
    /*
     * Parse the input for arg2, and goto next quiz.
     */
    if (!isdigit(*arg)) {
      SEND_TO_Q("Must be a numeric value, try again : ", d);
      return;
    }
    switch (OLC_CMD(d).command) {
    case 'M':
    case 'O':
      OLC_CMD(d).arg2 = atoi(arg);
      OLC_CMD(d).arg3 = real_room(OLC_NUM(d));
      zedit_disp_arg4(d);
      break;
    case 'G':
      OLC_CMD(d).arg2 = atoi(arg);
      zedit_disp_arg4(d);
      break;
    case 'P':
    case 'E':
      OLC_CMD(d).arg2 = atoi(arg);
      zedit_disp_arg3(d);
      break;
    case 'D':
      pos = atoi(arg);
      /*
       * Count directions.
       */
      if (pos < 0 || pos > NUM_OF_DIRS)
	SEND_TO_Q("Try again : ", d);
      else {
	OLC_CMD(d).arg2 = pos;
	zedit_disp_arg3(d);
      }
      break;
    case 'R':
      if ((pos = real_object(atoi(arg))) >= 0) {
	OLC_CMD(d).arg2 = pos;
	zedit_disp_menu(d);
      } else
	SEND_TO_Q("That object does not exist, try again : ", d);
      break;
    default:
      /*
       * We should never get here, but just in case...
       */
      cleanup_olc(d, CLEANUP_ALL);
      mudlog("SYSERR: OLC: zedit_parse(): case ARG2: Ack!", BRF, LVL_BUILDER, TRUE);
      SEND_TO_Q("Oops...\r\n", d);
      break;
    }
    break;

/*-------------------------------------------------------------------*/
  case ZEDIT_ARG3:
    /*
     * Parse the input for arg3, and goto arg4's menu.
     */
    if (!isdigit(*arg)) {
      SEND_TO_Q("Must be a numeric value, try again : ", d);
      return;
    }
    switch (OLC_CMD(d).command) {
    case 'E':
      pos = atoi(arg);
      /*
       * Count number of wear positions.  We could use NUM_WEARS, this is
       * more reliable.
       */
      while (*equipment_types[i] != '\n')
	i++;
      if (pos < 0 || pos > i)
	SEND_TO_Q("Try again : ", d);
      else {
	OLC_CMD(d).arg3 = pos;
        zedit_disp_arg4(d);
      }
      break;
    case 'P':
      if ((pos = real_object(atoi(arg))) >= 0) {
	OLC_CMD(d).arg3 = pos;
        zedit_disp_arg4(d);
      } else
	SEND_TO_Q("That object does not exist, try again : ", d);
      break;
    case 'D':
      pos = atoi(arg);
      if (pos < 0 || pos > 2)
	SEND_TO_Q("Try again : ", d);
      else {
	OLC_CMD(d).arg3 = pos;
        zedit_disp_arg4(d);
      }
      break;
    case 'M':
    case 'O':
    case 'G':
    case 'R':
    default:
      /*
       * We should never get here, but just in case...
       */
      cleanup_olc(d, CLEANUP_ALL);
      mudlog("SYSERR: OLC: zedit_parse(): case ARG3: Ack!", BRF, LVL_BUILDER, TRUE);
      SEND_TO_Q("Oops...\r\n", d);
      break;
    }
    break;

  case ZEDIT_ARG4:
    /*
     * Parse the input for arg4, and go back to main menu.
     */
    if (!isdigit(*arg)) {
      SEND_TO_Q("Must be a numeric value, try again : ", d);
      return;
    }
    switch (OLC_CMD(d).command) {
    case 'M':
    case 'O':
    case 'G':
    case 'E':
      pos = atoi(arg);
      if (pos < 0 || pos > 100)
        SEND_TO_Q("Try again : ", d);
      else {
        OLC_CMD(d).arg4 = pos;
        zedit_disp_menu(d);
      }
      break;

    case 'P':
    case 'D':
        OLC_CMD(d).arg3 = 100;
      break;

    default:
      /*

       * We should never get here, but just in case...
       */
      cleanup_olc(d, CLEANUP_ALL);
      mudlog("SYSERR: OLC: zedit_parse(): case ARG3: Ack!", BRF, LVL_BUILDER, TRUE);
      SEND_TO_Q("Oops...\r\n", d);
      break;
    }
    break;


/*-------------------------------------------------------------------*/
  case ZEDIT_ZONE_NAME:
    /*
     * Add new name and return to main menu.
     */
    if (genolc_checkstring(d, arg)) {
      if (OLC_ZONE(d)->name)
        free(OLC_ZONE(d)->name);
      else
        log("SYSERR: OLC: ZEDIT_ZONE_NAME: no name to free!");
      OLC_ZONE(d)->name = str_dup(arg);
      OLC_ZONE(d)->number = 1;
    }
    zedit_disp_menu(d);
    break;

/*-------------------------------------------------------------------*/
  case ZEDIT_ZONE_RESET:
    /*
     * Parse and add new reset_mode and return to main menu.
     */
    pos = atoi(arg);
    if (!isdigit(*arg) || pos < 0 || pos > 2)
      SEND_TO_Q("Try again (0-2) : ", d);
    else {
      OLC_ZONE(d)->reset_mode = pos;
      OLC_ZONE(d)->number = 1;
      zedit_disp_menu(d);
    }
    break;

/*-------------------------------------------------------------------*/
  case ZEDIT_ZONE_LIFE:
    /*
     * Parse and add new lifespan and return to main menu.
     */
    pos = atoi(arg);
    if (!isdigit(*arg) || pos < 0 || pos > 240)
      SEND_TO_Q("Try again (0-240) : ", d);
    else {
      OLC_ZONE(d)->lifespan = pos;
      OLC_ZONE(d)->number = 1;
      zedit_disp_menu(d);
    }
    break;

/*-------------------------------------------------------------------*/
  case ZEDIT_ZONE_TOP:
    /*
     * Parse and add new top room in zone and return to main menu.
     */
    if (OLC_ZNUM(d) == top_of_zone_table)
      OLC_ZONE(d)->top = LIMIT(atoi(arg), OLC_ZNUM(d) * 100, 32000);
    else
      OLC_ZONE(d)->top = LIMIT(atoi(arg), OLC_ZNUM(d) * 100, zone_table[OLC_ZNUM(d) + 1].number * 100);
    zedit_disp_menu(d);
    break;

/*-------------------------------------------------------------------*/
  default:
    /*
     * We should never get here, but just in case...
     */
    cleanup_olc(d, CLEANUP_ALL);
    mudlog("SYSERR: OLC: zedit_parse(): Reached default case!", BRF, LVL_BUILDER, TRUE);
    SEND_TO_Q("Oops...\r\n", d);
    break;
  }
}
示例#15
0
/*------------------------------------------------------*/
void		LoadFromPc(char *p)
			{
			void	InProg(void);
			int		ReadPar(char *);

			char	q[LINK_LEN],*r,*s,*ss[16];
			int		i,j,k;
			long	y,z;
			lib		*l;
			command	*c,**cp;

			switch(*p)
			{
			case 'd':
				Lr=scanLLA(Lr,++p,null);
				if(!Lr)
				{
					j=0;
					switch(strscan(p,ss,',',16))
					{
					case 2:
						j=atoi(ss[1]);
					case 1:
						if(l=FindLib(LinkAddrStr(ss[0])))
						{
							copylib(l,Lr=makelib());
							if(j)
								for(Lr->xc=Lr->x; --j && Lr->xc->next;)
									Lr->xc=Lr->xc->next;
							else
								Lr->x=Lr->xc=freecoord(Lr->x);
							Ungetch(REFRESH,0);
						}
						else
							puts_pc("!NOT_FOUND\r\n");
						break;
					default:
						puts_pc("!SYNTAX\r\n");
						break;
					}
				}
				break;

				case 'l':	if(i=LinkAddrStr(++p)) 
							{
								freelib(Lc);
								Lc=makelib();
								Lc->ltype=LinkAddrType(i);
								Lc->n=LinkAddrN(i);
								}
							else
								InsertLib(&Lc);
							break;

				case 'M':	if(sscanf(++p," %d,%04X,%04X,%s",&k,&i,&j,q)==4) {
                                if(Mscan)
/* znak, da je editor odprt ! */   	if(Mscan->c->maxopt) {
/* vrstica in obseg aktivna ? */		if(k)
											if(--k <= Mscan->c->maxopt) {
												Mscan->active = k;
        	       		                    	Refresh();
            	           		            	}
                                   		break;
                                    	}
                                r=strchr(q,',');
                                *r++=0;
                                cp=NULL;
                                if(!strcmp(q,"message"))
                                	cp=&CP;
                               	if(!strcmp(q,"gun"))
                               		cp=&GUN;
								if(!strcmp(q,"meteo"))
                                	cp=&METEO;
                                if(!cp)
                                	break;
/*......................................................................................*/
	                            if(!*cp)
                                	new_command(cp);
                                else{
	                               	c=*cp;
									do
										if(c->chk == j)
											*cp=c;
										else
											c=c->next;
									while(c != *cp);
									if((*cp)->chk != j)
										new_command(cp);
            						}
								(*cp)->chk=j;
                                c=*cp;
                                s=(char *)c;
								i = sizeof(command) - sizeof(command *) - sizeof(int);
								while(i--) {
					 				sscanf(r,"%02X",&j);
                                    *s++ = j;
									++r;++r;
									}
                                c->chk *= -1;
								if(cp == &CP)
									Ungetch(GXM_MESSAGE_ID,0);
								if(cp == &GUN)
									Ungetch(GXM_GUN_ID,0);
								}
							break;
				case 'r':   if(crest && (sscanf(++p," %ld %ld",&y,&z) == 2)) {
								add_coord(crest,0,y,z);
								crest->xc->refp=null;
								}
							else
								DeleteTask(DMRtimeout,RTC_task);
							break;

				case 'c':   i=j=0;
							if(Lc)
								Lc=scanLLA(Lc,++p,eof);
							break;
				case 'g':	if(Lc && (sscanf(++p," %s %d %d",q,&j,&k) == 3)) {
							for(i=0; Guns[i].name; ++i)
								if(!strcmp(Guns[i].name,q)) {
									Lc->gun=i;
									Lc->refd=j;
									Lc->powder=k;
									}
								}
							break;
				case 'a':	if(Lc && (sscanf(++p,"%s %d",q,&j) == 2)) {
								for(i=0; Guns[Lc->gun].ammo[i]; ++i)
									if(!strcmp(Guns[Lc->gun].ammo[i],q)) {
										Lc->ammpcs[i]=j;
										r=strchr(p,'+');
										s=strrchr(p,'+');
										if(r)
											do	Lc->ammpcs[i] += 0x1000;
													while(r++ != s);
										r=strchr(p,'-');
										s=strrchr(p,'-');
										if(r)
											do	Lc->ammpcs[i] -= 0x1000;
													while(r++ != s);
										}
								}
							break;
				case 'p':	if(sscanf(++p,"%d,%d",&i,&j) == 2)
								if(i<12 && j<4) {
									xyLCD(i,j);
									Ungetch(GXM_CURSOR_POS,0);
									}
							break;

				case 'm':	LoadHexRec(p,'m',_MenuCode);
							break;
				case 'h':	LoadHexRec(p,'h',_MenuHead);
							break;
				case 't':	if(Lc)
							{
								++p;
								++p;
								Lc->txt=addtxt(Lc,p);
							}
							else
								LoadHexRec(p,'t',_TextCode);
							break;

				case 'T':	if(sscanf(++p," %x %x",&i,&j)==2)
							{
							sprintf(q,"%04X\r\n",readTEMP(i,j));
							puts_pc(q);
							}
							break;

				case 'f':   if(ReadPar(++p))
								break;
							i=strscan(p,ss,' ',16);
							if(i>=2)
							{
								sscanf(ss[0],"%lx",&eebott);
								sscanf(ss[1],"%lx",&eetop);
								if(eebott < (long)FLASHTOP)
								{
									puts_pc("!ILL_ADDRESS\r\n");
									break;
								}
								if(eetop > (long)FLASHTOP+0x80000L)
								{
									puts_pc("!ILL_ADDRESS\r\n");
									break;
								}
								if(i==3)
								{
									ss[2][8]=0;
									sprintf(pass,"%-8s",ss[2]);
								}
								if(CheckPass(&syspass))
								{
									puts_pc("!NOT_ALLOWED\r\n");
									break;
								}
								puts_pc("\7\r\nFLASH programming !!!\r\n");
								wait(50);
								InProg();
								puts_pc("Done\r\n");
							}
							else
								puts_pc("!SYNTAX\r\n");
							break;
				case 'b':	k=sscanf(++p," %d %d",&i,&j);
							if(k)
								if(Baud(CHPC,i)) {
									if(k==2)
										Xonoff(j);
									break;
									}
							puts_pc("!SYNTAX\r\n");
							break;

				case 'z':	EnterZone(++p);
							break;

				case 'G':	DeleteTask(ReadPc,RTC_task);
							Guns=ReadGunData(0,0,0,0,NULL);
							SetTask(ReadPc,0,RTC_task);
							break;
				default:	puts_pc("!SYNTAX\r\n");
							break;
				}
			}
示例#16
0
static void parse_args(int argc, char **argv) {

	int i;
	char *arg;

	for (i=1; i < argc; i++) {

		arg = argv[i];

		if (!strcmp(arg, "--config") || !strcmp(arg, "-c")) {
			if (!configfile)
				configfile = strdup(argv[i+1]);

			i++;
			continue;
		} else if (!strcmp(arg, "--configdir") || !strcmp(arg, "-C")) {
			if (!configdir)
				configdir = strdup(argv[i+1]);

			i++;
			continue;
		} else if (!strcmp(arg, "--syncgroup")) {
			if (!syncgroup)
				syncgroup = strdup(argv[i+1]);
			i++;
			continue;
		} else if (!strcmp(arg, "--plugin") || !strcmp(arg, "-p")) {
			if (!pluginname)
				pluginname = strdup(argv[i+1]);

			i++;
			continue;
		} else if (!strcmp(arg, "--pluginpath") || !strcmp(arg, "-P")) {
			if (!pluginpath)
				pluginpath = strdup(argv[i+1]);

			i++;
			continue;
		} else if (!strcmp(arg, "--pluginlist") || !strcmp(arg, "-L")) {
			pluginlist= TRUE;

			i++;
			continue;
		} else if (!strcmp(arg, "--formatpath") || !strcmp(arg, "-F")) {
			if (!formatpath)
				formatpath = strdup(argv[i+1]);

			i++;
			continue;
		} else if (!strcmp(arg, "--initialize")) {
			new_command(CMD_INITIALIZE, NULL);
			continue;
		} else if (!strcmp(arg, "--connect")) {
			if (!argv[i+1] || *argv[i+1] == '-')
				new_command(CMD_CONNECT, NULL);
			else
				new_command(CMD_CONNECT, argv[++i]);

			continue;
		} else if (!strcmp(arg, "--disconnect")) {
			if (!argv[i+1] || *argv[i+1] == '-')
				new_command(CMD_DISCONNECT, NULL);
			else
				new_command(CMD_DISCONNECT, argv[++i]);

			continue;
		} else if (!strcmp(arg, "--finalize")) {
			new_command(CMD_FINALIZE, NULL);
			continue;
		} else if (!strcmp(arg, "--slowsync")) {
			if (!argv[i+1] || *argv[i+1] == '-')
				new_command(CMD_SLOWSYNC, NULL);
			else
				new_command(CMD_SLOWSYNC, argv[++i]);

			continue;
		} else if (!strcmp(arg, "--sync")) {
			if (!argv[i+1] || *argv[i+1] == '-')
				new_command(CMD_SYNC, NULL);
			else
				new_command(CMD_SYNC, argv[++i]);

			continue;
		} else if (!strcmp(arg, "--fastsync")) {
			if (!argv[i+1] || *argv[i+1] == '-')
				new_command(CMD_FASTSYNC, NULL);
			else
				new_command(CMD_FASTSYNC, argv[++i]);

			continue;
		} else if (!strcmp(arg, "--syncdone")) {
			if (!argv[i+1] || *argv[i+1] == '-')
				new_command(CMD_SYNCDONE, NULL);
			else
				new_command(CMD_SYNCDONE, argv[++i]);

			continue;
		} else if (!strcmp(arg, "--committedall")) {
			if (!argv[i+1] || *argv[i+1] == '-')
				new_command(CMD_COMMITTEDALL, NULL);
			else
				new_command(CMD_COMMITTEDALL, argv[++i]);

			continue;
		} else if (!strcmp(arg, "--commit")) {
			if (!argv[i+1] || *argv[i+1] == '-')
				new_command(CMD_COMMIT, NULL);
			else
				new_command(CMD_COMMIT, argv[++i]);

			continue;
		} else if (!strcmp(arg, "--write")) {
			if (!argv[i+1] || *argv[i+1] == '-')
				new_command(CMD_WRITE, NULL);
			else
				new_command(CMD_WRITE, argv[++i]);

			continue;
		} else if (!strcmp(arg, "--read")) {
			if (!argv[i+1] || *argv[i+1] == '-')
				new_command(CMD_READ, NULL);
			else
				new_command(CMD_READ, argv[++i]);

			continue;
		} else if (!strcmp(arg, "--discover")) {
			if (!argv[i+1] || *argv[i+1] == '-')
				new_command(CMD_DISCOVER, NULL);
			else
				new_command(CMD_DISCOVER, argv[++i]);

			continue;
		} else if (!strcmp(arg, "--empty")) {
			if (!argv[i+1] || *argv[i+1] == '-')
				new_command(CMD_EMPTY, NULL);
			else
				new_command(CMD_EMPTY, argv[++i]);

			continue;
		} else {
			fprintf(stderr, "Unknown argument: %s\n", argv[i]);
			usage(argv[0]);
		}
	}
	
	if (pluginlist)
		return;

	if (!cmdlist)
		fprintf(stderr, "No command set.\n");

	if (!pluginname)
		fprintf(stderr, "No plugin set.\n");

	if (!configdir)
		fprintf(stderr, "No working/configuraiton directory set.\n");

	if (!pluginname || !cmdlist || !configdir)
		usage(argv[0]);
}
示例#17
0
void handle_control_session(int fd, int code, void *data) {
  int ret;
  control_state *sess = (control_state *)data;

  switch(sess->state) {
    case READ_FD:
      switch(sess->operation) {
        case READ_COMMAND:
	  ret = read(fd, &sess->operation, 1);
	  if(ret == 0) goto close_clean;
	  if(ret < 0) {
	    if(errno == EAGAIN || errno == EWOULDBLOCK)
	      return;
	    goto error;
	  }
	  if(new_command(sess)) goto error;
	  if(set_event_mask(fd, sess)) goto error;
	  break;
	default:
	  goto error;
      }
      break;
    case WRITE_FD:
      switch(sess->operation) {
	case GET_WACK_STATE:
	  ret = write(fd, sess->data.writing.buffer+sess->data.writing.written,
		    sess->data.writing.size-sess->data.writing.written);
	  if(ret == 0) goto error;
	  if(ret<0) {
	    if(errno == EAGAIN || errno == EWOULDBLOCK)
              return;
            goto error;
	  }
	  sess->data.writing.written += ret;
	  if(sess->data.writing.written == sess->data.writing.size) {
	    free(sess->data.writing.buffer);
	    sess->operation = READ_COMMAND;
	    sess->state = READ_FD;
	    if(set_event_mask(fd, sess)) goto error;
	  }
	  break;
	case WACK_SERVICE_FAILURE:
	case WACK_SERVICE_SUCCESS:
	  ret = write(fd, &sess->data.retint, sizeof(int));
	  if(ret == 0) goto error;
	  if(ret<0) {
	    if(errno == EAGAIN || errno == EWOULDBLOCK)
              return;
            goto error;
          }
          if(ret != sizeof(int)) goto error;
	  sess->operation = READ_COMMAND;
	  sess->state = READ_FD;
	  if(set_event_mask(fd, sess)) goto error;
	  break;
	default:
	  goto error;
      }
      break;
    default:
      goto error;
  }
  return;
error:
  wack_alarm(PRINT, "control session error: [fd=%d] %s\n\tState=%d, Operation=%d",
	fd, strerror(errno), sess->state, sess->operation);
close_clean:
  E_detach_fd(fd, READ_FD);
  E_detach_fd(fd, WRITE_FD);
  free(sess);
  close(fd);
}
示例#18
0
/*
 * Main program
 */
int main(int argc, char **argv) {
    int sock_fd, serv_len, n;
    struct sockaddr_in serv_addr;
    struct hostent *serv;

    struct {
        char message[BUFFER];
        int uuid;
    } msg_in, msg_out;

    /* Generate a random UUID */
    srand(time(NULL));
    uuid = rand();

    clearScreen();

    char *input;
    command *cmd;
    size_t buffer = BUFFER;
    while (TRUE) {
        /* Display prompt */
        printPrompt();

        /* malloc input to memory */
        input = (char *)malloc(sizeof(char) * BUFFER);

        /* Clear msg_in and msg_out */
        bzero((char *)msg_in.message, sizeof(msg_in.message));
        bzero((char *)msg_out.message, sizeof(msg_out.message));
        msg_in.uuid = -1;
        msg_out.uuid = uuid;

        /* Get input */
        getline(&input, &buffer, stdin);
        input[strcspn(input, "\n")] = '\0'; //Remove trailing '\n'

        /* Create command */
        cmd = new_command(input);

        /* Output redirection */
        int file_out, con_out;
        if (cmd->output_file) {
            file_out = open(cmd->output_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
            if (file_out < 0) {
                perror("open");
                break;
            }
            con_out = dup(STDOUT_FILENO);
            dup2(file_out, STDOUT_FILENO);
            close(file_out);
        }

        /* Execute user command if possible */
        switch (check_command(cmd->name)) {
            case HELP: //help
                printHelp();
                break;
            case FMOUNT: //fmount
                if (serv_uuid != -1) {
                    printf("[ERROR] You are already connected to a server\n");
                    break;
                }
                if (cmd->argc != 2) {
                    printf("[ERROR] Usage: fmount <server>\n");
                    break;
                }

                printf("Connecting to `%s`... ", cmd->argv[1]);
                fflush(stdout); //Safety precaution

                /* Parse server */
                serv = gethostbyname(cmd->argv[1]);

                /* Open UDP socket */
                sock_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
                if (sock_fd < 0) {
                    perror("socket");
                    break;
                }

                /* Write zero's to serv_addr */
                bzero((char *)&serv_addr, sizeof(serv_addr));

                /* Set up server */
                serv_addr.sin_family = AF_INET;
                bcopy(serv->h_addr, (char *)&serv_addr.sin_addr, serv->h_length);
                serv_addr.sin_port = htons(PORT);
                serv_len = sizeof(serv_addr);

                /* Send CONNECT command to server */
                sprintf(msg_out.message, "CONNECT");
                n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                if (n < 0) {
                    perror("sendto");
                    break;
                }

                /* Get response from server */
                n = recvfrom(sock_fd, &msg_in, sizeof(msg_in), 0, (struct sockaddr *)&serv_addr, (socklen_t *)&serv_len);
                if (n < 0) {
                    perror("recvfrom");
                    break;
                }

                if (strcmp(msg_in.message, "CONNECT") != 0) {
                    printf("[ERROR] Invalid response from server\n");
                    break;
                }

                /* Save server UUID */
                serv_uuid = msg_in.uuid;

                /* Clear msg_in and msg_out */
                bzero((char *)&msg_out.message, sizeof(msg_out.message));
                bzero((char *)&msg_in.message, sizeof(msg_in.message));
                msg_out.uuid = uuid;
                msg_in.uuid = -1;

                /* Get SECTOR 0 from server */
                sprintf(msg_out.message, "GETSECTOR 0");
                n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                if (n < 0) {
                    perror("sendto");
                    break;
                }

                /* Get response from server */
                n = recvfrom(sock_fd, &msg_in, sizeof(msg_in), 0, (struct sockaddr *)&serv_addr, (socklen_t *)&serv_len);
                if (n < 0) {
                    perror("recvfrom");
                    break;
                }

                /* Load bytes into Fat12Boot */
                load_boot((unsigned char *)msg_in.message);

                /* malloc Fat12Entry */
                entry = (Fat12Entry *)malloc(sizeof(Fat12Entry) * boot.MAX_ROOT_DIRS);

                /* Request all ROOT_DIRECTORY sector entries */
                for (int i = 0; i < 14; i++) {
                    /* Clear msg_in and msg_out */
                    bzero((char *)&msg_out.message, sizeof(msg_out.message));
                    bzero((char *)&msg_in.message, sizeof(msg_in.message));
                    msg_out.uuid = uuid;
                    msg_in.uuid = -1;

                    /* Get ROOT DIRECTORY sector from server */
                    sprintf(msg_out.message, "GETSECTOR %d", ((boot.NUM_OF_FATS * boot.SECTORS_PER_FAT) + 1) + i);
                    n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                    if (n < 0) {
                        perror("sendto");
                        break;
                    }

                    /* Get response from server */
                    n = recvfrom(sock_fd, &msg_in, sizeof(msg_in), 0, (struct sockaddr *)&serv_addr, (socklen_t *)&serv_len);
                    if (n < 0) {
                        perror("recvfrom");
                        break;
                    }

                    /* Load bytes into Fat12Entry */
                    load_entry(16 * i, (unsigned char *)msg_in.message);
                }

                printf("Connected!\n");
                break;

            case FUMOUNT: //fumount
                if (serv_uuid == -1) {
                    printf("[ERROR] You are not connected to any server\n");
                    break;
                }
                if (cmd->argc != 1) {
                    printf("[ERROR] Usage: fumount\n");
                    break;
                }

                sprintf(msg_out.message, "DISCONNECT");
                n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                if (n < 0) {
                    perror("sendto");
                    break;
                }

                /* Close and write zero's to server */
                close(sock_fd);
                bzero((char *)&serv_addr, sizeof(serv_addr));
                serv_uuid = -1;
                break;

            case STRUCTURE: //structure
                if (serv_uuid == -1) {
                    printf("[ERROR] You are not connected to any server\n");
                    break;
                }
                if (cmd->argc > 2) {
                    printf("[ERROR] Usage: structure [-l]\n");
                    break;
                } else if (cmd->argc == 2) {
                    if (strcmp(cmd->argv[1], "-l") != 0) {
                        printf("[ERROR] Usage: structure [-l]\n");
                        break;
                    }
                }

                printf("        number of FAT:                      %d\n", boot.NUM_OF_FATS);
                printf("        number of sectors used by FAT:      %d\n", boot.SECTORS_PER_FAT);
                printf("        number of sectors per cluster:      %d\n", boot.SECTORS_PER_CLUSTER);
                printf("        number of ROOT Entries:             %d\n", boot.MAX_ROOT_DIRS);
                printf("        number of bytes per sector          %d\n", boot.BYTES_PER_SECTOR);
                if (cmd->argc == 2) {
                    printf("        ---Sector #---      ---Sector Types---\n");
                    printf("             0                    BOOT\n");
                    for (int i = 0; i < boot.NUM_OF_FATS; i++)
                        printf("          %02d -- %02d                FAT%d\n", (boot.SECTORS_PER_FAT * i) + 1, boot.SECTORS_PER_FAT * (i + 1), i);

                    printf("          %02d -- %02d                ROOT DIRECTORY\n", boot.SECTORS_PER_FAT * boot.NUM_OF_FATS, (boot.MAX_ROOT_DIRS / 16) + (boot.SECTORS_PER_FAT * boot.NUM_OF_FATS));
                }
                break;

            case TRAVERSE: //traverse
                if (serv_uuid == -1) {
                    printf("[ERROR] You are not connected to any server\n");
                    break;
                }
                if (cmd->argc > 2) {
                    printf("[ERROR] Usage: traverse [-l]\n");
                    break;
                } else if (cmd->argc == 2) {
                    if (strcmp(cmd->argv[1], "-l") != 0) {
                        printf("[ERROR] Usage: traverse [-l]\n");
                        break;
                    }
                }

                if (cmd->argc == 2) {
                    printf("    *****************************\n");
                    printf("    ** FILE ATTRIBUTE NOTATION **\n");
                    printf("    **                         **\n");
                    printf("    ** R ------ READ ONLY FILE **\n");
                    printf("    ** S ------ SYSTEM FILE    **\n");
                    printf("    ** H ------ HIDDEN FILE    **\n");
                    printf("    ** A ------ ARCHIVE FILE   **\n");
                    printf("    *****************************\n");
                    printf("\n");

                    for (int i = 0; i < boot.MAX_ROOT_DIRS; i++) {
                        if (entry[i].FILENAME[0] != 0x00 && entry[i].START_CLUSTER != 0) {
                            char attr[6] = {'-', '-', '-', '-', '-'};
                            unsigned char a = entry[i].ATTRIBUTES[0];
                            if (a == 0x01)
                                attr[0] = 'R';
                            if (a == 0x02)
                                attr[1] = 'H';
                            if (a == 0x04)
                                attr[2] = 'S';
                            if (a == 0x20)
                                attr[5] = 'A';
                            if (a == 0x10) {
                                for (int j = 0; j < 6; j++)
                                    attr[j] = '-';
                            }

                            if (entry[i].ATTRIBUTES[0] == 0x10) {
                                printf("%.6s    %d %d       < DIR >      /%.8s                 %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILENAME, entry[i].START_CLUSTER);
                                printf("%.6s    %d %d       < DIR >      /%.8s/.                 %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILENAME, entry[i].START_CLUSTER);
                                printf("%.6s    %d %d       < DIR >      /%.8s/..                 %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILENAME, 0);
                            } else {
                                printf("%.6s    %d %d       %lu      /%.8s.%.3s                 %d\n", attr, entry[i].CREATION_DATE, entry[i].CREATION_TIME, entry[i].FILE_SIZE, entry[i].FILENAME, entry[i].EXT, entry[i].START_CLUSTER);
                            }
                        }
                    }
                } else {
                    for (int i = 0; i < boot.MAX_ROOT_DIRS; i++) {
                        if (entry[i].FILENAME[0] != 0x00 && entry[i].START_CLUSTER != 0) {
                            if (entry[i].ATTRIBUTES[0] == 0x10) {
                                printf("/%.8s                       < DIR >\n", entry[i].FILENAME);
                                printf("/%.8s/.                     < DIR >\n", entry[i].FILENAME);
                                printf("/%.8s/..                    < DIR >\n", entry[i].FILENAME);
                            } else {
                                printf("/%.8s.%.3s\n", entry[i].FILENAME, entry[i].EXT);
                            }
                        }
                    }
                }
                break;

            case SHOWFAT: //showfat
                if (serv_uuid == -1) {
                    printf("[ERROR] You are not connected to any server\n");
                    break;
                }
                if (cmd->argc != 1) {
                    printf("[ERROR] Usage: showfat\n");
                    break;
                }

                int sectors = (boot.NUM_OF_FATS * boot.SECTORS_PER_FAT);
                int count = 0;
                printf("        0    1    2    3    4    5    6    7    8    9    a    b    c    d    e    f\n");

                /* Send GETSECTOR command to server */
                for (int i = 1; i <= sectors; i++) {
                    sprintf(msg_out.message, "GETSECTOR %d", i);
                    n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                    if (n < 0) {
                        perror("sendto");
                        break;
                    }

                    /* Get response from server */
                    n = recvfrom(sock_fd, &msg_in, sizeof(msg_in), 0, (struct sockaddr *)&serv_addr, (socklen_t *)&serv_len);
                    if (n < 0) {
                        perror("sendto");
                        break;
                    }

                    /* Check server UUID */
                    if (serv_uuid != msg_in.uuid) {
                        printf("[ERROR] Invalid server UUID - Connection rejected\n");
                        break;
                    }

                    for (int j = 0; j < boot.BYTES_PER_SECTOR; j++) {
                        if (count % 16 == 0 || count == 0) {
                            printf("\n");
                            printf("%4x", count);
                        }
                        printf("%5x", (unsigned char)msg_in.message[j]);
                        count++;
                    }
                }
                printf("\n");
                break;

            case SHOWSECTOR: //showsector
                if (serv_uuid == -1) {
                    printf("[ERROR] You are not connected to any server\n");
                    break;
                }
                if (cmd->argc != 2) {
                    printf("[ERROR] Usage: showsector <sector>\n");
                    break;
                }

                /* Parse sector */
                int sector = atoi(cmd->argv[1]);

                /* Send GETSECTOR command to server */
                sprintf(msg_out.message, "GETSECTOR %d", sector);
                n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                if (n < 0) {
                    perror("sendto");
                    break;
                }

                /* Get response from server */
                n = recvfrom(sock_fd, &msg_in, sizeof(msg_in), 0, (struct sockaddr *)&serv_addr, (socklen_t *)&serv_len);
                if (n < 0) {
                    perror("recvfrom");
                    break;
                }

                /* Check for valid server UUID */
                if (serv_uuid != msg_in.uuid) {
                    printf("[ERROR] Invalid server UUID - Connection rejected\n");
                    break;
                }

                /* Read response */
                printf("        0    1    2    3    4    5    6    7    8    9    a    b    c    d    e    f\n");
                for (int i = 0; i < boot.BYTES_PER_SECTOR; i++) {
                    if (i % 16 == 0 || i == 0) {
                        printf("\n");
                        printf("%4x", i);
                    }
                    printf("%5x", (unsigned char)msg_in.message[i]);
                }
                printf("\n");
                break;

            case SHOWFILE: //showfile
                if (serv_uuid == -1) {
                    printf("[ERROR] You are not connected to a server\n");
                    break;
                }
                if (cmd->argc != 2) {
                    printf("[ERROR] Usage: showfile <filename>\n");
                    break;
                }

                char filename[12] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' , '\0'};

                int index = 0, k;
                for (k = 0; k < strlen(cmd->argv[1]) && k < 9; k++) {
                    if (cmd->argv[1][k] == '.') {
                        k++;
                        break;
                    }
                    filename[index] = cmd->argv[1][k];
                    index++;
                }

                index = 8;
                for (int j = k; j < strlen(cmd->argv[1]) && j < 12; j++) {
                    if (cmd->argv[1][j] == '\n' || cmd->argv[1][j] == '\0') {
                        break;
                    }
                    filename[index] = cmd->argv[1][j];
                    index++;
                }

                for (int i = 0; i < boot.MAX_ROOT_DIRS; i++) {
                    if (entry[i].FILENAME != 0x00 && entry[i].START_CLUSTER != 0) {
                        if (compare_char(filename, (char *)entry[i].FILENAME)) {
                            int sector = ((boot.MAX_ROOT_DIRS / 16) + (boot.SECTORS_PER_FAT * boot.NUM_OF_FATS) - 1) + entry[i].START_CLUSTER;
                            int size = (entry[i].FILE_SIZE / 512) + 1;
                            int count = 0;

                            printf("        0    1    2    3    4    5    6    7    8    9    a    b    c    d    e    f\n");
                            for (int p = sector; p <= sector + size + 1; p++) {
                                sprintf(msg_out.message, "GETSECTOR %d", p);
                                n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                                if (n < 0) {
                                    perror("sendto");
                                    break;
                                }

                                n = recvfrom(sock_fd, &msg_in, sizeof(msg_in), 0, (struct sockaddr *)&serv_addr, (socklen_t *)&serv_len);
                                if (n < 0) {
                                    perror("recvfrom");
                                    break;
                                }

                                if (serv_uuid != msg_in.uuid) {
                                    printf("[ERROR] Invalid server UUID - Connection reject\n");
                                    break;
                                }

                                for (int j = 0; j < boot.BYTES_PER_SECTOR; j++) {
                                    if (j % 16 == 0 || j == 0) {
                                        printf("\n");
                                        printf("%4x", count++);
                                    }
                                    printf("%5x", (unsigned char)msg_in.message[j]);
                                }
                            }
                            printf("\n");
                        }
                    }
                }
                break;

            case EXIT: //exit
                free(input);
                delete_command(cmd);

                if (serv_uuid != -1) {
                    /* Send DISCONNECT command to server */
                    sprintf(msg_out.message, "DISCONNECT");
                    n = sendto(sock_fd, &msg_out, sizeof(msg_out), 0, (struct sockaddr *)&serv_addr, (socklen_t)serv_len);
                    if (n < 0) {
                        perror("sendto");
                        exit(EXIT_FAILURE);
                    }

                    close(sock_fd);
                    bzero((char *)&serv_addr, sizeof(serv_addr));
                    serv_uuid = -1;
                }
                exit(EXIT_SUCCESS);

            case INVALID_CMD: //Invalid command (default)
                printf("[ERROR] %s: Command not found\n", cmd->name);
                break;
        }

        fflush(stdout); //Safety precaution

        /* Restore output */
        if (cmd->output_file) {
            dup2(con_out, STDOUT_FILENO);
            close(con_out);
        }

        /* Free memory */
        free(input);
        delete_command(cmd);
    }
}
示例#19
0
 void Console::on_new_command(QString command)
 {
         this->append("user: " + command, QtDebugMsg);
         emit new_command(command);
 }
示例#20
0
void cmd_parser(char *mes, int as, int new_cmd)
// as = 0  - get command
// as = 1  - may be exit with empty command
// new_cmd = 1 - new command
// new_cmd = 0 - get added items
{
	char	*cmd, *str, *beg;
	term_t	type;
	int	len;

	if (debug_flag) printf("cmd_parser:\n");
	for (;;) {
		if (new_cmd) {
			new_command();
			type = CMD_TERM;
		} else type = ITEM_TERM;
		cmd = get_input_line(mes);
		if (cmd == (char *)NULL) {
			go_to_dialog();
			continue;
		};
		len = strlen(cmd_line);
		snprintf(cmd_line + len, LINE_BUF_SIZE - len, " %s",cmd);
		str = cmd;
		while (isspace(*str)) str++;
		if (strlen(str) == 0) {
			if (as) return;
			continue;
		};
		beg = str;
		if (*beg == '#') continue;
		while (*str != 0) {
			if (isspace(*str)) {
				*str++ = 0;
				if (strlen(beg) > 0) {
					add_term(beg, type);
					type = ITEM_TERM;
				};
				while (isspace(*str)) str++;
				beg = str;
				continue;
			};
			if (*str == '\"') {
				str++;
				while ((*str != 0) && (*str != '\"')) str ++;
				if (*str == 0) {
					add_term(beg, type);
					if (read_file)
						add_term(";", CMD_END_TERM);
					return;
				};
				if (*beg == '\"') {
					beg++;
					*str = 0;
					add_term(beg, type);
					type = ITEM_TERM;
					beg = str + 1;
				};
				str++;
				continue;
			};
			if (*str == 0) {
				if (strlen(beg) > 0)
					add_term(beg, type);
				if (read_file)
					add_term(";", CMD_END_TERM);
				return;
			};
			if (*str == ';') {
				*str++ = 0;
				if (strlen(beg) > 0)
					add_term(beg, type);
				add_term(";", CMD_END_TERM);
				return;
			};
			str++;
		};
		if (strlen(beg) > 0)
			add_term(beg, type);
		if (read_file)
			add_term(";", CMD_END_TERM);
		return;
	}
}