Exemplo n.º 1
0
void news_command(player *p,char *str)
{
    if (p->edit_info) {
	tell_player(p,"Can't do news commands whilst in editor.\n");
	return;
    }

    if ((*str=='/') && (p->input_to_fn==news_command)) {
	match_commands(p,str+1);
	if (!(p->flags&PANIC) && (p->input_to_fn==news_command))
	    do_prompt(p,"News Mode >");
	return;
    }
    if (!*str) 
	if (p->input_to_fn==news_command) {
	    tell_player(p,"Format: news <action>\n");
	    if (!(p->flags&PANIC) && (p->input_to_fn==news_command))
		do_prompt(p,"News Mode >");
	    return;
	}
	else {
	    tell_player(p,"Entering news mode. Use 'end' to leave.\n"
			"'/<command>' does normal commands.\n");
	    p->flags &= ~PROMPT;
	    p->input_to_fn=news_command;
	}
    else sub_command(p,str,news_list);
    if (!(p->flags&PANIC) && (p->input_to_fn==news_command))
	do_prompt(p,"News Mode >");
}
Exemplo n.º 2
0
/* the dreaded pager B-)  */
int             draw_page(player * p, char *text, int drawme)
{
   int             end_line = 0, n;
   float perc;
   ed_info        *e;
   char           *oldstack;
   oldstack = stack;

   for (n = TERM_LINES + 1; n; n--, end_line++)
   {
      while (*text && *text != '\n')
         *stack++ = *text++;
      if (!*text)
         break;
      *stack++ = *text++;
   }
   *stack++ = 0;
   
   if(drawme)
     tell_player(p, oldstack);
     
   if (*text && p->edit_info)
   {
      e = p->edit_info;
      end_line += e->size;
      perc = (((float)end_line/(float)e->max_size)*100);
      sprintf(oldstack, 
              "(Pager: lines %d-%d of %d (%d%%)) p/N/f/l/r/q/?: "
	      ,e->size+1, end_line, e->max_size, (int) perc);
      stack = end_string(oldstack);
      do_prompt(p, oldstack);
   }
   stack = oldstack;
   return *text;
}
Exemplo n.º 3
0
/*
 * Select a Storage resource from prompt list
 */
STORERES *select_storage_resource(UAContext *ua, bool autochanger_only)
{
   STORERES *store;
   char name[MAX_NAME_LENGTH];

   if (autochanger_only) {
      start_prompt(ua, _("The defined Autochanger Storage resources are:\n"));
   } else {
      start_prompt(ua, _("The defined Storage resources are:\n"));
   }

   LockRes();
   foreach_res(store, R_STORAGE) {
      if (acl_access_ok(ua, Storage_ACL, store->name())) {
         if (autochanger_only && !store->autochanger) {
            continue;
         } else {
            add_prompt(ua, store->name());
         }
      }
   }
   UnlockRes();

   if (do_prompt(ua, _("Storage"),  _("Select Storage resource"), name, sizeof(name)) < 0) {
      return NULL;
   }
   store = (STORERES *)GetResWithName(R_STORAGE, name);

   return store;
}
Exemplo n.º 4
0
int draw_page(player *p,char *text)
{
  int end_line=0,n;
  ed_info *e;
  char *oldstack;
  oldstack=stack;

  for(n=TERM_LINES-3;n;n--,end_line++) {
    while(*text && *text!='\n') *stack++=*text++;
    if (!*text) break;
    *stack++=*text++;
  }
  *stack++=0;
  tell_player(p,oldstack);
  if (*text && p->edit_info) {
    e=p->edit_info;
    end_line+=e->size;
    sprintf(oldstack,"(Pager: lines %d to %d, from a total %d)",
	    e->size,end_line,e->max_size);
    stack=end_string(oldstack);
    do_prompt(p,oldstack);
  }
  stack=oldstack;	
  return *text;
}
Exemplo n.º 5
0
void start_edit(player *p,int max_size,void *finish_func,void *quit_func,
		char *current)
{
  ed_info *e;
  int old_length;
  if (p->edit_info) return;
  e=(ed_info *)MALLOC(sizeof(ed_info));
  memset(e,0,sizeof(ed_info));
  p->edit_info=e;
  e->buffer=(char *)MALLOC(max_size);
  memset(e->buffer,0,max_size);
  e->max_size=max_size;
  e->finish_func=finish_func;
  e->quit_func=quit_func;
  if (current) {
    old_length=strlen(current);
    memcpy(e->buffer,current,old_length);
    e->size=old_length+1;
  }
  else e->size=1;
  e->current=e->buffer+e->size-1;
  p->flags |= DONT_CHECK_PIPE;
  save_flags(p);
  tell_player(p,"Entering editor ... Use /help editor for help.\n"
	      "/<command> for general commands, .<command> for editor commands\n"
	      "Use '.end' to finish and keep edit\n");
  if (p->saved_flags&QUIET_EDIT) 
    tell_player(p,"Blocking shouts and tells whilst in editor.\n");
  edit_view(p,0);
  edit_stats(p,0);
  do_prompt(p,"+");
}
Exemplo n.º 6
0
/*
 * Given a list of keywords, prompt the user to choose one.
 *
 * Returns: -1 on failure
 *          index into list (base 0) on success
 */
int do_keyword_prompt(UAContext *ua, const char *msg, const char **list)
{
   start_prompt(ua, _("You have the following choices:\n"));
   for (int i = 0; list[i]; i++) {
      add_prompt(ua, list[i]);
   }

   return do_prompt(ua, "", msg, NULL, 0);
}
Exemplo n.º 7
0
void editor_main(player *p,char *str)
{
  if (!p->edit_info) {
    log("error","Editor called with no edit_info");
    return;
  }
  if (*str=='/') {
    restore_flags(p);
    match_commands(p,str+1);
    save_flags(p);
    return;
  }
  if (*str=='.') {
    sub_command(p,str+1,editor_list);
    if (p->edit_info) do_prompt(p,"+");
    return;
  }
  insert_line(p,str);
  do_prompt(p,"+");
}
Exemplo n.º 8
0
void		help_page(player *p)
{
   tell_player(p," Pager Commands:\n"
   		 "	p - Previous page\n"
   		 "	n - Next page (also done by hitting return)\n"
   		 "	f - First page\n"
   		 "	l - Last page (and exit)\n"
   		 "	r - Refresh current page\n"
   		 "	q - Exit from pager\n"
   		 " All other commands will be as normal, but no additional paging or"
   		 " editing will be possible until you exit the current paged output.\n");
   do_prompt(p, "(Pager: press return to continue):");
}
Exemplo n.º 9
0
void mail_command(player *p,char *str)
{
    if (p->edit_info) {
	tell_player(p,"Can't do mail commands whilst in editor.\n");
	return;
    }

    if (!p->saved) {
	tell_player(p,"You have no save information, and so can't use "
		    "mail.\n");
	return;
    }

    if ((*str=='/') && (p->input_to_fn==mail_command)) {
	match_commands(p,str+1);
	if (!(p->flags&PANIC) && (p->input_to_fn==mail_command))
	    do_prompt(p,"Mail Mode >");
	return;
    }
    if (!*str) 
	if (p->input_to_fn==mail_command) {
	    tell_player(p,"Format: mail <action>\n");
	    if (!(p->flags&PANIC) && (p->input_to_fn==mail_command))
		do_prompt(p,"Mail Mode >");
	    return;
	}
	else {
	    tell_player(p,"Entering mail mode. Use 'end' to leave.\n"
			"'/<command>' does normal commands.\n");
	    p->flags &= ~PROMPT;
	    p->input_to_fn=mail_command;
	}
    else sub_command(p,str,mail_list);
    if (!(p->flags&PANIC) && (p->input_to_fn==mail_command))
	do_prompt(p,"Mail Mode >");
}
Exemplo n.º 10
0
/*
 * Get a catalog resource from prompt list
 */
CATRES *get_catalog_resource(UAContext *ua)
{
   CATRES *catalog = NULL;
   char name[MAX_NAME_LENGTH];

   for (int i = 1; i < ua->argc; i++) {
      if (bstrcasecmp(ua->argk[i], NT_("catalog")) && ua->argv[i]) {
         if (acl_access_ok(ua, Catalog_ACL, ua->argv[i])) {
            catalog = (CATRES *)GetResWithName(R_CATALOG, ua->argv[i]);
            break;
         }
      }
   }

   if (ua->gui && !catalog) {
      LockRes();
      catalog = (CATRES *)GetNextRes(R_CATALOG, NULL);
      UnlockRes();

      if (!catalog) {
         ua->error_msg(_("Could not find a Catalog resource\n"));
         return NULL;
      } else if (!acl_access_ok(ua, Catalog_ACL, catalog->name())) {
         ua->error_msg(_("You must specify a \"use <catalog-name>\" command before continuing.\n"));
         return NULL;
      }

      return catalog;
   }

   if (!catalog) {
      start_prompt(ua, _("The defined Catalog resources are:\n"));

      LockRes();
      foreach_res(catalog, R_CATALOG) {
         if (acl_access_ok(ua, Catalog_ACL, catalog->name())) {
            add_prompt(ua, catalog->name());
         }
      }
      UnlockRes();

      if (do_prompt(ua, _("Catalog"),  _("Select Catalog resource"), name, sizeof(name)) < 0) {
         return NULL;
      }

      catalog = (CATRES *)GetResWithName(R_CATALOG, name);
   }
Exemplo n.º 11
0
/* fire editor up */
void            start_edit(player * p, int max_size, player_func *finish_func, player_func *quit_func,
                            char *current)
{
   ed_info        *e;
   int             old_length, trunc=0;
   if (p->edit_info) {
      tell_player(p, " Unable to enter editor while already in edit/pager.\n");
      return;
   }
   e = (ed_info *) MALLOC(sizeof(ed_info));
   memset(e, 0, sizeof(ed_info));
   p->edit_info = e;
   e->buffer = (char *) MALLOC(max_size);
   memset(e->buffer, 0, max_size);
   e->max_size = max_size;
   e->finish_func = finish_func;
   e->quit_func = quit_func;
   if (current)
   {
      old_length = strlen(current);
      /* safety fix */
      if(old_length>=max_size) {
        trunc=1;
        old_length = max_size-1;
        *(current+old_length-1) ='\n';
      }
      memcpy(e->buffer, current, old_length);
      e->size = old_length + 1;
   } else
      e->size = 1;
   e->current = e->buffer + e->size - 1;
   /*p->flags |= DONT_CHECK_PIPE; - stolen for the moment */
   save_flags(p);
   tell_player(p, " Entering editor ... Use /help editor for help.\n"
                  " /<command> for general commands, .<command> for editor "
                  "commands\n"
                  " Use '.end' to finish and keep edit\n");
   if (p->saved_flags & QUIET_EDIT)
      tell_player(p, " Blocking shouts and tells whilst in editor.\n");
   edit_view(p, 0);
   if(trunc)
     tell_player(p, " Text truncated to this point...\n");
   edit_stats(p, 0);
   do_prompt(p, "+");
}
Exemplo n.º 12
0
void end_post(player *p,char *str)
{
    note *article;
    char *oldstack;
    oldstack=stack;

    article=(note *)p->edit_info->misc;
    stack=store_string(oldstack,p->edit_info->buffer);
    article->text.length=(int)stack-(int)oldstack;
    article->text.where=(char *)MALLOC(article->text.length);
    memcpy(article->text.where,oldstack,article->text.length);
    stack=oldstack;

    article->next_sent=news_start;
    news_start=article->id;
    news_count++;
    article->flags &= ~NOT_READY;
    article->read_count=0;
    tell_player(p,"Article posted....\n");
    if (p->edit_info->input_copy==news_command) do_prompt(p,"News Mode >");
}
Exemplo n.º 13
0
/*
 * Select a FileSet resource from prompt list
 */
FILESETRES *select_fileset_resource(UAContext *ua)
{
   FILESETRES *fs;
   char name[MAX_NAME_LENGTH];

   start_prompt(ua, _("The defined FileSet resources are:\n"));

   LockRes();
   foreach_res(fs, R_FILESET) {
      if (acl_access_ok(ua, FileSet_ACL, fs->name())) {
         add_prompt(ua, fs->name());
      }
   }
   UnlockRes();

   if (do_prompt(ua, _("FileSet"), _("Select FileSet resource"), name, sizeof(name)) < 0) {
      return NULL;
   }

   fs = (FILESETRES *)GetResWithName(R_FILESET, name);

   return fs;
}
Exemplo n.º 14
0
/* Our main file browser function.  path is the tilde-expanded path we
 * start browsing from. */
std::string do_browser(std::string path, DIR *dir)
{
	std::string retval;
	bool old_const_update = ISSET(CONST_UPDATE);
	std::string prev_dir;
	/* The directory we were in before backing up to "..". */
	std::string ans;
	/* The last answer the user typed at the statusbar prompt. */
	size_t old_selected;
	/* The selected file we had before the current selected file. */

	curs_set(0);
	blank_statusbar();
	bottombars(MBROWSER);
	wnoutrefresh(bottomwin);

	UNSET(CONST_UPDATE);

change_browser_directory:
	/* We go here after we select a new directory. */

	path = get_full_path(path);

	assert(path.length() > 0 && path.back() == '/');

	/* Get the file list, and set longest and width in the process. */
	browser_init(path, dir);

	/* Sort the file list. */
	std::sort(filelist.begin(), filelist.end(), sort_directories);

	/* If prev_dir isn't empty, select the directory saved in it, and then blow it away. */
	if (prev_dir != "") {
		browser_select_filename(prev_dir);

		prev_dir = "";
		/* Otherwise, select the first file or directory in the list. */
	} else {
		selected = 0;
	}

	old_selected = (size_t)-1;

	titlebar(path);

	Key *kbinput = nullptr;

	while (true) {
		struct stat st;
		size_t fileline = selected / width;
		/* The line number the selected file is on. */
		std::string new_path;
		/* The path we switch to at the "Go to Directory" prompt. */

		if (kbinput) {
			delete kbinput;
			kbinput = nullptr;
		}

		/* Display the file list if we don't have a key, or if the
		 * selected file has changed, and set width in the process. */
		if (old_selected != selected) {
			browser_refresh();
		}

		old_selected = selected;

		// Deal with the keyboard input
		kbinput = new Key(get_kbinput(edit));

		auto func = func_from_key(*kbinput);

		if (func == total_refresh) {
			total_redraw();
		} else if (func == do_help_void) {
			do_help_void();
			curs_set(0);
			/* Search for a filename. */
		} else if (func == do_search) {
			curs_set(1);
			do_filesearch();
			curs_set(0);
			/* Search for another filename. */
		} else if (func == do_research) {
			do_fileresearch();
		} else if (func == do_page_up) {
			if (selected >= (editwinrows + fileline % editwinrows) * width) {
				selected -= (editwinrows + fileline % editwinrows) * width;
			} else {
				selected = 0;
			}
		} else if (func == do_page_down) {
			selected += (editwinrows - fileline % editwinrows) * width;
			if (selected > filelist.size() - 1) {
				selected = filelist.size() - 1;
			}
		} else if (func == do_first_file) {
			selected = 0;
		} else if (func == do_last_file) {
			selected = filelist.size() - 1;
		} else if (func == goto_dir_void) {
			/* Go to a specific directory. */
			curs_set(1);

			std::shared_ptr<Key> key;
			PromptResult i = do_prompt(true,
			              false,
			              MGOTODIR, key, ans.c_str(),
			              NULL,
			              browser_refresh, _("Go To Directory"));

			curs_set(0);
			bottombars(MBROWSER);

			/* If the directory begins with a newline (i.e. an
			 * encoded null), treat it as though it's blank. */
			if (i == PROMPT_ABORTED || i == PROMPT_BLANK_STRING || answer.front() == '\n') {
				/* We canceled.  Indicate that on the statusbar, and
				 * blank out ans, since we're done with it. */
				statusbar(_("Cancelled"));
				ans = "";
				func = nullptr;
				continue;
			} else if (i != PROMPT_ENTER_PRESSED) {
				/* Put back the "Go to Directory" key and save
				 * answer in ans, so that the file list is displayed
				 * again, the prompt is displayed again, and what we
				 * typed before at the prompt is displayed again. */
				ans = answer;
				func = goto_dir_void;
				continue;
			}

			/* We have a directory.  Blank out ans, since we're done with it. */
			ans = "";

			/* Convert newlines to nulls, just before we go to the directory. */
			sunder(answer);

			new_path = real_dir_from_tilde(answer);

			if (new_path == "") {
				new_path = path + answer;
			}

			dir = opendir(new_path);
			if (dir == NULL) {
				/* We can't open this directory for some reason. Complain. */
				statusbar(_("Error reading %s: %s"), answer.c_str(), strerror(errno));
				beep();
				func = nullptr;
				continue;
			}

			/* Start over again with the new path value. */
			path = new_path;
			goto change_browser_directory;
		} else if (func == do_up_void) {
			if (selected >= width) {
				selected -= width;
			}
		} else if (func == do_left) {
			if (selected > 0) {
				selected--;
			}
		} else if (func == do_down_void) {
			if (selected + width <= filelist.size() - 1) {
				selected += width;
			}
		} else if (func == do_right) {
			if (selected < filelist.size() - 1) {
				selected++;
			}
		} else if (func == do_enter_void) {
			/* We can't move up from "/". */
			if (filelist[selected] == "/..") {
				statusbar(_("Can't move up a directory"));
				beep();
				func = nullptr;
				continue;
			}

			if (stat(filelist[selected], &st) == -1) {
				/* We can't open this file for some reason. Complain. */
				statusbar(_("Error reading %s: %s"), filelist[selected].c_str(), strerror(errno));
				beep();
				func = nullptr;
				continue;
			}

			if (!S_ISDIR(st.st_mode)) {
				/* We've successfully opened a file, we're done, so get out. */
				retval = filelist[selected];
				func = nullptr;
				break;
			} else if (tail(filelist[selected]) == "..") {
				/* We've successfully opened the parent directory,
				 * save the current directory in prev_dir, so that
				  * we can easily return to it by hitting Enter. */
				prev_dir = striponedir(filelist[selected]);
			}

			dir = opendir(filelist[selected].c_str());
			if (dir == NULL) {
				/* We can't open this directory for some reason. Complain. */
				statusbar(_("Error reading %s: %s"), filelist[selected].c_str(), strerror(errno));
				beep();
				func = nullptr;
				continue;
			}

			path = filelist[selected];

			/* Start over again with the new path value. */
			goto change_browser_directory;
		} else if (func == do_exit) {
			/* Exit from the file browser. */
			break;
		}
		func = nullptr;
	}
	if (kbinput) {
		delete kbinput;
	}
	titlebar(NULL);
	edit_refresh();
	curs_set(1);
	if (old_const_update) {
		SET(CONST_UPDATE);
	}

	filelist.clear();

	return retval;
}
Exemplo n.º 15
0
void            process_players()
{
   player         *scan;
   char           *oldstack;

   for (scan = flatlist_start; scan; scan = scan->flat_next)
   {
     if (scan->flat_next)
       if (((player *)scan->flat_next)->flat_previous != scan)
	 {
	   raw_wall("\n\n   -=> Non-terminated flatlist <=-\n\n");
	   raw_wall("\n\n   -=> Dumping end off of list <=-\n\n");
	   scan->flat_next=NULL;
	 }

      if ((scan->fd < 0) || (scan->flags & PANIC) ||
          (scan->flags & CHUCKOUT))
      {

         oldstack = stack;
         current_player = scan;

         if (scan->location && scan->name[0] && !(scan->flags & RECONNECTION))
         {
            sprintf(stack, " %s suddenly dissolve%s into a squintillion dots"
                           " that quickly disperse.\n",
                    scan->name, single_s(scan));
            stack = end_string(stack);
            tell_room(scan->location, oldstack);
            stack = oldstack;
            save_player(scan);
         }
         if (!(scan->flags & RECONNECTION))
         {
            command_type = 0;
	    if (scan->gender==PLURAL)
	      do_inform(scan, "[%s have disconnected] %s");
	    else
	      do_inform(scan, "[%s has disconnected] %s");
            if (scan->saved && !(scan->flags & NO_SAVE_LAST_ON))
               scan->saved->last_on = time(0);
         }
         if (sys_flags & VERBOSE || scan->residency == 0)
         {
            if (scan->name[0])
               sprintf(oldstack, "%s has disconnected from %s", scan->name,
                       scan->inet_addr);
            else
               sprintf(oldstack, "Disconnect from login. [%s]",
                       scan->inet_addr);
            stack = end_string(oldstack);
            log("newconn", oldstack);
         }
         destroy_player(scan);
         current_player = 0;
         stack = oldstack;
      } else if (scan->flags & INPUT_READY)
      {
/* there used to be this here...
            if (!(scan->lagged) && !(scan->flags & PERM_LAG))
   for reference... */

         if (!(scan->lagged))
         {
            current_player = scan;
            current_room = scan->location;
            input_for_one(scan);
            action = "processing players";
            current_player = 0;
            current_room = 0;

#ifdef PC
            if (scan->flags & PROMPT && scan == input_player)
#else
            if (scan->flags & PROMPT)
#endif
            {
               if (scan->saved_flags & CONVERSE)
                  do_prompt(scan, scan->converse_prompt);
               else
                  do_prompt(scan, scan->prompt);
            }
         }
         memset(scan->ibuffer, 0, IBUFFER_LENGTH);
         scan->flags &= ~INPUT_READY;
      }
   }
}
Exemplo n.º 16
0
/* Set up the system variables for a search or replace.  If use_answer
 * is TRUE, only set backupstring to answer.  Return -2 to run the
 * opposite program (search -> replace, replace -> search), return -1 if
 * the search should be canceled (due to Cancel, a blank search string,
 * Go to Line, or a failed regcomp()), return 0 on success, and return 1
 * on rerun calling program.
 *
 * replacing is TRUE if we call from do_replace(), and FALSE if called
 * from do_search(). */
int search_init(bool replacing, bool use_answer)
{
    int i = 0;
    char *buf;
    static char *backupstring = NULL;
	/* The search string we'll be using. */

    /* If backupstring doesn't exist, initialize it to "". */
    if (backupstring == NULL)
	backupstring = mallocstrcpy(NULL, "");

    /* If use_answer is TRUE, set backupstring to answer and get out. */
    if (use_answer) {
	backupstring = mallocstrcpy(backupstring, answer);
	return 0;
    }

    /* We display the search prompt below.  If the user types a partial
     * search string and then Replace or a toggle, we will return to
     * do_search() or do_replace() and be called again.  In that case,
     * we should put the same search string back up. */

    focusing = TRUE;

    if (last_search[0] != '\0') {
	char *disp = display_string(last_search, 0, COLS / 3, FALSE);

	buf = charalloc(strlen(disp) + 7);
	/* We use (COLS / 3) here because we need to see more on the line. */
	sprintf(buf, " [%s%s]", disp,
		(strlenpt(last_search) > COLS / 3) ? "..." : "");
	free(disp);
    } else
	buf = mallocstrcpy(NULL, "");

    /* This is now one simple call.  It just does a lot. */
    i = do_prompt(FALSE,
#ifndef DISABLE_TABCOMP
	TRUE,
#endif
	replacing ? MREPLACE : MWHEREIS, backupstring,
#ifndef DISABLE_HISTORIES
	&search_history,
#endif
	/* TRANSLATORS: This is the main search prompt. */
	edit_refresh, "%s%s%s%s%s%s", _("Search"),
#ifndef NANO_TINY
	/* TRANSLATORS: The next three strings are modifiers of the search prompt. */
	ISSET(CASE_SENSITIVE) ? _(" [Case Sensitive]") :
#endif
	"",
#ifdef HAVE_REGEX_H
	ISSET(USE_REGEXP) ? _(" [Regexp]") :
#endif
	"",
#ifndef NANO_TINY
	ISSET(BACKWARDS_SEARCH) ? _(" [Backwards]") :
#endif
	"", replacing ?
#ifndef NANO_TINY
	/* TRANSLATORS: The next two strings are modifiers of the search prompt. */
	openfile->mark_set ? _(" (to replace) in selection") :
#endif
	_(" (to replace)") : "", buf);

    fflush(stderr);

    /* Release buf now that we don't need it anymore. */
    free(buf);

    free(backupstring);
    backupstring = NULL;

    /* Cancel any search, or just return with no previous search. */
    if (i == -1 || (i < 0 && *last_search == '\0') || (!replacing &&
	i == 0 && *answer == '\0')) {
	statusbar(_("Cancelled"));
	return -1;
    } else {
	functionptrtype func = func_from_key(&i);

	if (i == -2 || i == 0 ) {
#ifdef HAVE_REGEX_H
		/* Use last_search if answer is an empty string, or
		 * answer if it isn't. */
		if (ISSET(USE_REGEXP) && !regexp_init((i == -2) ?
			last_search : answer))
		    return -1;
#endif
		;
#ifndef NANO_TINY
	} else if (func == case_sens_void) {
		TOGGLE(CASE_SENSITIVE);
		backupstring = mallocstrcpy(backupstring, answer);
		return 1;
	} else if (func == backwards_void) {
		TOGGLE(BACKWARDS_SEARCH);
		backupstring = mallocstrcpy(backupstring, answer);
		return 1;
#endif
#ifdef HAVE_REGEX_H
	} else if (func == regexp_void) {
		TOGGLE(USE_REGEXP);
		backupstring = mallocstrcpy(backupstring, answer);
		return 1;
#endif
	} else if (func == do_replace || func == flip_replace_void) {
		backupstring = mallocstrcpy(backupstring, answer);
		return -2;	/* Call the opposite search function. */
	} else if (func == do_gotolinecolumn_void) {
		do_gotolinecolumn(openfile->current->lineno,
			openfile->placewewant + 1, TRUE, TRUE);
				/* Put answer up on the statusbar and
				 * fall through. */
		return 3;
	} else {
		return -1;
	}
    }

    return 0;
}
Exemplo n.º 17
0
 void end_mail(player *p,char *str)
 {
   note *mail;
   char *oldstack,*name_list,*body,*tcpy,*comp,*text;
   saved_player **player_list,**pscan,**pfill;
   player *on;
   int receipt_count,n,m,*received_lists,*r;
   oldstack=stack;

   mail=(note *)p->edit_info->misc;

   align(stack);
   player_list=(saved_player **)stack;
   receipt_count=saved_tag(p,mail->text.where);
   if (mail->text.where) FREE(mail->text.where);
   mail->text.where=0;
   if (!receipt_count) {
     tell_player(p,"No one to send the letter to !\n");
     remove_note(mail);
     stack=oldstack;
     if (p->edit_info->input_copy==mail_command) do_prompt(p,"Mail Mode >");
     return;
   }

   if (!p->saved) {
     tell_player(p,"Eeek, no save file !\n");
     remove_note(mail);
     stack=oldstack;
     if (p->edit_info->input_copy==mail_command) do_prompt(p,"Mail Mode >");
     return;
   }

   pscan=player_list;
   pfill=player_list;
   m=receipt_count;
   for(n=0;n<m;n++) 
     if (((*pscan)->residency==STANDARD_ROOMS) ||
	 ((*pscan)->residency==BANISHED)) {
       tell_player(p,"You can't send mail to a room, or someone who is banished.\n");
       receipt_count--;
       pscan++;
     }
     else {
       if ((mail->flags&ANONYMOUS) && ((*pscan)->saved_flags&NO_ANONYMOUS)) {
	 text=stack;
	 sprintf(stack,"%s is not receiving anonymous mail.\n",(*pscan)->lower_name);
	 stack=end_string(stack);
	 tell_player(p,text);
	 stack=text;
	 receipt_count--;
	 pscan++;
       }
       else *pfill++=*pscan++;
     }

   if (receipt_count>0) {
     pscan=player_list;
     name_list=stack;
     if (mail->flags&SUPRESS_NAME) {
       strcpy(stack,"Anonymous");
       stack=end_string(stack);
     }
     else {
       strcpy(stack,(*pscan)->lower_name);
       stack=strchr(stack,0);
       if (receipt_count>1) {
	 pscan++;
	 for(n=2;n<receipt_count;n++,pscan++) {
	   sprintf(stack,", %s",(*pscan)->lower_name);
	   stack=strchr(stack,0); 
	 }
	 sprintf(stack," and %s",(*pscan)->lower_name);
	 stack=strchr(stack,0); 
       }
       *stack++=0;
     }

     body=stack;
     sprintf(stack,"Sending mail to %s.\n",name_list);
     stack=end_string(stack);
     tell_player(p,body);
     stack=body;

     if (mail->flags&ANONYMOUS) 
       sprintf(stack,"Anonymous mail dated %s.\nSubject: %s\nTo: %s\n\n",
	       convert_time(mail->date),mail->header,name_list);
     else
       sprintf(stack,"Mail dated %s.\nSubject: %s\nTo: %s\nFrom: %s\n\n",
	       convert_time(mail->date),mail->header,name_list,mail->name);
     stack=strchr(stack,0);

     tcpy=p->edit_info->buffer;
     for(n=0;n<p->edit_info->size;n++) *stack++=*tcpy++;

     comp=stack;
     stack=store_string(stack,body);
     mail->text.length=(int)stack-(int)comp;
     mail->text.where=(char *)MALLOC(mail->text.length);
     memcpy(mail->text.where,comp,mail->text.length);

     mail->next_sent=p->saved->mail_sent;
     p->saved->mail_sent=mail->id;

     text=stack;
     command_type |= HIGHLIGHT;

     if (mail->flags&ANONYMOUS) 
       sprintf(stack,"     -=>  New mail, '%s' sent anonymously\n\n",
	       mail->header);
     else
       sprintf(stack,"     -=>  New mail, '%s' from %s.\n\n",
	       mail->header,mail->name);
     stack=end_string(stack);

     align(stack);
     received_lists=(int *)stack;

     pscan=player_list;
     for(n=0;n<receipt_count;n++,pscan++) {
       stack=(char *)received_lists;
       r=(*pscan)->mail_received;
       if (!r) m=2*sizeof(int);
       else {
	 for(m=2*sizeof(int);*r;r++,m+=sizeof(int)) {
	   *(int *)stack=*r;
	   stack+=sizeof(int);
	 }
       }
       *(int *)stack=mail->id;
       stack+=sizeof(int);
       *(int *)stack=0;
       if ((*pscan)->mail_received) FREE((*pscan)->mail_received);
       r=(int *)MALLOC(m);
       memcpy(r,received_lists,m);
       (*pscan)->mail_received=r;
       on=find_player_absolute_quiet((*pscan)->lower_name);
       if (on && on->saved_flags&MAIL_INFORM) {
	 tell_player(on,"\007\n");
	 tell_player(on,text);
       }
       else (*pscan)->saved_flags |= NEW_MAIL;
     }

     command_type &= ~HIGHLIGHT;

     mail->read_count=receipt_count;
     mail->flags &= ~NOT_READY;
     tell_player(p,"Mail posted....\n");
   }
   else tell_player(p,"No mail posted.\n");
   if (p->edit_info->input_copy==mail_command) do_prompt(p,"Mail Mode >");
   stack=oldstack;
 }
Exemplo n.º 18
0
/*
 * Update a media record -- allows you to change the
 *  Volume status. E.g. if you want Bacula to stop
 *  writing on the volume, set it to anything other
 *  than Append.
 */
static int update_volume(UAContext *ua)
{
   MEDIA_DBR mr;
   POOL *pool;
   POOL_DBR pr;
   POOLMEM *query;
   POOL_MEM ret;
   char buf[1000];
   char ed1[130];
   bool done = false;
   int i;
   const char *kw[] = {
      NT_("VolStatus"),                /* 0 */
      NT_("VolRetention"),             /* 1 */
      NT_("VolUse"),                   /* 2 */
      NT_("MaxVolJobs"),               /* 3 */
      NT_("MaxVolFiles"),              /* 4 */
      NT_("MaxVolBytes"),              /* 5 */
      NT_("Recycle"),                  /* 6 */
      NT_("InChanger"),                /* 7 */
      NT_("Slot"),                     /* 8 */
      NT_("Pool"),                     /* 9 */
      NT_("FromPool"),                 /* 10 */
      NT_("AllFromPool"),              /* 11 !!! see below !!! */
      NT_("Enabled"),                  /* 12 */
      NT_("RecyclePool"),              /* 13 */
      NT_("ActionOnPurge"),            /* 14 */
      NULL };

#define AllFromPool 11               /* keep this updated with above */

   for (i=0; kw[i]; i++) {
      int j;
      POOL_DBR pr;

      if ((j=find_arg_with_value(ua, kw[i])) > 0) {
         /* If all from pool don't select a media record */
         if (i != AllFromPool && !select_media_dbr(ua, &mr)) {
            return 0;
         }
         switch (i) {
         case 0:
            update_volstatus(ua, ua->argv[j], &mr);
            break;
         case 1:
            update_volretention(ua, ua->argv[j], &mr);
            break;
         case 2:
            update_voluseduration(ua, ua->argv[j], &mr);
            break;
         case 3:
            update_volmaxjobs(ua, ua->argv[j], &mr);
            break;
         case 4:
            update_volmaxfiles(ua, ua->argv[j], &mr);
            break;
         case 5:
            update_volmaxbytes(ua, ua->argv[j], &mr);
            break;
         case 6:
            update_volrecycle(ua, ua->argv[j], &mr);
            break;
         case 7:
            update_volinchanger(ua, ua->argv[j], &mr);
            break;
         case 8:
            update_volslot(ua, ua->argv[j], &mr);
            break;
         case 9:
            memset(&pr, 0, sizeof(POOL_DBR));
            pr.PoolId = mr.PoolId;
            if (!db_get_pool_record(ua->jcr, ua->db, &pr)) {
               ua->error_msg("%s", db_strerror(ua->db));
               break;
            }
            update_vol_pool(ua, ua->argv[j], &mr, &pr);
            break;
         case 10:
            update_vol_from_pool(ua, &mr);
            return 1;
         case 11:
            update_all_vols_from_pool(ua, ua->argv[j]);
            return 1;
         case 12:
            update_volenabled(ua, ua->argv[j], &mr);
            break;
         case 13:
            update_vol_recyclepool(ua, ua->argv[j], &mr);
            break;
         case 14:
            update_vol_actiononpurge(ua, ua->argv[j], &mr);
            break;
         }
         done = true;
      }
   }

   /* Allow user to simply update all volumes */
   if (find_arg(ua, NT_("fromallpools")) > 0) {
      update_all_vols(ua);
      return 1;
   }

   for ( ; !done; ) {
      start_prompt(ua, _("Parameters to modify:\n"));
      add_prompt(ua, _("Volume Status"));              /* 0 */
      add_prompt(ua, _("Volume Retention Period"));    /* 1 */
      add_prompt(ua, _("Volume Use Duration"));        /* 2 */
      add_prompt(ua, _("Maximum Volume Jobs"));        /* 3 */
      add_prompt(ua, _("Maximum Volume Files"));       /* 4 */
      add_prompt(ua, _("Maximum Volume Bytes"));       /* 5 */
      add_prompt(ua, _("Recycle Flag"));               /* 6 */
      add_prompt(ua, _("Slot"));                       /* 7 */
      add_prompt(ua, _("InChanger Flag"));             /* 8 */
      add_prompt(ua, _("Volume Files"));               /* 9 */
      add_prompt(ua, _("Pool"));                       /* 10 */
      add_prompt(ua, _("Volume from Pool"));           /* 11 */
      add_prompt(ua, _("All Volumes from Pool"));      /* 12 */
      add_prompt(ua, _("All Volumes from all Pools")); /* 13 */
      add_prompt(ua, _("Enabled")),                    /* 14 */
      add_prompt(ua, _("RecyclePool")),                /* 15 */
      add_prompt(ua, _("Action On Purge")),            /* 16 */
      add_prompt(ua, _("Done"));                       /* 17 */
      i = do_prompt(ua, "", _("Select parameter to modify"), NULL, 0);  

      /* For All Volumes, All Volumes from Pool, and Done, we don't need
           * a Volume record */
      if ( i != 12 && i != 13 && i != 17) {
         if (!select_media_dbr(ua, &mr)) {  /* Get Volume record */
            return 0;
         }
         ua->info_msg(_("Updating Volume \"%s\"\n"), mr.VolumeName);
      }
      switch (i) {
      case 0:                         /* Volume Status */
         /* Modify Volume Status */
         ua->info_msg(_("Current Volume status is: %s\n"), mr.VolStatus);
         start_prompt(ua, _("Possible Values are:\n"));
         add_prompt(ua, NT_("Append")); 
         add_prompt(ua, NT_("Archive"));
         add_prompt(ua, NT_("Disabled"));
         add_prompt(ua, NT_("Full"));
         add_prompt(ua, NT_("Used"));
         add_prompt(ua, NT_("Cleaning"));
         if (strcmp(mr.VolStatus, NT_("Purged")) == 0) {
            add_prompt(ua, NT_("Recycle"));
         }
         add_prompt(ua, NT_("Read-Only"));
         if (do_prompt(ua, "", _("Choose new Volume Status"), ua->cmd, sizeof(mr.VolStatus)) < 0) {
            return 1;
         }
         update_volstatus(ua, ua->cmd, &mr);
         break;
      case 1:                         /* Retention */
         ua->info_msg(_("Current retention period is: %s\n"),
            edit_utime(mr.VolRetention, ed1, sizeof(ed1)));
         if (!get_cmd(ua, _("Enter Volume Retention period: "))) {
            return 0;
         }
         update_volretention(ua, ua->cmd, &mr);
         break;

      case 2:                         /* Use Duration */
         ua->info_msg(_("Current use duration is: %s\n"),
            edit_utime(mr.VolUseDuration, ed1, sizeof(ed1)));
         if (!get_cmd(ua, _("Enter Volume Use Duration: "))) {
            return 0;
         }
         update_voluseduration(ua, ua->cmd, &mr);
         break;

      case 3:                         /* Max Jobs */
         ua->info_msg(_("Current max jobs is: %u\n"), mr.MaxVolJobs);
         if (!get_pint(ua, _("Enter new Maximum Jobs: "))) {
            return 0;
         }
         update_volmaxjobs(ua, ua->cmd, &mr);
         break;

      case 4:                         /* Max Files */
         ua->info_msg(_("Current max files is: %u\n"), mr.MaxVolFiles);
         if (!get_pint(ua, _("Enter new Maximum Files: "))) {
            return 0;
         }
         update_volmaxfiles(ua, ua->cmd, &mr);
         break;

      case 5:                         /* Max Bytes */
         ua->info_msg(_("Current value is: %s\n"), edit_uint64(mr.MaxVolBytes, ed1));
         if (!get_cmd(ua, _("Enter new Maximum Bytes: "))) {
            return 0;
         }
         update_volmaxbytes(ua, ua->cmd, &mr);
         break;


      case 6:                         /* Recycle */
         ua->info_msg(_("Current recycle flag is: %s\n"),
            mr.Recycle==1?_("yes"):_("no"));
         if (!get_yesno(ua, _("Enter new Recycle status: "))) {
            return 0;
         }
         update_volrecycle(ua, ua->cmd, &mr);
         break;

      case 7:                         /* Slot */
         ua->info_msg(_("Current Slot is: %d\n"), mr.Slot);
         if (!get_pint(ua, _("Enter new Slot: "))) {
            return 0;
         }
         update_volslot(ua, ua->cmd, &mr);
         break;
         
      case 8:                         /* InChanger */
         ua->info_msg(_("Current InChanger flag is: %d\n"), mr.InChanger);
         bsnprintf(buf, sizeof(buf), _("Set InChanger flag for Volume \"%s\": yes/no: "),
            mr.VolumeName);
         if (!get_yesno(ua, buf)) {
            return 0;
         }
         mr.InChanger = ua->pint32_val;
         /*
          * Make sure to use db_update... rather than doing this directly,
          *   so that any Slot is handled correctly.
          */
         if (!db_update_media_record(ua->jcr, ua->db, &mr)) {
            ua->error_msg(_("Error updating media record Slot: ERR=%s"), db_strerror(ua->db));
         } else {
            ua->info_msg(_("New InChanger flag is: %d\n"), mr.InChanger);
         }
         break;


      case 9:                         /* Volume Files */
         int32_t VolFiles;
         ua->warning_msg(_("Warning changing Volume Files can result\n"
                        "in loss of data on your Volume\n\n"));
         ua->info_msg(_("Current Volume Files is: %u\n"), mr.VolFiles);
         if (!get_pint(ua, _("Enter new number of Files for Volume: "))) {
            return 0;
         }
         VolFiles = ua->pint32_val;
         if (VolFiles != (int)(mr.VolFiles + 1)) {
            ua->warning_msg(_("Normally, you should only increase Volume Files by one!\n"));
            if (!get_yesno(ua, _("Increase Volume Files? (yes/no): ")) || ua->pint32_val == 0) {
               break;
            }
         }
         query = get_pool_memory(PM_MESSAGE);
         Mmsg(query, "UPDATE Media SET VolFiles=%u WHERE MediaId=%s",
            VolFiles, edit_int64(mr.MediaId, ed1));
         if (!db_sql_query(ua->db, query, NULL, NULL)) {
            ua->error_msg("%s", db_strerror(ua->db));
         } else {
            ua->info_msg(_("New Volume Files is: %u\n"), VolFiles);
         }
         free_pool_memory(query);
         break;

      case 10:                        /* Volume's Pool */
         memset(&pr, 0, sizeof(POOL_DBR));
         pr.PoolId = mr.PoolId;
         if (!db_get_pool_record(ua->jcr, ua->db, &pr)) {
            ua->error_msg("%s", db_strerror(ua->db));
            return 0;
         }
         ua->info_msg(_("Current Pool is: %s\n"), pr.Name);
         if (!get_cmd(ua, _("Enter new Pool name: "))) {
            return 0;
         }
         update_vol_pool(ua, ua->cmd, &mr, &pr);
         return 1;

      case 11:
         update_vol_from_pool(ua, &mr);
         return 1;
      case 12:
         pool = select_pool_resource(ua);
         if (pool) {
            update_all_vols_from_pool(ua, pool->name());
         }
         return 1;

      case 13:
         update_all_vols(ua);
         return 1;

      case 14:
         ua->info_msg(_("Current Enabled is: %d\n"), mr.Enabled);
         if (!get_cmd(ua, _("Enter new Enabled: "))) {
            return 0;
         }
         if (strcasecmp(ua->cmd, "yes") == 0 || strcasecmp(ua->cmd, "true") == 0) {
            mr.Enabled = 1;
         } else if (strcasecmp(ua->cmd, "no") == 0 || strcasecmp(ua->cmd, "false") == 0) {
            mr.Enabled = 0;
         } else if (strcasecmp(ua->cmd, "archived") == 0) { 
            mr.Enabled = 2;
         } else {
            mr.Enabled = atoi(ua->cmd);
         }
         update_volenabled(ua, ua->cmd, &mr);
         break;

      case 15:
         memset(&pr, 0, sizeof(POOL_DBR));
         pr.PoolId = mr.RecyclePoolId;
         if (db_get_pool_record(ua->jcr, ua->db, &pr)) {
            ua->info_msg(_("Current RecyclePool is: %s\n"), pr.Name);
         } else {
            ua->info_msg(_("No current RecyclePool\n"));
         }
         if (!select_pool_dbr(ua, &pr, NT_("recyclepool"))) {
            return 0;
         }
         update_vol_recyclepool(ua, pr.Name, &mr);
         return 1;

      case 16:
         pm_strcpy(ret, "");
         ua->info_msg(_("Current ActionOnPurge is: %s\n"), 
                      action_on_purge_to_string(mr.ActionOnPurge, ret));
         if (!get_cmd(ua, _("Enter new ActionOnPurge (one of: Truncate, None): "))) {
            return 0;
         }

         update_vol_actiononpurge(ua, ua->cmd, &mr);
         break;

      default:                        /* Done or error */
         ua->info_msg(_("Selection terminated.\n"));
         return 1;
      }
   }
   return 1;
}
Exemplo n.º 19
0
/*
 * Update a Pool Record in the database.
 *  It is always updated from the Resource record.
 *
 *    update pool=<pool-name>
 *         updates pool from Pool resource
 *    update media pool=<pool-name> volume=<volume-name>
 *         changes pool info for volume
 *    update slots [scan=...]
 *         updates autochanger slots
 *    update stats [days=...]
 *         updates long term statistics
 */
int update_cmd(UAContext *ua, const char *cmd)
{
   static const char *kw[] = {
      NT_("media"),  /* 0 */
      NT_("volume"), /* 1 */
      NT_("pool"),   /* 2 */
      NT_("slots"),  /* 3 */
      NT_("slot"),   /* 4 */
      NT_("jobid"),  /* 5 */
      NT_("stats"),  /* 6 */
      NULL};

   if (!open_client_db(ua)) {
      return 1;
   }

   switch (find_arg_keyword(ua, kw)) {
   case 0:
   case 1:
      update_volume(ua);
      return 1;
   case 2:
      update_pool(ua);
      return 1;
   case 3:
   case 4:
      update_slots(ua);
      return 1;
   case 5:
      update_job(ua);
      return 1;
   case 6:
      update_stats(ua);
      return 1;
   default:
      break;
   }

   start_prompt(ua, _("Update choice:\n"));
   add_prompt(ua, _("Volume parameters"));
   add_prompt(ua, _("Pool from resource"));
   add_prompt(ua, _("Slots from autochanger"));
   add_prompt(ua, _("Long term statistics"));
   switch (do_prompt(ua, _("item"), _("Choose catalog item to update"), NULL, 0)) {
   case 0:
      update_volume(ua);
      break;
   case 1:
      update_pool(ua);
      break;
   case 2:
      update_slots(ua);
      break;
   case 3:
      update_stats(ua);
      break;
   default:
      break;
   }
   return 1;
}
Exemplo n.º 20
0
bool VskBase::enter_line(VskString& text, VskLineNo *lineno) {
    assert(lineno != NULL);
    m_line_pointer_helped = false;

    // parse
    shared_ptr<VskStmtsNode> stmts;
    VskTokenNodes nodes;
    if (!parse_line(text, lineno, stmts, nodes)) {
        if (m_internal_exec_mode == EXEC_IDLING) {
            do_prompt();
        }
        return false;
    }

    if (*lineno == 0) {
        // direct mode
        m_command_line_text = text;
        m_command_code = stmts;

        // update statements
        std::vector<VskControl> stack;
        if (!update_stmts_(stmts, 0, stack)) {
            return false;
        }
        if (stack.size() > 0) {
            switch (stack.back().m_type) {
            case VskControl::FOR:
                // FOR without NEXT
                do_error(26, stack.back().m_line_number);
                do_prompt();
                return false;
            case VskControl::WHILE:
                // WHILE without WEND
                do_error(30, stack.back().m_line_number);
                do_prompt();
                return false;
            default:
                break;
            }
        }
        // clear context and error
        m_context.clear();
        m_context_stack.clear();
        m_context.m_statements = stmts;
        m_editing = false;
        start_exec();
    } else {
        // program code
        m_contable = false;
        if (text.empty()) {
            m_program_list.erase(*lineno);
            m_program_nodes.erase(*lineno);
            m_program_codes.erase(*lineno);
        } else if (is_valid_lineno(*lineno)) {
            m_program_list[*lineno] = text;
            m_program_nodes[*lineno] = nodes;
            m_program_codes[*lineno] = stmts;
            m_line_pointer = *lineno;
        } else {
            // Syntax error
            do_error(2, 0);
            if (m_internal_exec_mode == EXEC_IDLING) {
                do_prompt();
            }
            return false;
        }
    }
    return true;
} // VskBase::enter_line
Exemplo n.º 21
0
Arquivo: browser.c Projeto: ris21/yoda
/* Our main file browser function.  path is the tilde-expanded path we
 * start browsing from. */
char *do_browser(char *path, DIR *dir)
{
    char *retval = NULL;
    int kbinput;
    bool old_const_update = ISSET(CONST_UPDATE);
    char *prev_dir = NULL;
	/* The directory we were in before backing up to "..". */
    char *ans = NULL;
	/* The last answer the user typed at the statusbar prompt. */
    size_t old_selected;
	/* The selected file we had before the current selected file. */
    functionptrtype func;
	/* The function of the key the user typed in. */

    curs_set(0);
    blank_statusbar();
    bottombars(MBROWSER);
    wnoutrefresh(bottomwin);

    UNSET(CONST_UPDATE);

    ans = mallocstrcpy(NULL, "");

  change_browser_directory:
	/* We go here after we select a new directory. */

    /* Start with no key pressed. */
    kbinput = ERR;

    path = mallocstrassn(path, get_full_path(path));

    /* Save the current path in order to be used later. */
    path_save = path;

    assert(path != NULL && path[strlen(path) - 1] == '/');

    /* Get the file list, and set longest and width in the process. */
    browser_init(path, dir);

    assert(filelist != NULL);

    /* Sort the file list. */
    qsort(filelist, filelist_len, sizeof(char *), diralphasort);

    /* If prev_dir isn't NULL, select the directory saved in it, and
     * then blow it away. */
    if (prev_dir != NULL) {
	browser_select_dirname(prev_dir);

	free(prev_dir);
	prev_dir = NULL;
    /* Otherwise, select the first file or directory in the list. */
    } else
	selected = 0;

    old_selected = (size_t)-1;

    titlebar(path);

    while (TRUE) {
	struct stat st;
	int i;
	size_t fileline = selected / width;
		/* The line number the selected file is on. */
	char *new_path;
		/* The path we switch to at the "Go to Directory"
		 * prompt. */

	/* Display the file list if we don't have a key, or if the
	 * selected file has changed, and set width in the process. */
	if (kbinput == ERR || old_selected != selected)
	    browser_refresh();

	old_selected = selected;

	kbinput = get_kbinput(edit);

#ifndef NANO_TINY
	if (kbinput == KEY_WINCH) {
	    kbinput = ERR;
	    curs_set(0);
	    continue;
	}
#endif

#ifndef DISABLE_MOUSE
	if (kbinput == KEY_MOUSE) {
	    int mouse_x, mouse_y;

	    /* We can click on the edit window to select a
	     * filename. */
	    if (get_mouseinput(&mouse_x, &mouse_y, TRUE) == 0 &&
		wmouse_trafo(edit, &mouse_y, &mouse_x, FALSE)) {
		/* longest is the width of each column.  There
		 * are two spaces between each column. */
		selected = (fileline / editwinrows) *
				(editwinrows * width) + (mouse_y *
				width) + (mouse_x / (longest + 2));

		/* If they clicked beyond the end of a row,
		 * select the last filename in that row. */
		if (mouse_x > width * (longest + 2))
		    selected--;

		/* If we're off the screen, select the last filename. */
		if (selected > filelist_len - 1)
		    selected = filelist_len - 1;

		/* If we selected the same filename as last time,
		 * put back the Enter key so that it's read in. */
		if (old_selected == selected)
		    unget_kbinput(sc_seq_or(do_enter_void, 0), FALSE, FALSE);
	    }
	}
#endif /* !DISABLE_MOUSE */

	func = parse_browser_input(&kbinput);

	if (func == total_refresh) {
	    total_redraw();
	} else if (func == do_help_void) {
#ifndef DISABLE_HELP
	    do_help_void();
	    /* Perhaps the window dimensions have changed. */
	    browser_refresh();
	    curs_set(0);
#else
	    nano_disabled_msg();
#endif
	} else if (func == do_search) {
	    /* Search for a filename. */
	    curs_set(1);
	    do_filesearch();
	    curs_set(0);
	} else if (func == do_research) {
	    /* Search for another filename. */
	    do_fileresearch();
	} else if (func == do_page_up) {
	    if (selected >= (editwinrows + fileline % editwinrows) * width)
		selected -= (editwinrows + fileline % editwinrows) * width;
	    else
		selected = 0;
	} else if (func == do_page_down) {
	    selected += (editwinrows - fileline % editwinrows) * width;
	    if (selected > filelist_len - 1)
		selected = filelist_len - 1;
	} else if (func == do_first_file) {
	    selected = 0;
	} else if (func == do_last_file) {
	    selected = filelist_len - 1;
	} else if (func == goto_dir_void) {
	    /* Go to a specific directory. */
	    curs_set(1);
	    i = do_prompt(TRUE,
#ifndef DISABLE_TABCOMP
			FALSE,
#endif
			MGOTODIR, ans,
#ifndef DISABLE_HISTORIES
			NULL,
#endif
			/* TRANSLATORS: This is a prompt. */
			browser_refresh, _("Go To Directory"));

	    curs_set(0);
	    bottombars(MBROWSER);

	    /* If the directory begins with a newline (i.e. an
	     * encoded null), treat it as though it's blank. */
	    if (i < 0 || *answer == '\n') {
		/* We canceled.  Indicate that on the statusbar, and
		* blank out ans, since we're done with it. */
		statusbar(_("Cancelled"));
		ans = mallocstrcpy(ans, "");
		continue;
	    } else if (i != 0) {
		/* Put back the "Go to Directory" key and save
		 * answer in ans, so that the file list is displayed
		 * again, the prompt is displayed again, and what we
		 * typed before at the prompt is displayed again. */
		unget_kbinput(sc_seq_or(do_gotolinecolumn_void, 0), FALSE, FALSE);
		ans = mallocstrcpy(ans, answer);
		continue;
	    }

	    /* We have a directory.  Blank out ans, since we're done
	     * with it. */
	    ans = mallocstrcpy(ans, "");

	    /* Convert newlines to nulls, just before we go to the
	     * directory. */
	    sunder(answer);
	    align(&answer);

	    new_path = real_dir_from_tilde(answer);

	    if (new_path[0] != '/') {
		new_path = charealloc(new_path, strlen(path) +
				strlen(answer) + 1);
		sprintf(new_path, "%s%s", path, answer);
	    }

#ifndef DISABLE_OPERATINGDIR
	    if (check_operating_dir(new_path, FALSE)) {
		statusbar(_("Can't go outside of %s in restricted mode"),
				operating_dir);
		free(new_path);
		continue;
	    }
#endif

	    dir = opendir(new_path);
	    if (dir == NULL) {
		/* We can't open this directory for some reason.
		* Complain. */
		statusbar(_("Error reading %s: %s"), answer,
				strerror(errno));
		beep();
		free(new_path);
		continue;
	    }

	    /* Start over again with the new path value. */
	    free(path);
	    path = new_path;
	    goto change_browser_directory;
	} else if (func == do_up_void) {
	    if (selected >= width)
		selected -= width;
	} else if (func == do_down_void) {
	    if (selected + width <= filelist_len - 1)
		selected += width;
	} else if (func == do_left) {
	    if (selected > 0)
		selected--;
	} else if (func == do_right) {
	    if (selected < filelist_len - 1)
		selected++;
	} else if (func == do_enter_void) {
	    /* We can't move up from "/". */
	    if (strcmp(filelist[selected], "/..") == 0) {
		statusbar(_("Can't move up a directory"));
		beep();
		continue;
	    }

#ifndef DISABLE_OPERATINGDIR
	    /* Note: The selected file can be outside the operating
	     * directory if it's ".." or if it's a symlink to a
	     * directory outside the operating directory. */
	    if (check_operating_dir(filelist[selected], FALSE)) {
		statusbar(_("Can't go outside of %s in restricted mode"),
				operating_dir);
		beep();
		continue;
	    }
#endif

	    if (stat(filelist[selected], &st) == -1) {
		/* We can't open this file for some reason.
		 * Complain. */
		 statusbar(_("Error reading %s: %s"),
				filelist[selected], strerror(errno));
		 beep();
		 continue;
	    }

	    if (!S_ISDIR(st.st_mode)) {
		/* We've successfully opened a file, we're done, so
		 * get out. */
		retval = mallocstrcpy(NULL, filelist[selected]);
		break;
	    } else if (strcmp(tail(filelist[selected]), "..") == 0)
		/* We've successfully opened the parent directory,
		 * save the current directory in prev_dir, so that
		 * we can easily return to it by hitting Enter. */
		prev_dir = mallocstrcpy(NULL, striponedir(filelist[selected]));

	    dir = opendir(filelist[selected]);
	    if (dir == NULL) {
		/* We can't open this directory for some reason.
		 * Complain. */
		statusbar(_("Error reading %s: %s"),
				filelist[selected], strerror(errno));
		beep();
		continue;
	    }

	    path = mallocstrcpy(path, filelist[selected]);

	    /* Start over again with the new path value. */
	    goto change_browser_directory;
	} else if (func == do_exit) {
	    /* Exit from the file browser. */
	    break;
	}
    }
    titlebar(NULL);
    edit_refresh();
    curs_set(1);
    if (old_const_update)
	SET(CONST_UPDATE);

    free(path);
    free(ans);

    free_chararray(filelist, filelist_len);
    filelist = NULL;
    filelist_len = 0;

    return retval;
}
Exemplo n.º 22
0
Arquivo: search.c Projeto: ris21/yoda
/* Go to the specified line and column, or ask for them if interactive
 * is TRUE.  Save the x-coordinate and y-coordinate if save_pos is TRUE.
 * Update the screen afterwards if allow_update is TRUE.  Note that both
 * the line and column numbers should be one-based. */
void do_gotolinecolumn(ssize_t line, ssize_t column, bool use_answer,
	bool interactive, bool save_pos, bool allow_update)
{
    if (interactive) {
	char *ans = mallocstrcpy(NULL, answer);
	functionptrtype func;

	/* Ask for the line and column. */
	int i = do_prompt(FALSE,
#ifndef DISABLE_TABCOMP
		TRUE,
#endif
		MGOTOLINE, use_answer ? ans : "",
#ifndef DISABLE_HISTORIES
		NULL,
#endif
		/* TRANSLATORS: This is a prompt. */
		edit_refresh, _("Enter line number, column number"));

	free(ans);

	/* Cancel, or Enter with blank string. */
	if (i < 0) {
	    statusbar(_("Cancelled"));
	    display_main_list();
	    return;
	}

	func = func_from_key(&i);

	if (func == gototext_void) {
	    /* Keep answer up on the statusbar. */
	    search_init(TRUE, TRUE);

	    do_search();
	    return;
	}

	/* Do a bounds check.  Display a warning on an out-of-bounds
	 * line or column number only if we hit Enter at the statusbar
	 * prompt. */
	if (!parse_line_column(answer, &line, &column) || line < 1 ||
		column < 1) {
	    if (i == 0)
		statusbar(_("Invalid line or column number"));
	    display_main_list();
	    return;
	}
    } else {
	if (line < 1)
	    line = openfile->current->lineno;

	if (column < 1)
	    column = openfile->placewewant + 1;
    }

    for (openfile->current = openfile->fileage;
	openfile->current != openfile->filebot && line > 1; line--)
	openfile->current = openfile->current->next;

    openfile->current_x = actual_x(openfile->current->data, column - 1);
    openfile->placewewant = column - 1;

    /* Put the top line of the edit window in range of the current line.
     * If save_pos is TRUE, don't change the cursor position when doing
     * it. */
    edit_update(save_pos ? NONE : CENTER);

    /* If allow_update is TRUE, update the screen. */
    if (allow_update) {
	edit_refresh();
	display_main_list();
    }
}
Exemplo n.º 23
0
Arquivo: search.c Projeto: ris21/yoda
/* Replace a string. */
void do_replace(void)
{
    linestruct *edittop_save, *begin;
    size_t begin_x, pww_save;
    ssize_t numreplaced;
    int i;

    if (ISSET(VIEW_MODE)) {
	print_view_warning();
	search_replace_abort();
	return;
    }

    i = search_init(TRUE, FALSE);
    if (i == -1) {
	/* Cancel, Go to Line, blank search string, or regcomp() failed. */
	search_replace_abort();
	return;
    } else if (i == -2) {
	/* No Replace. */
	do_search();
	return;
    } else if (i == 1)
	/* Case Sensitive, Backwards, or Regexp search toggle. */
	do_replace();

    if (i != 0)
	return;

    /* If answer is not "", add answer to the search history list and
     * copy answer into last_search. */
    if (answer[0] != '\0') {
#ifndef DISABLE_HISTORIES
	update_history(&search_history, answer);
#endif
	last_search = mallocstrcpy(last_search, answer);
    }

    last_replace = mallocstrcpy(last_replace, "");

    i = do_prompt(FALSE,
#ifndef DISABLE_TABCOMP
	TRUE,
#endif
	MREPLACEWITH, last_replace,
#ifndef DISABLE_HISTORIES
	&replace_history,
#endif
	/* TRANSLATORS: This is a prompt. */
	edit_refresh, _("Replace with"));

#ifndef DISABLE_HISTORIES
    /* If the replace string is not "", add it to the replace history list. */
    if (i == 0)
	update_history(&replace_history, answer);
#endif

    if (i != 0 && i != -2) {
	if (i == -1) {		/* Cancel. */
	    if (last_replace[0] != '\0')
		answer = mallocstrcpy(answer, last_replace);
	    statusbar(_("Cancelled"));
	}
	search_replace_abort();
	return;
    }

    last_replace = mallocstrcpy(last_replace, answer);

    /* Save where we are. */
    edittop_save = openfile->edittop;
    begin = openfile->current;
    begin_x = openfile->current_x;
    pww_save = openfile->placewewant;

    numreplaced = do_replace_loop(
#ifndef DISABLE_SPELLER
	FALSE,
#endif
	NULL, begin, &begin_x, last_search);

    /* Restore where we were. */
    openfile->edittop = edittop_save;
    openfile->current = begin;
    openfile->current_x = begin_x;
    openfile->placewewant = pww_save;

    edit_refresh();

    if (numreplaced >= 0)
	statusbar(P_("Replaced %lu occurrence",
		"Replaced %lu occurrences", (unsigned long)numreplaced),
		(unsigned long)numreplaced);

    search_replace_abort();
}
Exemplo n.º 24
0
/*
 * Read a file containing SQL queries and prompt
 *  the user to select which one.
 *
 *   File format:
 *   #  => comment
 *   :prompt for query
 *   *prompt for subst %1
 *   *prompt for subst %2
 *   ...
 *   SQL statement possibly terminated by ;
 *   :next query prompt
 */
bool query_cmd(UAContext *ua, const char *cmd)
{
   FILE *fd = NULL;
   POOLMEM *query = get_pool_memory(PM_MESSAGE);
   char line[1000];
   int i, item, len;
   char *prompt[9];
   int nprompt = 0;
   char *query_file = me->query_file;

   if (!open_client_db(ua, true)) {
      goto bail_out;
   }
   if ((fd=fopen(query_file, "rb")) == NULL) {
      berrno be;
      ua->error_msg(_("Could not open %s: ERR=%s\n"), query_file,
         be.bstrerror());
      goto bail_out;
   }

   start_prompt(ua, _("Available queries:\n"));
   while (fgets(line, sizeof(line), fd) != NULL) {
      if (line[0] == ':') {
         strip_trailing_junk(line);
         add_prompt(ua, line+1);
      }
   }
   if ((item=do_prompt(ua, "", _("Choose a query"), NULL, 0)) < 0) {
      goto bail_out;
   }
   rewind(fd);
   i = -1;
   while (fgets(line, sizeof(line), fd) != NULL) {
      if (line[0] == ':') {
         i++;
      }
      if (i == item) {
         break;
      }
   }
   if (i != item) {
      ua->error_msg(_("Could not find query.\n"));
      goto bail_out;
   }
   query[0] = 0;
   for (i=0; i<9; i++) {
      prompt[i] = NULL;
   }
   while (fgets(line, sizeof(line), fd) != NULL) {
      if (line[0] == '#') {
         continue;
      }
      if (line[0] == ':') {
         break;
      }
      strip_trailing_junk(line);
      len = strlen(line);
      if (line[0] == '*') {            /* prompt */
         if (nprompt >= 9) {
            ua->error_msg(_("Too many prompts in query, max is 9.\n"));
         } else {
            line[len++] = ' ';
            line[len] = 0;
            prompt[nprompt++] = bstrdup(line+1);
            continue;
         }
      }
      if (*query != 0) {
         pm_strcat(query, " ");
      }
      pm_strcat(query, line);
      if (line[len-1] != ';') {
         continue;
      }
      line[len-1] = 0;             /* zap ; */
      if (query[0] != 0) {
         query = substitute_prompts(ua, query, prompt, nprompt);
         Dmsg1(100, "Query2=%s\n", query);
         if (query[0] == '!') {
            db_list_sql_query(ua->jcr, ua->db, query+1, ua->send, VERT_LIST, false);
         } else if (!db_list_sql_query(ua->jcr, ua->db, query, ua->send, HORZ_LIST, true)) {
            ua->send_msg("%s\n", query);
         }
         query[0] = 0;
      }
   } /* end while */

   if (query[0] != 0) {
      query = substitute_prompts(ua, query, prompt, nprompt);
      Dmsg1(100, "Query2=%s\n", query);
         if (query[0] == '!') {
            db_list_sql_query(ua->jcr, ua->db, query+1, ua->send, VERT_LIST, false);
         } else if (!db_list_sql_query(ua->jcr, ua->db, query, ua->send, HORZ_LIST, true)) {
            ua->error_msg("%s\n", query);
         }
   }

bail_out:
   if (fd) {
      fclose(fd);
   }
   free_pool_memory(query);
   for (i=0; i<nprompt; i++) {
      free(prompt[i]);
   }
   return true;
}
Exemplo n.º 25
0
/*
 * The first step in the restore process is for the user to
 *  select a list of JobIds from which he will subsequently
 *  select which files are to be restored.
 *
 *  Returns:  2  if filename list made
 *            1  if jobid list made
 *            0  on error
 */
static int user_select_jobids_or_files(UAContext *ua, RESTORE_CTX *rx)
{
   char *p;
   char date[MAX_TIME_LENGTH];
   bool have_date = false;
   /* Include current second if using current time */
   utime_t now = time(NULL) + 1;
   JobId_t JobId;
   JOB_DBR jr = { (JobId_t)-1 };
   bool done = false;
   int i, j;
   const char *list[] = {
      _("List last 20 Jobs run"),
      _("List Jobs where a given File is saved"),
      _("Enter list of comma separated JobIds to select"),
      _("Enter SQL list command"),
      _("Select the most recent backup for a client"),
      _("Select backup for a client before a specified time"),
      _("Enter a list of files to restore"),
      _("Enter a list of files to restore before a specified time"),
      _("Find the JobIds of the most recent backup for a client"),
      _("Find the JobIds for a backup for a client before a specified time"),
      _("Enter a list of directories to restore for found JobIds"),
      _("Select full restore to a specified Job date"),
      _("Cancel"),
      NULL
   };

   const char *kw[] = {
       /*
        * These keywords are handled in a for loop
        */
      "jobid",         /* 0 */
      "current",       /* 1 */
      "before",        /* 2 */
      "file",          /* 3 */
      "directory",     /* 4 */
      "select",        /* 5 */
      "pool",          /* 6 */
      "all",           /* 7 */

      /*
       * The keyword below are handled by individual arg lookups
       */
      "client",        /* 8 */
      "storage",       /* 9 */
      "fileset",       /* 10 */
      "where",         /* 11 */
      "yes",           /* 12 */
      "bootstrap",     /* 13 */
      "done",          /* 14 */
      "strip_prefix",  /* 15 */
      "add_prefix",    /* 16 */
      "add_suffix",    /* 17 */
      "regexwhere",    /* 18 */
      "restoreclient", /* 19 */
      "copies",        /* 20 */
      "comment",       /* 21 */
      "restorejob",    /* 22 */
      "replace",       /* 23 */
      "pluginoptions", /* 24 */
      NULL
   };

   rx->JobIds[0] = 0;

   for (i = 1; i<ua->argc; i++) {        /* loop through arguments */
      bool found_kw = false;
      for (j = 0; kw[j]; j++) {          /* loop through keywords */
         if (bstrcasecmp(kw[j], ua->argk[i])) {
            found_kw = true;
            break;
         }
      }
      if (!found_kw) {
         ua->error_msg(_("Unknown keyword: %s\n"), ua->argk[i]);
         return 0;
      }
      /* Found keyword in kw[] list, process it */
      switch (j) {
      case 0:                            /* jobid */
         if (!has_value(ua, i)) {
            return 0;
         }
         if (*rx->JobIds != 0) {
            pm_strcat(rx->JobIds, ",");
         }
         pm_strcat(rx->JobIds, ua->argv[i]);
         done = true;
         break;
      case 1:                            /* current */
         /*
          * Note, we add one second here just to include any job
          *  that may have finished within the current second,
          *  which happens a lot in scripting small jobs.
          */
         bstrutime(date, sizeof(date), now);
         have_date = true;
         break;
      case 2:                            /* before */
         if (have_date || !has_value(ua, i)) {
            return 0;
         }
         if (str_to_utime(ua->argv[i]) == 0) {
            ua->error_msg(_("Improper date format: %s\n"), ua->argv[i]);
            return 0;
         }
         bstrncpy(date, ua->argv[i], sizeof(date));
         have_date = true;
         break;
      case 3:                            /* file */
      case 4:                            /* dir */
         if (!has_value(ua, i)) {
            return 0;
         }
         if (!have_date) {
            bstrutime(date, sizeof(date), now);
         }
         if (!get_client_name(ua, rx)) {
            return 0;
         }
         pm_strcpy(ua->cmd, ua->argv[i]);
         insert_one_file_or_dir(ua, rx, date, j==4);
         return 2;
      case 5:                            /* select */
         if (!have_date) {
            bstrutime(date, sizeof(date), now);
         }
         if (!select_backups_before_date(ua, rx, date)) {
            return 0;
         }
         done = true;
         break;
      case 6:                            /* pool specified */
         if (!has_value(ua, i)) {
            return 0;
         }
         rx->pool = (POOLRES *)GetResWithName(R_POOL, ua->argv[i]);
         if (!rx->pool) {
            ua->error_msg(_("Error: Pool resource \"%s\" does not exist.\n"), ua->argv[i]);
            return 0;
         }
         if (!acl_access_ok(ua, Pool_ACL, ua->argv[i], true)) {
            rx->pool = NULL;
            ua->error_msg(_("Error: Pool resource \"%s\" access not allowed.\n"), ua->argv[i]);
            return 0;
         }
         break;
      case 7:                         /* all specified */
         rx->all = true;
         break;
      default:
         /*
          * All keywords 7 or greater are ignored or handled by a select prompt
          */
         break;
      }
   }

   if (!done) {
      ua->send_msg(_("\nFirst you select one or more JobIds that contain files\n"
                  "to be restored. You will be presented several methods\n"
                  "of specifying the JobIds. Then you will be allowed to\n"
                  "select which files from those JobIds are to be restored.\n\n"));
   }

   /* If choice not already made above, prompt */
   for ( ; !done; ) {
      char *fname;
      int len;
      bool gui_save;
      db_list_ctx jobids;

      start_prompt(ua, _("To select the JobIds, you have the following choices:\n"));
      for (int i=0; list[i]; i++) {
         add_prompt(ua, list[i]);
      }
      done = true;
      switch (do_prompt(ua, "", _("Select item: "), NULL, 0)) {
      case -1:                        /* error or cancel */
         return 0;
      case 0:                         /* list last 20 Jobs run */
         if (!acl_access_ok(ua, Command_ACL, NT_("sqlquery"), true)) {
            ua->error_msg(_("SQL query not authorized.\n"));
            return 0;
         }
         gui_save = ua->jcr->gui;
         ua->jcr->gui = true;
         db_list_sql_query(ua->jcr, ua->db, uar_list_jobs, ua->send, HORZ_LIST, true);
         ua->jcr->gui = gui_save;
         done = false;
         break;
      case 1:                         /* list where a file is saved */
         if (!get_client_name(ua, rx)) {
            return 0;
         }
         if (!get_cmd(ua, _("Enter Filename (no path):"))) {
            return 0;
         }
         len = strlen(ua->cmd);
         fname = (char *)malloc(len * 2 + 1);
         db_escape_string(ua->jcr, ua->db, fname, ua->cmd, len);
         Mmsg(rx->query, uar_file[db_get_type_index(ua->db)], rx->ClientName, fname);
         free(fname);
         gui_save = ua->jcr->gui;
         ua->jcr->gui = true;
         db_list_sql_query(ua->jcr, ua->db, rx->query, ua->send, HORZ_LIST, true);
         ua->jcr->gui = gui_save;
         done = false;
         break;
      case 2:                         /* enter a list of JobIds */
         if (!get_cmd(ua, _("Enter JobId(s), comma separated, to restore: "))) {
            return 0;
         }
         pm_strcpy(rx->JobIds, ua->cmd);
         break;
      case 3:                         /* Enter an SQL list command */
         if (!acl_access_ok(ua, Command_ACL, NT_("sqlquery"), true)) {
            ua->error_msg(_("SQL query not authorized.\n"));
            return 0;
         }
         if (!get_cmd(ua, _("Enter SQL list command: "))) {
            return 0;
         }
         gui_save = ua->jcr->gui;
         ua->jcr->gui = true;
         db_list_sql_query(ua->jcr, ua->db, ua->cmd, ua->send, HORZ_LIST, true);
         ua->jcr->gui = gui_save;
         done = false;
         break;
      case 4:                         /* Select the most recent backups */
         if (!have_date) {
            bstrutime(date, sizeof(date), now);
         }
         if (!select_backups_before_date(ua, rx, date)) {
            return 0;
         }
         break;
      case 5:                         /* select backup at specified time */
         if (!have_date) {
            if (!get_date(ua, date, sizeof(date))) {
               return 0;
            }
         }
         if (!select_backups_before_date(ua, rx, date)) {
            return 0;
         }
         break;
      case 6:                         /* Enter files */
         if (!have_date) {
            bstrutime(date, sizeof(date), now);
         }
         if (!get_client_name(ua, rx)) {
            return 0;
         }
         ua->send_msg(_("Enter file names with paths, or < to enter a filename\n"
                        "containing a list of file names with paths, and terminate\n"
                        "them with a blank line.\n"));
         for ( ;; ) {
            if (!get_cmd(ua, _("Enter full filename: "))) {
               return 0;
            }
            len = strlen(ua->cmd);
            if (len == 0) {
               break;
            }
            insert_one_file_or_dir(ua, rx, date, false);
         }
         return 2;
       case 7:                        /* enter files backed up before specified time */
         if (!have_date) {
            if (!get_date(ua, date, sizeof(date))) {
               return 0;
            }
         }
         if (!get_client_name(ua, rx)) {
            return 0;
         }
         ua->send_msg(_("Enter file names with paths, or < to enter a filename\n"
                        "containing a list of file names with paths, and terminate\n"
                        "them with a blank line.\n"));
         for ( ;; ) {
            if (!get_cmd(ua, _("Enter full filename: "))) {
               return 0;
            }
            len = strlen(ua->cmd);
            if (len == 0) {
               break;
            }
            insert_one_file_or_dir(ua, rx, date, false);
         }
         return 2;

      case 8:                         /* Find JobIds for current backup */
         if (!have_date) {
            bstrutime(date, sizeof(date), now);
         }
         if (!select_backups_before_date(ua, rx, date)) {
            return 0;
         }
         done = false;
         break;

      case 9:                         /* Find JobIds for give date */
         if (!have_date) {
            if (!get_date(ua, date, sizeof(date))) {
               return 0;
            }
         }
         if (!select_backups_before_date(ua, rx, date)) {
            return 0;
         }
         done = false;
         break;

      case 10:                        /* Enter directories */
         if (*rx->JobIds != 0) {
            ua->send_msg(_("You have already selected the following JobIds: %s\n"),
               rx->JobIds);
         } else if (get_cmd(ua, _("Enter JobId(s), comma separated, to restore: "))) {
            if (*rx->JobIds != 0 && *ua->cmd) {
               pm_strcat(rx->JobIds, ",");
            }
            pm_strcat(rx->JobIds, ua->cmd);
         }
         if (*rx->JobIds == 0 || *rx->JobIds == '.') {
            *rx->JobIds = 0;
            return 0;                 /* nothing entered, return */
         }
         if (!have_date) {
            bstrutime(date, sizeof(date), now);
         }
         if (!get_client_name(ua, rx)) {
            return 0;
         }
         ua->send_msg(_("Enter full directory names or start the name\n"
                        "with a < to indicate it is a filename containing a list\n"
                        "of directories and terminate them with a blank line.\n"));
         for ( ;; ) {
            if (!get_cmd(ua, _("Enter directory name: "))) {
               return 0;
            }
            len = strlen(ua->cmd);
            if (len == 0) {
               break;
            }
            /* Add trailing slash to end of directory names */
            if (ua->cmd[0] != '<' && !IsPathSeparator(ua->cmd[len-1])) {
               strcat(ua->cmd, "/");
            }
            insert_one_file_or_dir(ua, rx, date, true);
         }
         return 2;

      case 11:                        /* Choose a jobid and select jobs */
         if (!get_cmd(ua, _("Enter JobId to get the state to restore: ")) ||
             !is_an_integer(ua->cmd))
         {
            return 0;
         }

         memset(&jr, 0, sizeof(jr));
         jr.JobId = str_to_int64(ua->cmd);
         if (!db_get_job_record(ua->jcr, ua->db, &jr)) {
            ua->error_msg(_("Unable to get Job record for JobId=%s: ERR=%s\n"),
                          ua->cmd, db_strerror(ua->db));
            return 0;
         }
         ua->send_msg(_("Selecting jobs to build the Full state at %s\n"),
                      jr.cStartTime);
         jr.JobLevel = L_INCREMENTAL; /* Take Full+Diff+Incr */
         if (!db_accurate_get_jobids(ua->jcr, ua->db, &jr, &jobids)) {
            return 0;
         }
         pm_strcpy(rx->JobIds, jobids.list);
         Dmsg1(30, "Item 12: jobids = %s\n", rx->JobIds);
         break;
      case 12:                        /* Cancel or quit */
         return 0;
      }
   }

   memset(&jr, 0, sizeof(jr));
   POOLMEM *JobIds = get_pool_memory(PM_FNAME);
   *JobIds = 0;
   rx->TotalFiles = 0;
   /*
    * Find total number of files to be restored, and filter the JobId
    *  list to contain only ones permitted by the ACL conditions.
    */
   for (p=rx->JobIds; ; ) {
      char ed1[50];
      int status = get_next_jobid_from_list(&p, &JobId);
      if (status < 0) {
         ua->error_msg(_("Invalid JobId in list.\n"));
         free_pool_memory(JobIds);
         return 0;
      }
      if (status == 0) {
         break;
      }
      if (jr.JobId == JobId) {
         continue;                    /* duplicate of last JobId */
      }
      memset(&jr, 0, sizeof(jr));
      jr.JobId = JobId;
      if (!db_get_job_record(ua->jcr, ua->db, &jr)) {
         ua->error_msg(_("Unable to get Job record for JobId=%s: ERR=%s\n"),
            edit_int64(JobId, ed1), db_strerror(ua->db));
         free_pool_memory(JobIds);
         return 0;
      }
      if (!acl_access_ok(ua, Job_ACL, jr.Name, true)) {
         ua->error_msg(_("Access to JobId=%s (Job \"%s\") not authorized. Not selected.\n"),
            edit_int64(JobId, ed1), jr.Name);
         continue;
      }
      if (*JobIds != 0) {
         pm_strcat(JobIds, ",");
      }
      pm_strcat(JobIds, edit_int64(JobId, ed1));
      rx->TotalFiles += jr.JobFiles;
   }
   free_pool_memory(rx->JobIds);
   rx->JobIds = JobIds;               /* Set ACL filtered list */
   if (*rx->JobIds == 0) {
      ua->warning_msg(_("No Jobs selected.\n"));
      return 0;
   }

   if (strchr(rx->JobIds,',')) {
      ua->info_msg(_("You have selected the following JobIds: %s\n"), rx->JobIds);
   } else {
      ua->info_msg(_("You have selected the following JobId: %s\n"), rx->JobIds);
   }
   return true;
}
Exemplo n.º 26
0
/*
 * .die (seg fault)
 * .dump (sm_dump)
 * .exit (no arg => .quit)
 */
bool dot_admin_cmds(UAContext *ua, const char *cmd)
{
   pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
   STORERES *store = NULL;
   CLIENTRES *client = NULL;
   bool dir=false;
   bool do_deadlock=false;
   const char *remote_cmd;
   int i;
   JCR *jcr = NULL;
   int a;
   if (strncmp(ua->argk[0], ".die", 4) == 0) {
      if (find_arg(ua, "deadlock") > 0) {
         do_deadlock = true;
         remote_cmd = ".die deadlock";
      } else {
         remote_cmd = ".die";
      }
   } else if (strncmp(ua->argk[0], ".dump", 5) == 0) {
      remote_cmd = "sm_dump";
   } else if (strncmp(ua->argk[0], ".exit", 5) == 0) {
      remote_cmd = "exit";
   } else {
      ua->error_msg(_("Unknown command: %s\n"), ua->argk[0]);
      return true;
   }
   /* General debug? */
   for (i = 1; i < ua->argc; i++) {
      if (bstrcasecmp(ua->argk[i], "dir") ||
          bstrcasecmp(ua->argk[i], "director")) {
         dir = true;
      }
      if (bstrcasecmp(ua->argk[i], "client") ||
          bstrcasecmp(ua->argk[i], "fd")) {
         client = NULL;
         if (ua->argv[i]) {
            client = (CLIENTRES *)GetResWithName(R_CLIENT, ua->argv[i]);
         }
         if (!client) {
            client = select_client_resource(ua);
         }
      }

      if (bstrcasecmp(ua->argk[i], NT_("store")) ||
          bstrcasecmp(ua->argk[i], NT_("storage")) ||
          bstrcasecmp(ua->argk[i], NT_("sd"))) {
         store = NULL;
         if (ua->argv[i]) {
            store = (STORERES *)GetResWithName(R_STORAGE, ua->argv[i]);
         }
         if (!store) {
            store = get_storage_resource(ua);
         }
      }
   }

   if (!dir && !store && !client) {
      /*
       * We didn't find an appropriate keyword above, so
       * prompt the user.
       */
      start_prompt(ua, _("Available daemons are: \n"));
      add_prompt(ua, _("Director"));
      add_prompt(ua, _("Storage"));
      add_prompt(ua, _("Client"));
      switch(do_prompt(ua, "", _("Select daemon type to make die"), NULL, 0)) {
      case 0:                         /* Director */
         dir=true;
         break;
      case 1:
         store = get_storage_resource(ua);
         break;
      case 2:
         client = select_client_resource(ua);
         break;
      default:
         break;
      }
   }

   if (store) {
      switch (store->Protocol) {
      case APT_NDMPV2:
      case APT_NDMPV3:
      case APT_NDMPV4:
         ua->warning_msg(_("Storage has non-native protocol.\n"));
         break;
      default:
         do_storage_cmd(ua, store, remote_cmd);
         break;
      }
   }

   if (client) {
      do_client_cmd(ua, client, remote_cmd);
   }

   if (dir) {
      if (strncmp(remote_cmd, ".die", 4) == 0) {
         if (do_deadlock) {
            ua->send_msg(_("The Director will generate a deadlock.\n"));
            P(mutex);
            P(mutex);
         }
         ua->send_msg(_("The Director will segment fault.\n"));
         a = jcr->JobId; /* ref NULL pointer */
         jcr->JobId = 1000; /* another ref NULL pointer */
         jcr->JobId = a;

      } else if (strncmp(remote_cmd, ".dump", 5) == 0) {
         sm_dump(false, true);
      } else if (strncmp(remote_cmd, ".exit", 5) == 0) {
         quit_cmd(ua, cmd);
      }
   }

   return true;
}
Exemplo n.º 27
0
void process_players()
{
  player *scan,*su;
  char *oldstack;
  for(scan=flatlist_start;scan;scan=scan->flat_next) 
    if ((scan->fd<0) || (scan->flags&PANIC) || 
	(scan->flags&CHUCKOUT)) {
      
      oldstack=stack;
      current_player=scan;
      
      if (scan->location && scan->name[0] && !(scan->flags&RECONNECTION)) {
	sprintf(stack,"%s jumps up into the air and disappears with a loud *POP* !\n",full_name(scan));
	stack=end_string(stack);
	tell_room(scan->location,oldstack);
	stack=oldstack;
	save_player(scan);
      }
      if (!(scan->flags&RECONNECTION)) {
	  command_type=0;
	  do_inform(scan,"[%s has disconnected] %s");
	if (scan->saved && !(scan->flags&NO_SAVE_LAST_ON)) 
	    scan->saved->last_on=time(0);
      }
      
      if (sys_flags&VERBOSE) {
	if (scan->name[0])
	  sprintf(oldstack,"%s has disconnected.",scan->name);
	else
	  strcpy(oldstack,"Disconnect from login.");
	stack=end_string(oldstack);
	log("connection",oldstack);
    }
      destroy_player(scan);
      sys_flags|=ENFORCE_NO_NEW;
      for (su=flatlist_start;su;su=su->flat_next)
	  if (su->residency&OFF_DUTY) {
	      sys_flags&=~ENFORCE_NO_NEW;
	      break;
	  }
      current_player=0;
      stack=oldstack;
  }
    else 
	if (scan->flags&INPUT_READY) {
	    if (!(scan->lagged) && !(scan->flags&PERM_LAG)) {
		current_player=scan;
		current_room=scan->location;
		input_for_one(scan);
		action="processing players";
		current_player=0;
		current_room=0;
		
#ifdef PC
		if (scan->flags&PROMPT && scan==input_player) 
#else
		    if (scan->flags&PROMPT) 
#endif
			{
			    if (scan->saved_flags&CONVERSE) 
				do_prompt(scan,scan->converse_prompt);
			    else
				do_prompt(scan,scan->prompt);
			}
	    }
	memset(scan->ibuffer,0,IBUFFER_LENGTH);
	scan->flags &= ~INPUT_READY;
      }
}
Exemplo n.º 28
0
/*
 * Prune records from database
 *
 * prune files client=xxx [pool=yyy]
 * prune jobs client=xxx [pool=yyy]
 * prune volume=xxx
 * prune stats
 * prune directory=xxx [client=xxx] [recursive]
 */
int prune_cmd(UAContext *ua, const char *cmd)
{
   CLIENTRES *client;
   POOLRES *pool;
   POOL_DBR pr;
   MEDIA_DBR mr;
   utime_t retention;
   int kw;
   static const char *keywords[] = {
      NT_("Files"),
      NT_("Jobs"),
      NT_("Volume"),
      NT_("Stats"),
      NT_("Directory"),
      NULL
   };

   if (!open_client_db(ua, true)) {
      return false;
   }

   /*
    * First search args
    */
   kw = find_arg_keyword(ua, keywords);
   if (kw < 0 || kw > 4) {
      /*
       * No args, so ask user
       */
      kw = do_keyword_prompt(ua, _("Choose item to prune"), keywords);
   }

   switch (kw) {
   case 0: /* prune files */
      if (!(client = get_client_resource(ua))) {
         return false;
      }

      if (find_arg_with_value(ua, NT_("pool")) >= 0) {
         pool = get_pool_resource(ua);
      } else {
         pool = NULL;
      }

      /*
       * Pool File Retention takes precedence over client File Retention
       */
      if (pool && pool->FileRetention > 0) {
         if (!confirm_retention(ua, &pool->FileRetention, "File")) {
            return false;
         }
      } else if (!confirm_retention(ua, &client->FileRetention, "File")) {
         return false;
      }

      prune_files(ua, client, pool);

      return true;
   case 1: { /* prune jobs */
      int i;
      char jobtype[MAX_NAME_LENGTH];

      if (!(client = get_client_resource(ua))) {
         return false;
      }

      if (find_arg_with_value(ua, NT_("pool")) >= 0) {
         pool = get_pool_resource(ua);
      } else {
         pool = NULL;
      }

      /*
       * Ask what jobtype to prune.
       */
      if ((i = find_arg_with_value(ua, NT_("jobtype"))) >= 0) {
         bstrncpy(jobtype, ua->argv[i], sizeof(jobtype));
      } else {
         start_prompt(ua, _("Jobtype to prune:\n"));
         for (i = 0; jobtypes[i].type_name; i++) {
            add_prompt(ua, jobtypes[i].type_name);
         }

         if (do_prompt(ua, _("JobType"),  _("Select Job Type"), jobtype, sizeof(jobtype)) < 0) {
            return true;
         }
      }

      for (i = 0; jobtypes[i].type_name; i++) {
         if (bstrcasecmp(jobtypes[i].type_name, jobtype)) {
            break;
         }
      }

      if (!jobtypes[i].type_name) {
         ua->warning_msg(_("Illegal jobtype %s.\n"), jobtype);
         return false;
      }

      /*
       * Pool Job Retention takes precedence over client Job Retention
       */
      if (pool && pool->JobRetention > 0) {
         if (!confirm_retention(ua, &pool->JobRetention, "Job")) {
            return false;
         }
      } else if (!confirm_retention(ua, &client->JobRetention, "Job")) {
         return false;
      }

      if (jobtypes[i].type_name) {
         return prune_jobs(ua, client, pool, jobtypes[i].job_type);
      }

      return false;
   }
   case 2: /* prune volume */
      if (!select_pool_and_media_dbr(ua, &pr, &mr)) {
         return false;
      }

      if (mr.Enabled == 2) {
         ua->error_msg(_("Cannot prune Volume \"%s\" because it is archived.\n"),
                       mr.VolumeName);
         return false;
      }

      if (!confirm_retention(ua, &mr.VolRetention, "Volume")) {
         return false;
      }

      return prune_volume(ua, &mr);
   case 3: /* prune stats */
      if (!me->stats_retention) {
         return false;
      }

      retention = me->stats_retention;

      if (!confirm_retention(ua, &retention, "Statistics")) {
         return false;
      }

      return prune_stats(ua, retention);
   case 4: /* prune directory */
      if (find_arg_with_value(ua, NT_("client")) >= 0) {
         if (!(client = get_client_resource(ua))) {
            return false;
         }
      } else {
         client = NULL;
      }

      return prune_directory(ua, client);
   default:
      break;
   }

   return true;
}