Esempio n. 1
0
// Show the events details
void event_details(int z_index) {
	erase();
	titlebar();
	refresh();
	resize_term(25, 80);

	attron(COLOR_PAIR(3));
	mvprintw(2, 1, "View Details");
	mvprintw(3, 1, "------------");

	mvprintw(5, 1, "Event Name\t: %s", myVector[z_index].name);
	mvprintw(7, 1, "Date\t\t: %i %s %i", myVector[z_index].day, mon_name(myVector[z_index].nmon), myVector[z_index].year);
	mvprintw(9, 1, "Time\t\t: ");
	formatted_time(9, 18, myVector[z_index].hour, myVector[z_index].min);
	mvprintw(11, 1, "Location\t: %s", myVector[z_index].loc);
	//mvprintw(13, 1, "Description\t: ");
	attron(COLOR_PAIR(6));
	mvprintw(17, 1, "Press ESC to go back...");
	refresh();

	/*WINDOW *wdesc;
	wdesc = newwin(3, 60, 13, 18);
	wattron(wdesc, COLOR_PAIR(3));
	mvwprintw(wdesc, 0, 0, "%s", myVector[z_index].desc);
	wrefresh(wdesc);*/

	int key;
	do {
		key = getch();
	} while (key != 27);
	list_events();
}
Esempio n. 2
0
File: wew.c Progetto: laserswald/opt
int
main (int argc, char **argv)
{

	char *argv0;

	ARGBEGIN {
		case 'l':
			list_events();
			exit(0);
		case 'm':
			  mask = strtoul(EARGF(usage(argv0)), NULL, 10);
			  break;
		default: usage(argv0);
	} ARGEND;

	init_xcb(&conn);
	get_screen(conn, &scr);

	handle_events();

	kill_xcb(&conn);

	return 0;
}
Esempio n. 3
0
/* 
 * Read and process calendar commands
 * Return:  -1 for quit command
 *          0 otherwise
 */
int process_args(int cmd_argc, char **cmd_argv, Calendar **calendar_list_ptr, User **user_list_ptr) {

    Calendar *calendar_list = *calendar_list_ptr; 
    User *user_list = *user_list_ptr;

    if (cmd_argc <= 0) {
        return 0;
    } else if (strcmp(cmd_argv[0], "quit") == 0 && cmd_argc == 1) {
        return -1;
        
    } else if (strcmp(cmd_argv[0], "add_calendar") == 0 && cmd_argc == 2) {
        if (add_calendar(calendar_list_ptr, cmd_argv[1]) == -1) {
            error("Calendar by this name already exists");
        }
        
    } else if (strcmp(cmd_argv[0], "list_calendars") == 0 && cmd_argc == 1) {
        printf("%s", list_calendars(calendar_list));
        
    } else if (strcmp(cmd_argv[0], "add_event") == 0 && cmd_argc >= 4) {
        // Parameters for convert_time are the values in the array
        // cmd_argv but starting at cmd_argv[3]. The first 3 are not
        // part of the time.
        // So subtract these 3 from the count and pass the pointer 
        // to element 3 (where the first is element 0).
        time_t time = convert_time(cmd_argc-3, &cmd_argv[3]);

        if (add_event(calendar_list, cmd_argv[1], cmd_argv[2], time) == -1) {
           error("Calendar by this name does not exist");
        }

    } else if (strcmp(cmd_argv[0], "list_events") == 0 && cmd_argc == 2) {
        printf("%s", list_events(calendar_list, cmd_argv[1]));

    } else if (strcmp(cmd_argv[0], "add_user") == 0 && cmd_argc == 2) {
        if (add_user(user_list_ptr, cmd_argv[1]) == -1) {
                error("User by this name already exists");
        }

    } else if (strcmp(cmd_argv[0], "list_users") == 0 && cmd_argc == 1) {
        printf("%s", list_users(user_list));
        
    } else if (strcmp(cmd_argv[0], "subscribe") == 0 && cmd_argc == 3) {
        int return_code = subscribe(user_list, calendar_list, cmd_argv[1], cmd_argv[2]);
        if (return_code == -1) {
           error("User by this name does not exist");
        } else if (return_code == -2) {
           error("Calendar by this name does not exist");
        } else if (return_code == -3) {
           error("This user is already subscribed to this calendar");
        }
      
    } else {
        error("Incorrect syntax");
    }
    return 0;
}
Esempio n. 4
0
/*
 * Machine interface
 * Print a list of channel
 *
 */
static int mi_list_channels(struct lttng_channel *channels, int count,
		const char *channel_name)
{
	int i, ret;
	unsigned int chan_found = 0;

	/* Open channels element */
	ret = mi_lttng_channels_open(writer);
	if (ret) {
		goto error;
	}

	for (i = 0; i < count; i++) {
		if (channel_name != NULL) {
			if (strncmp(channels[i].name, channel_name, NAME_MAX) == 0) {
				chan_found = 1;
			} else {
				continue;
			}
		}

		/* Write channel element  and leave it open */
		ret = mi_lttng_channel(writer, &channels[i], 1);
		if (ret) {
			goto error;
		}

		/* Listing events per channel */
		ret = list_events(channels[i].name);
		if (ret) {
			goto error;
		}

		/* Closing the channel element we opened earlier */
		ret = mi_lttng_writer_close_element(writer);
		if (ret) {
			goto error;
		}

		if (chan_found) {
			break;
		}
	}

	/* Close channels element */
	ret = mi_lttng_writer_close_element(writer);
	if (ret) {
		goto error;
	}

error:
	return ret;
}
Esempio n. 5
0
int main(int argc, char *argv) {
	void	*options, *events;
	bool	fullscr = false;
	int	tmp;

	/* parse command line here */
	options = pcline(argc, argv);
	if (options == NULL) {	/* oopthspthspthsie! */
		prinf("\nUnable to allocate memory!\n");
		return 1;
	}

	if (((bool) *options) == true) {	/* we're editing */
		fullscr = init_ncurses();
		/* TODO: Implement non-fullscreen functionality */

		while ((tmp = event_editor(events, fullscr)) != 5) {
		  switch (event_editor(events, fullscr)) {
		    case 1: /* list events */
			list_events(*events);
			break;
		    case 2: /* delete event(s) */
			delete_events(*events);
			break;
		    case 3: /* add event(s) */
			add_events(*events);
			break;
		    case 4: /* edit event */
			ed_event(*events);
			break;
		    case 5: /* exit */
			return 0;
			break;
		    default:
			err("\n\nWTF?\nFell through main loop: %s\n");
		  }
		}
	
	} else if (((bool) *(options + 1)) == true) { /* fork & notify */
		if (notifyd != 0) return 2;
	}

}
Esempio n. 6
0
File: latim.c Progetto: tolmalev/SPM
int main (int argc, char *argv[]) {

	struct params par = PAR_DEFAULT;

	int j, js, fd;
	int n_read;
	int spurious_count=0;
	struct timespec very_first, very_last;
	struct event *time_buf, *time_list, *event;
        struct event *big_time_buf=NULL, origin;
	int side, size;
	int *i_differ, *e_delay=NULL, *i_delay;
	int delta_e;
	int status;
	int count=0, first;
	float sigma, quantum;
	FILE * logfile=NULL, * listfile=NULL;
	FILE * plot=NULL;
	char buff[BUFLEN];
	double *tevi=NULL, delta;
	double cf[2];
	double average;
	int total_time;
	int block_size, full_size;
	int bin_size;

	parse_options (argc, argv, &par);

	if (par.p & MRC_PM) {
		bin_size = (par.n + BINS - 1) / BINS;
		if (par.v) printf ("Bin size is: %d\n", bin_size);
	}
	if (!par.e && par.p & LAT_PM) {
		printf ("The latency distribution will not be computed if"
			" the external clock is not specified [-e]\n");
		par.p &= ~LAT_PM;
	}

	quantum = par.g * par.c;     /* usec/channel in time distributions */

	/* start auxiliary services: gnuplot */

	if (par.p) {
		plot = popen("/usr/bin/gnuplot -noraise -persist -geometry "
			     "1024x512", "w");
		if (plot == NULL) {
			printf ("Start of graphical display failed!\n");
			exit (-1);
		} else {
			if (par.v) printf (
				"Time distributions will be plotted\n");
			fprintf (plot, "set grid; set term X11\n");
		}
	}

	/* open time device and log files */

	if (par.i == NULL) par.i = "/dev/latim";
	if (strcmp(par.i, "-") == 0) {         /* data from standard input */
		fd = 0;
	} else {
		fd = open (par.i, O_RDONLY);
		if (fd == -1) {
			printf ("Failed while opening time device '%s'\n",
				par.i);
			perror ("");
			exit (-1);
		}
	}

	if (!par.f) par.f = new_code();
	logfile = fopen(par.f, "w");
	if (!logfile) {
		perror ("Failed while opening log file");
		exit (-1);
	}
	printf ("Log to file %s\n", par.f);

	if (par.L) {
		strcpy (par.f+strlen(par.f)-3, "lst");
		listfile = fopen (par.f, "w");
		if (!listfile) {
			perror ("Failed while opening list file");
			exit (-1);
		}
		printf ("Time list to file %s\n", par.f);
	}

	/* save the full command line to log file */

	fprintf (logfile, "# ");
	for ( j=0 ; j<argc ; j++) {
		fprintf (logfile, "%s ", *(argv+j));
		if (par.v) printf ("%s ", *(argv+j));
	}
	fprintf (logfile, "\n\n");
	if (par.v) printf ("\n");
	    
	/* get memory for buffers */

	block_size = par.n * SLOT;
	full_size = (par.U ? par.N : 1) * block_size;

	big_time_buf = malloc (full_size+SLOT);
	time_buf = big_time_buf;
	if (!time_buf) {
		perror ("malloc failed with time_buf");
		exit (-1);
	}

	if (par.v) printf ("Allocated time buffer %d bytes wide at %p\n",
			   (int) (full_size+SLOT), big_time_buf);

	time_list = time_buf + 1;

	tevi = malloc (par.n * sizeof(double));
	if (!tevi) {
		perror ("malloc failed with tevi");
		goto bad_exit;
	}
	if (par.v) printf ("Allocated count buffer %d bytes wide at %p\n",
			   (int) (par.n * sizeof(*tevi)), tevi);

	side = par.m/par.c + 1.0;
	size = 2*side + 1;

	e_delay = calloc (3*size, sizeof(int));
	if (!e_delay) {
		perror ("malloc failed with e_delay");
		goto bad_exit;
	}
	if (par.v) printf ("Allocated distribution buffer %d bytes wide "
			   "at %p\n", (int) (3*size*sizeof(int)), e_delay);
	i_differ = e_delay + size;
	i_delay = i_differ + size;

	/*
	 *   enter the main loop
	 */

	n_read = read (fd, (void *) time_buf, SLOT);
	if (n_read != SLOT) {
		printf ("reading of time origin failed with %d\n", n_read);
		goto bad_exit;
	}

	origin = *time_buf;
	count = 0;
	while (!par.N || count < par.N) {

		n_read = 0;
		while (n_read < block_size) {
			status = read (fd, (void *) time_list +
				       n_read, block_size - n_read);
			if (status == 0) break;
			if (status < 0) {
				perror ("read operation failed");
				goto bad_exit;
			}
			n_read += status;
		}
		if (status == 0) {
			printf ("Undue EOF after %d bytes\n", n_read);
			goto bad_exit;
		}

		if (n_read != block_size) {
			printf("read operation failed with return %d\n",
			       n_read);
			perror ("reason");
			goto bad_exit;
		}
    
		first = count * par.n;

		/*
		 *    issue a complete list of all events:
                 *    -l  list to console
                 *    -L  list to file
		 */

                list_events (&par, listfile, time_list, first, &origin);

		/*     Analyze buffer for spurious events.
		 *     An event is spurious when the measured latency exceeds
		 *     the given threshold (-m).
		 */

                if (check_events (&par, time_list, logfile, count,
                                  &spurious_count, first, &origin) == -1)
                  goto bad_exit;
                
		printf ("events/err.: %9d / %d", first+par.n, spurious_count);

		/*
		 *    histograms:
		 *
		 *    i_differ: distribution of internal clock differences
		 *    e_delay:  distribution of external counter delays
		 *    i_delay:  distribution of internal clock delays
		 *
		 */

		/* build i_differ and e_delay time distributions */

		for ( j=0 ; j<par.n ; j++ ) {
			event = time_list+j;
			delta = (us_diff(&event->timic, &(event-1)->timic) -
                                 par.t) / quantum;
			if (delta < -side) delta = -side;
			else if (delta > side) delta = side;
			i_differ[(int) (delta + side)] += 1;
//			tevi[j] = us_diff(&event->timic, &origin.timic);
			tevi[j] = us_diff(&event->timic, &time_list->timic);
			if (par.e) {
				delta_e = diff_e(event) / par.g;
				if (delta_e > size) delta_e = size;
				e_delay[delta_e] += 1;
			}
		}

		/* compute clock rate and build 'i_delay' histogram */

		fit1 (tevi, par.n, cf);
		printf ("      clock rate: %9.3f  %8.3f\n", cf[0], cf[1]+200);

		for ( j=0 ; j<par.n ; j++ ) {
			tevi[j] -= (cf[0]*(j+1) + cf[1]);
			if (tevi[j] < -par.m) tevi[j] = -par.m;
			if (tevi[j] >= par.m) tevi[j] = par.m;
			delta = tevi[j] / (par.g * par.c);
			i_delay[(int) (delta+side)] += 1;
		}

		/* plots */

                plot_histograms
                  (&par, plot, i_differ, i_delay, e_delay, tevi, time_list);

                /*
                 * close the main loop
                 */

		if (!count) very_first = time_buf->timic;
		very_last = (time_buf + par.n)->timic;
		if (par.U) {
			time_buf += par.n;
			time_list = time_buf + 1;
		} else {
			*time_buf = *(time_buf + par.n);
		}
		count++;
	}

	/* print final logs */

	if ((par.L || par.l) && par.U) {
		for ( j=0 ; j<par.n*par.N ; j++ ) {
			event = big_time_buf+j+1;
			delta = us_diff (&event->timic, &(event-1)->timic);
			sprintf (buff, "%8d  %12ld.%09ld  %10d  %8.2f %6.2f",
                                 j, event->timic.tv_sec, event->timic.tv_nsec,
				 tm_diff(&event->timic, &origin.timic),
				 delta, delta - par.t);
			if (par.e) {
				delta_e = diff_e(event);
				sprintf (buff+strlen(buff), "    %4d  %4d",
					 event->timec, delta_e);
			}
			sprintf (buff+strlen(buff), "\n");
			if (par.l) printf (buff);
			if (par.L) fprintf (listfile, buff);
		}
	}

	/* print final time distributions */

	if (par.S) {                                        /* i_differ */
		printf ("\nTime distribution from internal clock\n");
		print_distrib (i_differ, size, logfile, side, quantum);

		if (par.e) {                                 /* e_delay */
			printf ("\nTime distribution from external clock\n");
			fprintf (logfile, "\n\n");
			print_distrib (e_delay, size, logfile, 0, quantum);
		}

		printf ("\nTime distribution of delays from internal clock\n");
		fprintf (logfile, "\n\n");                       /* delay */
		print_distrib (i_delay, size, logfile, side, quantum);
	}

	/* time distribution average and width */

	if (par.s || par.S) {

		sigma = 0.;
		average = 0.;

		for ( js=-side ; js<=side ; js++ )
                  average += i_differ[js+side] * js;

		average /= (par.n * par.N)/quantum;

		for ( js=-side ; js<=side ; js++ )
                  sigma += i_differ[js+side] * (js-average) * (js-average);

		sprintf (buff, "par.t: %d   <T>: %f   Sigma: %f\n", par.t,
			 average, quantum*sqrt(sigma/(par.n * par.N - 1)));

		printf ("\n%s", buff);
		fprintf (logfile, "\n# %s", buff); 
	}

	total_time = tm_diff(&very_last, &very_first);
	sprintf (buff, "Total time: %d   skew: %d\n",
		 total_time, total_time -
		 par.n * par.N * par.t);
	printf (buff);
	fprintf (logfile, "# %s", buff);

	if (listfile) fclose (listfile);
	if (logfile) fclose (logfile);

	if (par.v) printf ("Cleaning buffers at %p %p %p\n",
			   big_time_buf, tevi, e_delay);
	free (big_time_buf);
	free (tevi);
	free (e_delay);

	return 0;

 bad_exit:
	if (logfile) fclose (logfile);
	if (listfile) fclose (listfile);
	free (big_time_buf);
	free (tevi);
	free (e_delay);
	return -1;
}
Esempio n. 7
0
//
// ARGUMENT PARSING AND PROGRAM SETUP
//
sysdig_init_res sysdig_init(int argc, char **argv)
{
	sysdig_init_res res;
	sinsp* inspector = NULL;
	vector<string> infiles;
	string outfile;
	int op;
	uint64_t cnt = -1;
	bool quiet = false;
	bool is_filter_display = false;
	bool verbose = false;
	bool list_flds = false;
	bool list_flds_markdown = false;
	bool print_progress = false;
	bool compress = false;
	sinsp_evt::param_fmt event_buffer_format = sinsp_evt::PF_NORMAL;
	sinsp_filter* display_filter = NULL;
	double duration = 1;
	int duration_to_tot = 0;
	captureinfo cinfo;
	string output_format;
	uint32_t snaplen = 0;
	int long_index = 0;
	int32_t n_filterargs = 0;
	int cflag = 0;
	bool jflag = false;
	bool unbuf_flag = false;
	bool filter_proclist_flag = false;
	string cname;
	vector<summary_table_entry>* summary_table = NULL;
	string* k8s_api = 0;
	string* k8s_api_cert = 0;
	string* mesos_api = 0;

	// These variables are for the cycle_writer engine
	int duration_seconds = 0;
	int rollover_mb = 0;
	int file_limit = 0;
	unsigned long event_limit = 0L;

	static struct option long_options[] =
	{
		{"print-ascii", no_argument, 0, 'A' },
		{"print-base64", no_argument, 0, 'b' },
#ifdef HAS_CHISELS
		{"chisel", required_argument, 0, 'c' },
		{"list-chisels", no_argument, &cflag, 1 },
#endif
		{"displayflt", no_argument, 0, 'd' },
		{"debug", no_argument, 0, 'D'},
		{"exclude-users", no_argument, 0, 'E' },
		{"event-limit", required_argument, 0, 'e'},
		{"fatfile", no_argument, 0, 'F'},
		{"filter-proclist", no_argument, 0, 0 },
		{"seconds", required_argument, 0, 'G' },
		{"help", no_argument, 0, 'h' },
#ifdef HAS_CHISELS
		{"chisel-info", required_argument, 0, 'i' },
#endif
		{"file-size", required_argument, 0, 'C' },
		{"json", no_argument, 0, 'j' },
		{"k8s-api", required_argument, 0, 'k'},
		{"k8s-api-cert", required_argument, 0, 'K' },
		{"list", no_argument, 0, 'l' },
		{"list-events", no_argument, 0, 'L' },
		{"list-markdown", no_argument, 0, 0 },
		{"mesos-api", required_argument, 0, 'm'},
		{"numevents", required_argument, 0, 'n' },
		{"progress", required_argument, 0, 'P' },
		{"print", required_argument, 0, 'p' },
		{"quiet", no_argument, 0, 'q' },
		{"readfile", required_argument, 0, 'r' },
		{"snaplen", required_argument, 0, 's' },
		{"summary", no_argument, 0, 'S' },
		{"timetype", required_argument, 0, 't' },
		{"unbuffered", no_argument, 0, 0 },
		{"verbose", no_argument, 0, 'v' },
		{"version", no_argument, 0, 0 },
		{"writefile", required_argument, 0, 'w' },
		{"limit", required_argument, 0, 'W' },
		{"print-hex", no_argument, 0, 'x'},
		{"print-hex-ascii", no_argument, 0, 'X'},
		{"compress", no_argument, 0, 'z' },
		{0, 0, 0, 0}
	};

	output_format = "*%evt.num %evt.outputtime %evt.cpu %proc.name (%thread.tid) %evt.dir %evt.type %evt.info";

	try
	{
		inspector = new sinsp();


#ifdef HAS_CHISELS
		add_chisel_dirs(inspector);
#endif

		//
		// Parse the args
		//
		while((op = getopt_long(argc, argv,
                                        "Abc:"
                                        "C:"
                                        "dDEe:F"
                                        "G:"
                                        "hi:jk:K:lLm:M:Nn:Pp:qr:Ss:t:v"
                                        "W:"
                                        "w:xXz", long_options, &long_index)) != -1)
		{
			switch(op)
			{
			case 'A':
				if(event_buffer_format != sinsp_evt::PF_NORMAL)
				{
					fprintf(stderr, "you cannot specify more than one output format\n");
					delete inspector;
					return sysdig_init_res(EXIT_SUCCESS);
				}

				event_buffer_format = sinsp_evt::PF_EOLS;
				break;
			case 'b':
				if(event_buffer_format != sinsp_evt::PF_NORMAL)
				{
					fprintf(stderr, "you cannot specify more than one output format\n");
					delete inspector;
					return sysdig_init_res(EXIT_SUCCESS);
				}

				event_buffer_format = sinsp_evt::PF_BASE64;
				break;
			case 0:
				if(cflag != 1 && cflag != 2)
				{
					break;
				}

				if(cflag == 2)
				{
					cname = optarg;
				}
#ifdef HAS_CHISELS
			case 'c':
				{
					if(cflag == 0)
					{
						string ostr(optarg);

						if(ostr.size() >= 1)
						{
							if(ostr == "l")
							{
								cflag = 1;
							}
						}
					}

					if(cflag == 1)
					{
						vector<chisel_desc> chlist;
						sinsp_chisel::get_chisel_list(&chlist);
						list_chisels(&chlist, true);
						delete inspector;
						return sysdig_init_res(EXIT_SUCCESS);
					}

					sinsp_chisel* ch = new sinsp_chisel(inspector, optarg);
					parse_chisel_args(ch, inspector, optind, argc, argv, &n_filterargs);
					g_chisels.push_back(ch);
				}
#endif
				break;

			// File-size
			case 'C':
				rollover_mb = atoi(optarg);
				if(rollover_mb <= 0)
				{
					throw sinsp_exception(string("invalid file size") + optarg);
					res.m_res = EXIT_FAILURE;
					goto exit;
				}
				break;

			case 'D':
				inspector->set_debug_mode(true);
				inspector->set_log_stderr();
				break;
			case 'E':
				inspector->set_import_users(false);
				break;
			case 'e':
				event_limit = strtoul(optarg, NULL, 0);
				if(event_limit <= 0)
				{
					throw sinsp_exception(string("invalid parameter 'number of events' ") + optarg);
					res.m_res = EXIT_FAILURE;
					goto exit;
				}
				break;
			case 'F':
				inspector->set_fatfile_dump_mode(true);
				break;
			// Number of seconds between roll-over
			case 'G':
				duration_seconds = atoi(optarg);
				if(duration_seconds <= 0)
				{
					throw sinsp_exception(string("invalid duration") + optarg);
					res.m_res = EXIT_FAILURE;
					goto exit;
				}
				break;

#ifdef HAS_CHISELS
			// --chisel-info and -i
			case 'i':
				{
					cname = optarg;
					vector<chisel_desc> chlist;

					sinsp_chisel::get_chisel_list(&chlist);

					for(uint32_t j = 0; j < chlist.size(); j++)
					{
						if(chlist[j].m_name == cname)
						{
							print_chisel_info(&chlist[j]);
							delete inspector;
							return sysdig_init_res(EXIT_SUCCESS);
						}
					}

					throw sinsp_exception("chisel " + cname + " not found - use -cl to list them.");
				}
				break;
#endif

			case 'd':
				is_filter_display = true;
				break;
			case 'j':
				//
				// set the json flag to 1 for now, the data format will depend from the print format parameters
				//
				jflag = true;
				break;
			case 'k':
				k8s_api = new string(optarg);
				break;
			case 'K':
				k8s_api_cert = new string(optarg);
				break;
			case 'h':
				usage();
				delete inspector;
				return sysdig_init_res(EXIT_SUCCESS);
			case 'l':
				list_flds = true;
				break;
			case 'L':
				list_events(inspector);
				delete inspector;
				return sysdig_init_res(EXIT_SUCCESS);
			case 'm':
				mesos_api = new string(optarg);
				break;
			case 'M':
				duration_to_tot = atoi(optarg);
				if(duration_to_tot <= 0)
				{
					throw sinsp_exception(string("invalid duration") + optarg);
					res.m_res = EXIT_FAILURE;
					goto exit;
				}
				break;
			case 'N':
				inspector->set_hostname_and_port_resolution_mode(false);
				break;
			case 'n':
				try
				{
					cnt = sinsp_numparser::parseu64(optarg);
				}
				catch(...)
				{
					throw sinsp_exception("can't parse the -n argument, make sure it's a number");
				}

				if(cnt <= 0)
				{
					throw sinsp_exception(string("invalid event count ") + optarg);
					res.m_res = EXIT_FAILURE;
					goto exit;
				}
				break;
			case 'P':
				print_progress = true;
				break;
			case 'p':
				if(string(optarg) == "p")
				{
					// -pp shows the default output format, useful if the user wants to tweak it.
					printf("%s\n", output_format.c_str());
					delete inspector;
					return sysdig_init_res(EXIT_SUCCESS);
				}
				else if(string(optarg) == "c" || string(optarg) == "container")
				{
					output_format = "*%evt.num %evt.outputtime %evt.cpu %container.name (%container.id) %proc.name (%thread.tid:%thread.vtid) %evt.dir %evt.type %evt.info";

					// This enables chisels to determine if they should print container information
					if(inspector != NULL)
					{
						inspector->set_print_container_data(true);
					}
				}
				else if(string(optarg) == "k" || string(optarg) == "kubernetes")
				{
					output_format = "*%evt.num %evt.outputtime %evt.cpu %k8s.pod.name (%container.id) %proc.name (%thread.tid:%thread.vtid) %evt.dir %evt.type %evt.info";

					// This enables chisels to determine if they should print container information
					if(inspector != NULL)
					{
						inspector->set_print_container_data(true);
					}
				}
				else if(string(optarg) == "m" || string(optarg) == "mesos")
				{
					output_format = "*%evt.num %evt.outputtime %evt.cpu %mesos.task.name (%container.id) %proc.name (%thread.tid:%thread.vtid) %evt.dir %evt.type %evt.info";

					// This enables chisels to determine if they should print container information
					if(inspector != NULL)
					{
						inspector->set_print_container_data(true);
					}
				}
				else
				{
					output_format = optarg;
				}

				break;
			case 'q':
				quiet = true;
				break;
			case 'r':
				infiles.push_back(optarg);
				k8s_api = new string();
				mesos_api = new string();
				break;
			case 'S':
				summary_table = new vector<summary_table_entry>;

				for(uint32_t j = 0; j < PPM_EVENT_MAX; j++)
				{
					summary_table->push_back(summary_table_entry(j, false));
				}

				for(uint32_t j = 0; j < PPM_SC_MAX * 2; j++)
				{
					summary_table->push_back(summary_table_entry(j, true));
				}

				break;
			case 's':
				snaplen = atoi(optarg);
				break;
			case 't':
				{
					string tms(optarg);

					if(tms == "h" || tms == "a" || tms == "r" || tms == "d" || tms == "D")
					{
						inspector->set_time_output_mode(tms.c_str()[0]);
					}
					else
					{
						fprintf(stderr, "invalid modifier for flag -t\n");
						delete inspector;
						return sysdig_init_res(EXIT_FAILURE);
					}
				}
				break;
			case 'v':
				verbose = true;
				break;
			case 'w':
				outfile = optarg;
				quiet = true;
				break;

			// Number of capture files to cycle through
			case 'W':
				file_limit = atoi(optarg);
				if(file_limit <= 0)
				{
					throw sinsp_exception(string("invalid file limit") + optarg);
					res.m_res = EXIT_FAILURE;
					goto exit;
				}
				break;

			case 'x':
				if(event_buffer_format != sinsp_evt::PF_NORMAL)
				{
					fprintf(stderr, "you cannot specify more than one output format\n");
					delete inspector;
					return sysdig_init_res(EXIT_FAILURE);
				}

				event_buffer_format = sinsp_evt::PF_HEX;
				break;
			case 'X':
				if(event_buffer_format != sinsp_evt::PF_NORMAL)
				{
					fprintf(stderr, "you cannot specify more than one output format\n");
					delete inspector;
					return sysdig_init_res(EXIT_FAILURE);
				}

				event_buffer_format = sinsp_evt::PF_HEXASCII;
				break;
			case 'z':
				compress = true;
				break;
            // getopt_long : '?' for an ambiguous match or an extraneous parameter 
			case '?':
				delete inspector;
				return sysdig_init_res(EXIT_FAILURE);
				break;
			default:
				break;
			}

			if(string(long_options[long_index].name) == "version")
			{
				printf("sysdig version %s\n", SYSDIG_VERSION);
				delete inspector;
				return sysdig_init_res(EXIT_SUCCESS);
			}

			if(string(long_options[long_index].name) == "unbuffered")
			{
				unbuf_flag = true;
			}

			if(string(long_options[long_index].name) == "filter-proclist")
			{
				filter_proclist_flag = true;
			}

			if(string(long_options[long_index].name) == "list-markdown")
			{
				list_flds = true;
				list_flds_markdown = true;
			}
		}

		//
		// If -j was specified the event_buffer_format must be rewritten to account for it
		//
		if(jflag)
		{
			switch (event_buffer_format)
			{
				case sinsp_evt::PF_NORMAL:
					event_buffer_format = sinsp_evt::PF_JSON;
					break;
				case sinsp_evt::PF_EOLS:
					event_buffer_format = sinsp_evt::PF_JSONEOLS;
					break;
				case sinsp_evt::PF_HEX:
					event_buffer_format = sinsp_evt::PF_JSONHEX;
					break;
				case sinsp_evt::PF_HEXASCII:
					event_buffer_format = sinsp_evt::PF_JSONHEXASCII;
					break;
				case sinsp_evt::PF_BASE64:
					event_buffer_format = sinsp_evt::PF_JSONBASE64;
					break;
				default:
					// do nothing
					break;
			}
		}

		inspector->set_buffer_format(event_buffer_format);

		//
		// If -l was specified, print the fields and exit
		//
		if(list_flds)
		{
			if(verbose)
			{
				//
				// -ll shows the fields verbosely, i.e. with more information
				// like the type
				//
				list_fields(true, list_flds_markdown);
			}
			else
			{
				list_fields(false, list_flds_markdown);
			}

			res.m_res = EXIT_SUCCESS;
			goto exit;
		}

		string filter;

		//
		// the filter is at the end of the command line
		//
		if(optind + n_filterargs < argc)
		{
#ifdef HAS_FILTERING
			for(int32_t j = optind + n_filterargs; j < argc; j++)
			{
				filter += argv[j];
				if(j < argc - 1)
				{
					filter += " ";
				}
			}

			if(is_filter_display)
			{
				sinsp_filter_compiler compiler(inspector, filter);
				display_filter = compiler.compile();
			}
#else
			fprintf(stderr, "filtering not compiled.\n");
			res.m_res = EXIT_FAILURE;
			goto exit;
#endif
		}

		if(signal(SIGINT, signal_callback) == SIG_ERR)
		{
			fprintf(stderr, "An error occurred while setting SIGINT signal handler.\n");
			res.m_res = EXIT_FAILURE;
			goto exit;
		}

		if(signal(SIGTERM, signal_callback) == SIG_ERR)
		{
			fprintf(stderr, "An error occurred while setting SIGTERM signal handler.\n");
			res.m_res = EXIT_FAILURE;
			goto exit;
		}

		//
		// Create the event formatter
		//
		sinsp_evt_formatter formatter(inspector, output_format);

		//
		// Set output buffers len
		//
		if(!verbose && g_chisels.size() == 0)
		{
			inspector->set_max_evt_output_len(80);
		}

		//
		// Determine if we need to filter when dumping to file
		//
		if(filter_proclist_flag)
		{
			if(filter != "")
			{
				if(infiles.size() == 0)
				{
					fprintf(stderr, "--filter-proclist not supported with live captures.\n");
					res.m_res = EXIT_FAILURE;
					goto exit;
				}

				inspector->filter_proc_table_when_saving(true);
			}
			else
			{
				fprintf(stderr, "you must specify a filter if you use --filter-proclist.\n");
				res.m_res = EXIT_FAILURE;
				goto exit;
			}
		}

		for(uint32_t j = 0; j < infiles.size() || infiles.size() == 0; j++)
		{
#ifdef HAS_FILTERING
			if(filter.size() && !is_filter_display)
			{
				inspector->set_filter(filter);
			}
#endif

			//
			// Launch the capture
			//
			if(infiles.size() != 0)
			{
				initialize_chisels();

				//
				// We have a file to open
				//
				inspector->open(infiles[j]);
			}
			else
			{
				if(j > 0)
				{
					break;
				}

				initialize_chisels();

				//
				// No file to open, this is a live capture
				//
#if defined(HAS_CAPTURE)
				bool open_success = true;
				
				if(print_progress)
				{
					fprintf(stderr, "the -P flag cannot be used with live captures.\n");
					res.m_res = EXIT_FAILURE;
					goto exit;
				}

				try
				{
					inspector->open("");
				}
				catch(sinsp_exception e)
				{
					open_success = false;
				}

				//
				// Starting the live capture failed, try to load the driver with
				// modprobe.
				//
				if(!open_success)
				{
					open_success = true;

					if(system("modprobe " PROBE_NAME " > /dev/null 2> /dev/null"))
					{
						fprintf(stderr, "Unable to load the driver\n");
					}

					inspector->open("");
				}
#else
				//
				// Starting live capture
				// If this fails on Windows and OSX, don't try with any driver
				//
				inspector->open("");
#endif

				//
				// Enable gathering the CPU from the kernel module
				//
				inspector->set_get_procs_cpu_from_driver(true);
			}

			if(snaplen != 0)
			{
				inspector->set_snaplen(snaplen);
			}

			duration = ((double)clock()) / CLOCKS_PER_SEC;

			if(outfile != "")
			{
				inspector->setup_cycle_writer(outfile, rollover_mb, duration_seconds, file_limit, event_limit, compress);
				inspector->autodump_next_file();
			}

			//
			// Notify the chisels that the capture is starting
			//
			chisels_on_capture_start();

			//
			// run k8s, if required
			//
			if(k8s_api)
			{
				if(!k8s_api_cert)
				{
					if(char* k8s_cert_env = getenv("SYSDIG_K8S_API_CERT"))
					{
						k8s_api_cert = new string(k8s_cert_env);
					}
				}
				inspector->init_k8s_client(k8s_api, k8s_api_cert, verbose);
				k8s_api = 0;
				k8s_api_cert = 0;
			}
			else if(char* k8s_api_env = getenv("SYSDIG_K8S_API"))
			{
				if(k8s_api_env != NULL)
				{
					if(!k8s_api_cert)
					{
						if(char* k8s_cert_env = getenv("SYSDIG_K8S_API_CERT"))
						{
							k8s_api_cert = new string(k8s_cert_env);
						}
					}
					k8s_api = new string(k8s_api_env);
					inspector->init_k8s_client(k8s_api, k8s_api_cert, verbose);
				}
				else
				{
					delete k8s_api;
					delete k8s_api_cert;
				}
				k8s_api = 0;
				k8s_api_cert = 0;
			}

			//
			// run mesos, if required
			//
			if(mesos_api)
			{
				inspector->init_mesos_client(mesos_api, verbose);
			}
			else if(char* mesos_api_env = getenv("SYSDIG_MESOS_API"))
			{
				if(mesos_api_env != NULL)
				{
					mesos_api = new string(mesos_api_env);
					inspector->init_mesos_client(mesos_api, verbose);
				}
			}
			delete mesos_api;
			mesos_api = 0;

			cinfo = do_inspect(inspector,
				cnt,
				duration_to_tot,
				quiet,
				jflag,
				unbuf_flag,
				print_progress,
				display_filter,
				summary_table,
				&formatter);

			duration = ((double)clock()) / CLOCKS_PER_SEC - duration;

			scap_stats cstats;
			inspector->get_capture_stats(&cstats);

			if(verbose)
			{
				fprintf(stderr, "Driver Events:%" PRIu64 "\nDriver Drops:%" PRIu64 "\n",
					cstats.n_evts,
					cstats.n_drops);

				fprintf(stderr, "Elapsed time: %.3lf, Captured Events: %" PRIu64 ", %.2lf eps\n",
					duration,
					cinfo.m_nevts,
					(double)cinfo.m_nevts / duration);
			}

			//
			// Done. Close the capture.
			//
			inspector->close();
		}
	}
	catch(sinsp_capture_interrupt_exception&)
	{
		handle_end_of_file(print_progress);
	}
	catch(sinsp_exception& e)
	{
		cerr << e.what() << endl;
		handle_end_of_file(print_progress);
		res.m_res = EXIT_FAILURE;
	}
	catch(...)
	{
		handle_end_of_file(print_progress);
		res.m_res = EXIT_FAILURE;
	}

exit:
	//
	// If any of the chisels is requesting another run,
	//
	for(vector<sinsp_chisel*>::iterator it = g_chisels.begin();
		it != g_chisels.end(); ++it)
	{
		string na;
		if((*it)->get_nextrun_args(&na))
		{
			res.m_next_run_args = sinsp_split(na, ' ');
		}
	}

	//
	// If there's a summary table, sort and print it
	//
	if(summary_table != NULL)
	{
		print_summary_table(inspector, summary_table, 100);
	}

	//
	// Free all the stuff that was allocated
	//
	free_chisels();

	if(inspector)
	{
		delete inspector;
	}

	if(display_filter)
	{
		delete display_filter;
	}

	return res;
}
Esempio n. 8
0
void
process_command(int descr, dbref player, char *command)
{
	char *arg1;
	char *arg2;
	char *full_command;
	char *p;					/* utility */
	char pbuf[BUFFER_LEN];
	char xbuf[BUFFER_LEN];
	char ybuf[BUFFER_LEN];
	struct timeval starttime;
	struct timeval endtime;
	double totaltime;

	if (command == 0)
		abort();

	/* robustify player */
	if (player < 0 || player >= db_top ||
		(Typeof(player) != TYPE_PLAYER && Typeof(player) != TYPE_THING)) {
		log_status("process_command: bad player %d", player);
		return;
	}

	if ((tp_log_commands || Wizard(OWNER(player)))) {
		if (!(FLAGS(player) & (INTERACTIVE | READMODE))) {
			if (!*command) {
				return; 
			}
			log_command("%s: %s", whowhere(player), command);
		} else {
			if (tp_log_interactive) {
				log_command("%s: %s%s", whowhere(player),
						(FLAGS(player) & (READMODE)) ? "[READ] " : "[INTERP] ", command);
			}
		}
	}

	if (FLAGS(player) & INTERACTIVE) {
		interactive(descr, player, command);
		return;
	}
	/* eat leading whitespace */
	while (*command && isspace(*command))
		command++;

	/* Disable null command once past READ line */
	if (!*command)
		return;

	/* check for single-character commands */
	if (!tp_enable_prefix) {
		if (*command == SAY_TOKEN) {
			snprintf(pbuf, sizeof(pbuf), "say %s", command + 1);
			command = &pbuf[0];
		} else if (*command == POSE_TOKEN) {
			snprintf(pbuf, sizeof(pbuf), "pose %s", command + 1);
			command = &pbuf[0];
		} else if (*command == EXIT_DELIMITER) {
			snprintf(pbuf, sizeof(pbuf), "delimiter %s", command + 1);
			command = &pbuf[0];
		}
	}

	/* profile how long command takes. */
	gettimeofday(&starttime, NULL);

	/* if player is a wizard, and uses overide token to start line... */
	/* ... then do NOT run actions, but run the command they specify. */
	if (!(TrueWizard(OWNER(player)) && (*command == OVERIDE_TOKEN))) {
		if (can_move(descr, player, command, 0)) {
			do_move(descr, player, command, 0);	/* command is exact match for exit */
			*match_args = 0;
			*match_cmdname = 0;
		} else {
			if (tp_enable_prefix) {
				if (*command == SAY_TOKEN) {
					snprintf(pbuf, sizeof(pbuf), "say %s", command + 1);
					command = &pbuf[0];
				} else if (*command == POSE_TOKEN) {
					snprintf(pbuf, sizeof(pbuf), "pose %s", command + 1);
					command = &pbuf[0];
				} else if (*command == EXIT_DELIMITER) {
					snprintf(pbuf, sizeof(pbuf), "delimiter %s", command + 1);
					command = &pbuf[0];
				} else {
					goto bad_pre_command;
				}
				if (can_move(descr, player, command, 0)) {
					do_move(descr, player, command, 0);	/* command is exact match for exit */
					*match_args = 0;
					*match_cmdname = 0;
				} else {
					goto bad_pre_command;
				}
			} else {
				goto bad_pre_command;
			}
		}
	} else {
	  bad_pre_command:
		if (TrueWizard(OWNER(player)) && (*command == OVERIDE_TOKEN))
			command++;
		full_command = strcpyn(xbuf, sizeof(xbuf), command);
		for (; *full_command && !isspace(*full_command); full_command++) ;
		if (*full_command)
			full_command++;

		/* find arg1 -- move over command word */
		command = strcpyn(ybuf, sizeof(ybuf), command);
		for (arg1 = command; *arg1 && !isspace(*arg1); arg1++) ;
		/* truncate command */
		if (*arg1)
			*arg1++ = '\0';

		/* remember command for programs */
		strcpyn(match_args, sizeof(match_args), full_command);
		strcpyn(match_cmdname, sizeof(match_cmdname), command);

		/* move over spaces */
		while (*arg1 && isspace(*arg1))
			arg1++;

		/* find end of arg1, start of arg2 */
		for (arg2 = arg1; *arg2 && *arg2 != ARG_DELIMITER; arg2++) ;

		/* truncate arg1 */
		for (p = arg2 - 1; p >= arg1 && isspace(*p); p--)
			*p = '\0';

		/* go past delimiter if present */
		if (*arg2)
			*arg2++ = '\0';
		while (*arg2 && isspace(*arg2))
			arg2++;

		switch (command[0]) {
		case '@':
			switch (command[1]) {
			case 'a':
			case 'A':
				/* @action, @armageddon, @attach */
				switch (command[2]) {
				case 'c':
				case 'C':
					Matched("@action");
					NOGUEST("@action", player);
					BUILDERONLY("@action", player);
					do_action(descr, player, arg1, arg2);
					break;
				case 'r':
				case 'R':
					if (strcmp(command, "@armageddon"))
						goto bad;
/*
					WIZARDONLY("@armageddon", player);
					PLAYERONLY("@armageddon", player);
*/
					do_armageddon(player, full_command);
					break;
				case 't':
				case 'T':
					Matched("@attach");
					NOGUEST("@attach", player);
					BUILDERONLY("@attach", player);
					do_attach(descr, player, arg1, arg2);
					break;
				default:
					goto bad;
				}
				break;
			case 'b':
			case 'B':
				/* @bless, @boot */
				switch (command[2]) {
				case 'l':
				case 'L':
					Matched("@bless");
					WIZARDONLY("@bless", player);
					PLAYERONLY("@bless", player);
					NOFORCE("@bless", force_level, player);
					do_bless(descr, player, arg1, arg2);
					break;
				case 'o':
				case 'O':
					Matched("@boot");
					WIZARDONLY("@boot", player);
					PLAYERONLY("@boot", player);
					do_boot(player, arg1);
					break;
				default:
					goto bad;
				}
				break;
			case 'c':
			case 'C':
				/* @chlock, @chown, @chown_lock, @clone,
				   @conlock, @contents, @create, @credits */
				switch (command[2]) {
				case 'h':
				case 'H':
					switch (command[3]) {
					case 'l':
					case 'L':
						Matched("@chlock");
						NOGUEST("@chlock", player);
						set_standard_lock(descr, player, arg1, MESGPROP_CHLOCK, "Chown Lock", arg2);
						break;
					case 'o':
					case 'O':
						if(strlen(command) < 7) {
							Matched("@chown");
							do_chown(descr, player, arg1, arg2);
						} else {
							Matched("@chown_lock");
							NOGUEST("@chown_lock", player);
							set_standard_lock(descr, player, arg1, MESGPROP_CHLOCK, "Chown Lock", arg2);
						}
						break;
					default:
						goto bad;
					}
					break;
				case 'l':
				case 'L':
					Matched("@clone");
					NOGUEST("@clone", player);
					BUILDERONLY("@clone", player);
					do_clone(descr, player, arg1);
					break;
				case 'o':
				case 'O':
					switch (command[4]) {
					case 'l':
					case 'L':
						Matched("@conlock");
						NOGUEST("@conlock", player);
						set_standard_lock(descr, player, arg1, MESGPROP_CONLOCK, "Container Lock", arg2);
						break;
					case 't':
					case 'T':
						Matched("@contents");
						do_contents(descr, player, arg1, arg2);
						break;
					default:
						goto bad;
					}
					break;
				case 'r':
				case 'R':
					if (string_compare(command, "@credits")) {
						Matched("@create");
						NOGUEST("@create", player);
						BUILDERONLY("@create", player);
						do_create(player, arg1, arg2);
					} else {
						do_credits(player);
					}
					break;
				default:
					goto bad;
				}
				break;
			case 'd':
			case 'D':
				/* @dbginfo, @describe, @dig, @doing,
				   @drop, @dump */
				switch (command[2]) {
#ifdef DISKBASE
				case 'b':
				case 'B':
					Matched("@dbginfo");
					WIZARDONLY("@dbginfo", player);
					diskbase_debug(player);
					break;
#endif
				case 'e':
				case 'E':
					Matched("@describe");
					NOGUEST("@describe", player);
					set_standard_property(descr, player, arg1, MESGPROP_DESC, "Object Description", arg2);
					break;
				case 'i':
				case 'I':
					Matched("@dig");
					NOGUEST("@dig", player);
					BUILDERONLY("@dig", player);
					do_dig(descr, player, arg1, arg2);
					break;
				case 'o':
				case 'O':
					Matched("@doing");
					if (!tp_who_doing)
						goto bad;
					NOGUEST("@doing", player);
					set_standard_property(descr, player, arg1, MESGPROP_DOING, "Doing", arg2);
					break;
				case 'r':
				case 'R':
					Matched("@drop");
					NOGUEST("@drop", player);
					set_standard_property(descr, player, arg1, MESGPROP_DROP, "Drop Message", arg2);
					break;
				case 'u':
				case 'U':
					Matched("@dump");
					WIZARDONLY("@dump", player);
					PLAYERONLY("@dump", player);
					do_dump(player, full_command);
					break;
				default:
					goto bad;
				}
				break;
			case 'e':
			case 'E':
				/* @edit, @entrances, @examine */
				switch (command[2]) {
				case 'd':
				case 'D':
					Matched("@edit");
					NOGUEST("@edit", player);
					PLAYERONLY("@edit", player);
					MUCKERONLY("@edit", player);
					do_edit(descr, player, arg1);
					break;
				case 'n':
				case 'N':
					Matched("@entrances");
					do_entrances(descr, player, arg1, arg2);
					break;
				case 'x':
				case 'X':
					Matched("@examine");
					GODONLY("@examine", player);
					sane_dump_object(player, arg1);
					break;
				default:
					goto bad;
				}
				break;
			case 'f':
			case 'F':
				/* @fail, @find, @flock, @force, @force_lock */
				switch (command[2]) {
				case 'a':
				case 'A':
					Matched("@fail");
					NOGUEST("@fail", player);
					set_standard_property(descr, player, arg1, MESGPROP_FAIL, "Fail Message", arg2);
					break;
				case 'i':
				case 'I':
					Matched("@find");
					do_find(player, arg1, arg2);
					break;
				case 'l':
				case 'L':
					Matched("@flock");
					NOGUEST("@flock", player);
					NOFORCE("@flock", force_level, player);
					set_standard_lock(descr, player, arg1, MESGPROP_FLOCK, "Force Lock", arg2);
					break;
				case 'o':
				case 'O':
					if(strlen(command) < 7) {
						Matched("@force");
						do_force(descr, player, arg1, arg2);
					} else {
						Matched("@force_lock");
						NOGUEST("@force_lock", player);
						NOFORCE("@force_lock", force_level, player);
						set_standard_lock(descr, player, arg1, MESGPROP_FLOCK, "Force Lock", arg2);
					}
					break;
				default:
					goto bad;
				}
				break;
			case 'h':
			case 'H':
				/* @hashes */
				Matched("@hashes");
				do_hashes(player, arg1);
				break;
			case 'i':
			case 'I':
				/* @idescribe */
				Matched("@idescribe");
				NOGUEST("@idescribe", player);
				set_standard_property(descr, player, arg1, MESGPROP_IDESC, "Inside Description", arg2);
				break;
			case 'k':
			case 'K':
				/* @kill */
				Matched("@kill");
				do_dequeue(descr, player, arg1);
				break;
			case 'l':
			case 'L':
				/* @link, @list, @lock */
				switch (command[2]) {
				case 'i':
				case 'I':
					switch (command[3]) {
					case 'n':
					case 'N':
						Matched("@link");
						NOGUEST("@link", player);
						do_link(descr, player, arg1, arg2);
						break;
					case 's':
					case 'S':
						Matched("@list");
						match_and_list(descr, player, arg1, arg2);
						break;
					default:
						goto bad;
					}
					break;
				case 'o':
				case 'O':
					Matched("@lock");
					NOGUEST("@lock", player);
					set_standard_lock(descr, player, arg1, MESGPROP_LOCK, "Lock", arg2);
					break;
				default:
					goto bad;
				}
				break;
			case 'm':
			case 'M':
				/* @mcpedit, @mcpprogram, @memory, @mpitops,
				   @muftops */
				switch (command[2]) {
#ifdef MCP_SUPPORT
				case 'c':
				case 'C':
					if (string_prefix("@mcpedit", command)) {
						Matched("@mcpedit");
						NOGUEST("@mcpedit", player);
						PLAYERONLY("@mcpedit", player);
						MUCKERONLY("@mcpedit", player);
						do_mcpedit(descr, player, arg1);
						break;
					} else {
						Matched("@mcpprogram");
						NOGUEST("@mcpprogram", player);
						PLAYERONLY("@mcpprogram", player);
						MUCKERONLY("@mcpprogram", player);
						do_mcpprogram(descr, player, arg1);
						break;
					}
#endif
#ifndef NO_MEMORY_COMMAND
				case 'e':
				case 'E':
					Matched("@memory");
					WIZARDONLY("@memory", player);
					do_memory(player);
					break;
#endif
				case 'p':
			    case 'P':
			        Matched("@mpitops");
				WIZARDONLY("@mpitops", player);
			        do_mpi_topprofs(player, arg1);
			        break;
			    case 'u':
			    case 'U':
			        Matched("@muftops");
				WIZARDONLY("@muftops", player);
			        do_muf_topprofs(player, arg1);
			        break;
				default:
					goto bad;
				}
				break;
			case 'n':
			case 'N':
				/* @name, @newpassword */
				switch (command[2]) {
				case 'a':
				case 'A':
					Matched("@name");
					NOGUEST("@name", player);
					do_name(descr, player, arg1, arg2);
					break;
				case 'e':
				case 'E':
					if (strcmp(command, "@newpassword"))
						goto bad;
					WIZARDONLY("@newpassword", player);
					PLAYERONLY("@newpassword", player);
					do_newpassword(player, arg1, arg2);
					break;
				default:
					goto bad;
				}
				break;
			case 'o':
			case 'O':
				/* @odrop, @oecho, @ofail, @open, @osuccess,
				   @owned */
				switch (command[2]) {
				case 'd':
				case 'D':
					Matched("@odrop");
					NOGUEST("@odrop", player);
					set_standard_property(descr, player, arg1, MESGPROP_ODROP, "ODrop Message", arg2);
					break;
				case 'e':
				case 'E':
					Matched("@oecho");
					NOGUEST("@oecho", player);
					set_standard_property(descr, player, arg1, MESGPROP_OECHO, "Outside-echo Prefix", arg2);
					break;
				case 'f':
				case 'F':
					Matched("@ofail");
					NOGUEST("@ofail", player);
					set_standard_property(descr, player, arg1, MESGPROP_OFAIL, "OFail Message", arg2);
					break;
				case 'p':
				case 'P':
					Matched("@open");
					NOGUEST("@open", player);
					BUILDERONLY("@open", player);
					do_open(descr, player, arg1, arg2);
					break;
				case 's':
				case 'S':
					Matched("@osuccess");
					NOGUEST("@osuccess", player);
					set_standard_property(descr, player, arg1, MESGPROP_OSUCC, "OSuccess Message", arg2);
					break;
				case 'w':
				case 'W':
					Matched("@owned");
					do_owned(player, arg1, arg2);
					break;
				default:
					goto bad;
				}
				break;
			case 'p':
			case 'P':
				/* @password, @pcreate, @pecho, @program, 
				   @propset, @ps */
				switch (command[2]) {
				case 'a':
				case 'A':
					Matched("@password");
					PLAYERONLY("@password", player);
					NOGUEST("@password", player);
					do_password(player, arg1, arg2);
					break;
				case 'c':
				case 'C':
					Matched("@pcreate");
					WIZARDONLY("@pcreate", player);
					PLAYERONLY("@pcreate", player);
					do_pcreate(player, arg1, arg2);
					break;
				case 'e':
				case 'E':
					Matched("@pecho");
					NOGUEST("@pecho", player);
					set_standard_property(descr, player, arg1, MESGPROP_PECHO, "Puppet-echo Prefix", arg2);
					break;
				case 'r':
				case 'R':
					if (string_prefix("@program", command)) {
						Matched("@program");
						NOGUEST("@program", player);
						PLAYERONLY("@program", player);
						MUCKERONLY("@program", player);
						do_prog(descr, player, arg1);
						break;
					} else {
						Matched("@propset");
						NOGUEST("@propset", player);
						do_propset(descr, player, arg1, arg2);
						break;
					}
				case 's':
				case 'S':
					Matched("@ps");
					list_events(player);
					break;
				default:
					goto bad;
				}
				break;
			case 'r':
			case 'R':
				/* @recycle, @reconfiguressl, @relink, @restart, @restrict */
				switch (command[3]) {
				case 'c':
				case 'C':
#ifdef USE_SSL
                                        if (!strcmp(command, "@reconfiguressl")) {
                                                WIZARDONLY("@reconfiguressl", player);
                                                PLAYERONLY("@reconfiguressl", player);
                                                do_reconfigure_ssl(player);
                                                break;
                                        }
#endif
                                        Matched("@recycle");
                                        NOGUEST("@recycle", player);
                                        do_recycle(descr, player, arg1);
                                        break;
				case 'l':
				case 'L':
					Matched("@relink");
					NOGUEST("@relink", player);
					do_relink(descr, player, arg1, arg2);
					break;
				case 's':
				case 'S':
					if (!strcmp(command, "@restart")) {
/*
						WIZARDONLY("@restart", player);
						PLAYERONLY("@restart", player);
*/
						do_restart(player);
					} else if (!strcmp(command, "@restrict")) {
						WIZARDONLY("@restrict", player);
						PLAYERONLY("@restrict", player);
						do_restrict(player, arg1);
					} else {
						goto bad;
					}
					break;
				default:
					goto bad;
				}
				break;
			case 's':
			case 'S':
				/* @sanity, @sanchange, @sanfix, @set,
				   @shutdown, @stats, @success, @sweep */
				switch (command[2]) {
				case 'a':
				case 'A':
					if (!strcmp(command, "@sanity")) {
						GODONLY("@sanity", player);
						sanity(player);
					} else if (!strcmp(command, "@sanchange")) {
						GODONLY("@sanchange", player);
						sanechange(player, full_command);
					} else if (!strcmp(command, "@sanfix")) {
						GODONLY("@sanfix", player);
						sanfix(player);
					} else {
						goto bad;
					}
					break;
				case 'e':
				case 'E':
					Matched("@set");
					NOGUEST("@set", player);
					do_set(descr, player, arg1, arg2);
					break;
				case 'h':
				case 'H':
					if (strcmp(command, "@shutdown"))
						goto bad;
/*
					WIZARDONLY("@shutdown", player);
					PLAYERONLY("@shutdown", player);
*/
					do_shutdown(player);
					break;
				case 't':
				case 'T':
					Matched("@stats");
					do_stats(player, arg1);
					break;
				case 'u':
				case 'U':
					Matched("@success");
					NOGUEST("@success", player);
					set_standard_property(descr, player, arg1, MESGPROP_SUCC, "Success Message", arg2);
					break;
				case 'w':
				case 'W':
					Matched("@sweep");
					do_sweep(descr, player, arg1);
					break;
				default:
					goto bad;
				}
				break;
			case 't':
			case 'T':
				/* @teleport, @toad, @trace, @tune */
				switch (command[2]) {
				case 'e':
				case 'E':
					Matched("@teleport");
					do_teleport(descr, player, arg1, arg2);
					break;
				case 'o':
				case 'O':
					if (!strcmp(command, "@toad")) {
						WIZARDONLY("@toad", player);
						PLAYERONLY("@toad", player);
						do_toad(descr, player, arg1, arg2);
					} else if (!strcmp(command, "@tops")) {
						WIZARDONLY("@tops", player);
						do_all_topprofs(player, arg1);
					} else {
						goto bad;
					}
					break;
				case 'r':
				case 'R':
					Matched("@trace");
					do_trace(descr, player, arg1, atoi(arg2));
					break;
				case 'u':
				case 'U':
					Matched("@tune");
					WIZARDONLY("@tune", player);
					PLAYERONLY("@tune", player);
					do_tune(player, arg1, arg2, !!strchr(full_command, ARG_DELIMITER));
					break;
				default:
					goto bad;
				}
				break;
			case 'u':
			case 'U':
				/* @unbless, @unlink, @unlock, @uncompile,
				   @usage */
				switch (command[2]) {
				case 'N':
				case 'n':
					if (string_prefix(command, "@unb")) {
						Matched("@unbless");
						WIZARDONLY("@unbless", player);
						PLAYERONLY("@unbless", player);
						NOFORCE("@unbless", force_level, player);
						do_unbless(descr, player, arg1, arg2);
					} else if (string_prefix(command, "@unli")) {
						Matched("@unlink");
						NOGUEST("@unlink", player);
						do_unlink(descr, player, arg1);
					} else if (string_prefix(command, "@unlo")) {
						Matched("@unlock");
						NOGUEST("@unlock", player);
						set_standard_lock(descr, player, arg1, MESGPROP_LOCK, "Lock", "");
					} else if (string_prefix(command, "@uncom")) {
						Matched("@uncompile");
						WIZARDONLY("@uncompile", player);
						PLAYERONLY("@uncompile", player);
						do_uncompile(player);
					} else {
						goto bad;
					}
					break;
#ifndef NO_USAGE_COMMAND
				case 'S':
				case 's':
					Matched("@usage");
					WIZARDONLY("@usage", player);
					do_usage(player);
					break;
#endif
				default:
					goto bad;
					break;
				}
				break;
			case 'v':
			case 'V':
				/* @version */
				Matched("@version");
				do_version(player);
				break;
			case 'w':
			case 'W':
				/* @wall */
				if (strcmp(command, "@wall"))
					goto bad;
				WIZARDONLY("@wall", player);
				PLAYERONLY("@wall", player);
				do_wall(player, full_command);
				break;
			default:
				goto bad;
			}
			break;
		case 'd':
		case 'D':
			/* disembark, drop */
			switch (command[1]) {
			case 'i':
			case 'I':
				Matched("disembark");
				do_leave(descr, player);
				break;
			case 'r':
			case 'R':
				Matched("drop");
				do_drop(descr, player, arg1, arg2);
				break;
			default:
				goto bad;
			}
			break;
		case 'e':
		case 'E':
			/* examine */
			Matched("examine");
			do_examine(descr, player, arg1, arg2);
			break;
		case 'g':
		case 'G':
			/* get, give, goto, gripe */
			switch (command[1]) {
			case 'e':
			case 'E':
				Matched("get");
				do_get(descr, player, arg1, arg2);
				break;
			case 'i':
			case 'I':
				Matched("give");
				do_give(descr, player, arg1, atoi(arg2));
				break;
			case 'o':
			case 'O':
				Matched("goto");
				do_move(descr, player, arg1, 0);
				break;
			case 'r':
			case 'R':
				if (string_compare(command, "gripe"))
					goto bad;
				do_gripe(player, full_command);
				break;
			default:
				goto bad;
			}
			break;
		case 'h':
		case 'H':
			/* help */
			Matched("help");
			do_help(player, arg1, arg2);
			break;
		case 'i':
		case 'I':
			/* inventory, info */
			if (string_compare(command, "info")) {
				Matched("inventory");
				do_inventory(player);
			} else {
				Matched("info");
				do_info(player, arg1, arg2);
			}
			break;
		case 'k':
		case 'K':
			/* kill */
			Matched("kill");
			do_kill(descr, player, arg1, atoi(arg2));
			break;
		case 'l':
		case 'L':
			/* leave, look */
			if (string_prefix("look", command)) {
				Matched("look");
				do_look_at(descr, player, arg1, arg2);
				break;
			} else {
				Matched("leave");
				do_leave(descr, player);
				break;
			}
		case 'm':
		case 'M':
			/* man, motd, move, mpi */
			if (string_prefix(command, "move")) {
				do_move(descr, player, arg1, 0);
				break;
			} else if (!string_compare(command, "motd")) {
				do_motd(player, full_command);
				break;
			} else if (!string_compare(command, "mpi")) {
				do_mpihelp(player, arg1, arg2);
				break;
			} else {
				if (string_compare(command, "man"))
					goto bad;
				do_man(player, (!*arg1 && !*arg2 && arg1 != arg2) ? "=" : arg1, arg2);
			}
			break;
		case 'n':
		case 'N':
			/* news */
			Matched("news");
			do_news(player, arg1, arg2);
			break;
		case 'p':
		case 'P':
			/* page, pose, put */
			switch (command[1]) {
			case 'a':
			case 'A':
				Matched("page");
				do_page(player, arg1, arg2);
				break;
			case 'o':
			case 'O':
				Matched("pose");
				do_pose(player, full_command);
				break;
			case 'u':
			case 'U':
				Matched("put");
				do_drop(descr, player, arg1, arg2);
				break;
			default:
				goto bad;
			}
			break;
		case 'r':
		case 'R':
			/* read, rob */
			switch (command[1]) {
			case 'e':
			case 'E':
				Matched("read");	/* undocumented alias for look */
				do_look_at(descr, player, arg1, arg2);
				break;
			case 'o':
			case 'O':
				Matched("rob");
				do_rob(descr, player, arg1);
				break;
			default:
				goto bad;
			}
			break;
		case 's':
		case 'S':
			/* say, score */
			switch (command[1]) {
			case 'a':
			case 'A':
				Matched("say");
				do_say(player, full_command);
				break;
			case 'c':
			case 'C':
				Matched("score");
				do_score(player);
				break;
			default:
				goto bad;
			}
			break;
		case 't':
		case 'T':
			/* take, throw */
			switch (command[1]) {
			case 'a':
			case 'A':
				Matched("take");
				do_get(descr, player, arg1, arg2);
				break;
			case 'h':
			case 'H':
				Matched("throw");
				do_drop(descr, player, arg1, arg2);
				break;
			default:
			goto bad;
			}
			break;
		case 'w':
		case 'W':
			/* whisper */
			Matched("whisper");
			do_whisper(descr, player, arg1, arg2);
			break;
		default:
		  bad:
			if (tp_m3_huh != 0)
			{
				char hbuf[BUFFER_LEN];
				snprintf(hbuf,BUFFER_LEN,"HUH? %s", command);
				if(can_move(descr, player, hbuf, 3)) {
					do_move(descr, player, hbuf, 3);
					*match_args = 0;
					*match_cmdname = 0;
					break;
				}
			}	
			notify(player, tp_huh_mesg);
			if (tp_log_failed_commands && !controls(player, LOCATION(player))) {
				log_status("HUH from %s(%d) in %s(%d)[%s]: %s %s",
						   NAME(player), player, NAME(LOCATION(player)),
						   LOCATION(player),
						   NAME(OWNER(LOCATION(player))), command, full_command);
			}
			break;
		}
	}

	/* calculate time command took. */
	gettimeofday(&endtime, NULL);
	if (starttime.tv_usec > endtime.tv_usec) {
		endtime.tv_usec += 1000000;
		endtime.tv_sec -= 1;
	}
	endtime.tv_usec -= starttime.tv_usec;
	endtime.tv_sec -= starttime.tv_sec;

	totaltime = endtime.tv_sec + (endtime.tv_usec * 1.0e-6);
	if (totaltime > (tp_cmd_log_threshold_msec / 1000.0)) {
		log2file(LOG_CMD_TIMES, "%6.3fs, %.16s: %s: %s",
					totaltime, ctime((time_t *)&starttime.tv_sec),
					whowhere(player), command);
	}
}
Esempio n. 9
0
/*
 * List channel(s) of session and domain.
 *
 * If channel_name is NULL, all channels are listed.
 */
static int list_channels(const char *channel_name)
{
	int count, i, ret = CMD_SUCCESS;
	unsigned int chan_found = 0;
	struct lttng_channel *channels = NULL;

	DBG("Listing channel(s) (%s)", channel_name ? : "<all>");

	count = lttng_list_channels(handle, &channels);
	if (count < 0) {
		switch (-count) {
		case LTTNG_ERR_KERN_CHAN_NOT_FOUND:
			if (lttng_opt_mi) {
				/* When printing mi this is not an error
				 * but an empty channels element */
				count = 0;
			} else {
				ret = CMD_SUCCESS;
				WARN("No kernel channel");
				goto error_channels;
			}
			break;
		default:
			/* We had a real error */
			ret = CMD_ERROR;
			ERR("%s", lttng_strerror(count));
			goto error_channels;
			break;
		}
	}

	if (lttng_opt_mi) {
		/* Mi print */
		ret = mi_list_channels(channels, count, channel_name);
		if (ret) {
			ret = CMD_ERROR;
			goto error;
		}
	} else {
		/* Pretty print */
		if (count) {
			MSG("Channels:\n-------------");
		}

		for (i = 0; i < count; i++) {
			if (channel_name != NULL) {
				if (strncmp(channels[i].name, channel_name, NAME_MAX) == 0) {
					chan_found = 1;
				} else {
					continue;
				}
			}
			print_channel(&channels[i]);

			/* Listing events per channel */
			ret = list_events(channels[i].name);
			if (ret) {
				goto error;
			}

			if (chan_found) {
				break;
			}
		}

		if (!chan_found && channel_name != NULL) {
			ret = CMD_ERROR;
			ERR("Channel %s not found", channel_name);
			goto error;
		}
	}
error:
	free(channels);

error_channels:
	return ret;
}
Esempio n. 10
0
//
// MAIN
//
int main(int argc, char **argv)
{
	int res = EXIT_SUCCESS;
	sinsp* inspector = NULL;
	vector<string> infiles;
	string outfile;
	int op;
	uint64_t cnt = -1;
	bool quiet = false;
	bool absolute_times = false;
	bool is_filter_display = false;
	bool verbose = false;
	bool list_flds = false;
	bool print_progress = false;
	bool compress = false;
	sinsp_evt::param_fmt event_buffer_format = sinsp_evt::PF_NORMAL;
	sinsp_filter* display_filter = NULL;
	double duration = 1;
	captureinfo cinfo;
	string output_format;
	uint32_t snaplen = 0;
	int long_index = 0;
	int32_t n_filterargs = 0;
	int cflag = 0;
	string cname;
	vector<summary_table_entry>* summary_table = NULL;
	string timefmt = "%evt.time";

	static struct option long_options[] =
	{
		{"print-ascii", no_argument, 0, 'A' },
		{"abstimes", no_argument, 0, 'a' },
#ifdef HAS_CHISELS
		{"chisel", required_argument, 0, 'c' },
		{"list-chisels", no_argument, &cflag, 1 },
#endif
		{"compress", no_argument, 0, 'z' },
		{"displayflt", no_argument, 0, 'd' },
		{"debug", no_argument, 0, 'D'},
		{"help", no_argument, 0, 'h' },
#ifdef HAS_CHISELS
		{"chisel-info", required_argument, 0, 'i' },
#endif
		{"json", no_argument, 0, 'j' },
		{"list", no_argument, 0, 'l' },
		{"list-events", no_argument, 0, 'L' },
		{"numevents", required_argument, 0, 'n' },
		{"progress", required_argument, 0, 'P' },
		{"print", required_argument, 0, 'p' },
		{"quiet", no_argument, 0, 'q' },
		{"readfile", required_argument, 0, 'r' },
		{"snaplen", required_argument, 0, 's' },
		{"summary", no_argument, 0, 'S' },
		{"timetype", required_argument, 0, 't' },
		{"verbose", no_argument, 0, 'v' },
		{"writefile", required_argument, 0, 'w' },
		{"print-hex", no_argument, 0, 'x'},
		{"print-hex-ascii", no_argument, 0, 'X'},
		{0, 0, 0, 0}
	};

	output_format = "*%evt.num <TIME> %evt.cpu %proc.name (%thread.tid) %evt.dir %evt.type %evt.args";
//	output_format = DEFAULT_OUTPUT_STR;

	try
	{
		inspector = new sinsp();

#ifdef HAS_CHISELS
		add_chisel_dirs(inspector);
#endif

		//
		// Parse the args
		//
		while((op = getopt_long(argc, argv, "Aac:dDhi:jlLn:Pp:qr:Ss:t:vw:xXz", long_options, &long_index)) != -1)
		{
			switch(op)
			{
			case 'A':
				if(event_buffer_format != sinsp_evt::PF_NORMAL)
				{
					fprintf(stderr, "you cannot specify more than one output format\n");
					delete inspector;
					return EXIT_SUCCESS;
				}

				event_buffer_format = sinsp_evt::PF_EOLS;
				break;
			case 'a':
				absolute_times = true;
				break;
			case 0:
				if(cflag != 1 && cflag != 2)
				{
					break;
				}

				if(cflag == 2)
				{
					cname = optarg;
				}
#ifdef HAS_CHISELS
			case 'c':
				{
					if(cflag == 0)
					{
						string ostr(optarg);

						if(ostr.size() >= 1)
						{
							if(ostr == "l")
							{
								cflag = 1;
							}
						}
					}

					if(cflag == 1)
					{
						vector<chisel_desc> chlist;
						sinsp_chisel::get_chisel_list(&chlist);
						list_chisels(&chlist, true);
						delete inspector;
						return EXIT_SUCCESS;
					}

					sinsp_chisel* ch = new sinsp_chisel(inspector, optarg);
					parse_chisel_args(ch, inspector, optind, argc, argv, &n_filterargs);
					g_chisels.push_back(ch);
				}
#endif
				break;
			case 'D':
				inspector->set_debug_mode(true);
				break;
#ifdef HAS_CHISELS
			// --chisel-info and -i
			case 'i':
				{
					cname = optarg;

					vector<chisel_desc> chlist;

					sinsp_chisel::get_chisel_list(&chlist);

					for(uint32_t j = 0; j < chlist.size(); j++)
					{
						if(chlist[j].m_name == cname)
						{
							print_chisel_info(&chlist[j]);
							delete inspector;
							return EXIT_SUCCESS;
						}
					}

					throw sinsp_exception("chisel " + cname + " not found - use -cl to list them.");
				}
				break;
#endif

			case 'd':
				is_filter_display = true;
				break;
			case 'j':
//				throw sinsp_exception("json output not yet implemented");

				if(event_buffer_format != sinsp_evt::PF_NORMAL)
				{
					fprintf(stderr, "you cannot specify more than one output format\n");
					delete inspector;
					return EXIT_SUCCESS;
				}

				event_buffer_format = sinsp_evt::PF_JSON;
				break;
			case 'h':
				usage();
				delete inspector;
				return EXIT_SUCCESS;
			case 'l':
				list_flds = true;
				break;
			case 'L':
				list_events(inspector);
				delete inspector;
				return EXIT_SUCCESS;
			case 'n':
				cnt = atoi(optarg);
				if(cnt <= 0)
				{
					throw sinsp_exception(string("invalid packet count") + optarg);
					res = EXIT_FAILURE;
					goto exit;
				}
				break;
			case 'P':
				print_progress = true;
				break;
			case 'p':
				if(string(optarg) == "p")
				{
					//
					// -pp shows the default output format, useful if the user wants to tweak it.
					//
					replace_in_place(output_format, "<TIME>", timefmt);
					printf("%s\n", output_format.c_str());
					delete inspector;
					return EXIT_SUCCESS;
				}
				else
				{
					output_format = optarg;
				}

				break;
			case 'q':
				quiet = true;
				break;
			case 'r':
				infiles.push_back(optarg);
				break;
			case 'S':
				summary_table = new vector<summary_table_entry>;

				for(uint32_t j = 0; j < PPM_EVENT_MAX; j++)
				{
					summary_table->push_back(summary_table_entry(j, false));
				}

				for(uint32_t j = 0; j < PPM_SC_MAX * 2; j++)
				{
					summary_table->push_back(summary_table_entry(j, true));
				}

				break;
			case 's':
				snaplen = atoi(optarg);
				break;
			case 't':
				{
					string tms(optarg);

					if(tms == "h")
					{
						timefmt = "%evt.time";
					}
					else if(tms == "a")
					{
						timefmt = "%evt.rawtime.s.%evt.rawtime.ns";
					}
					else if(tms == "r")
					{
						timefmt = "%evt.reltime.s.%evt.reltime.ns";
					}
					else if(tms == "d")
					{
						timefmt = "%evt.latency.s.%evt.latency.ns";
					}
				}
				break;
			case 'v':
				verbose = true;
				break;
			case 'w':
				outfile = optarg;
				quiet = true;
				break;
			case 'x':
				if(event_buffer_format != sinsp_evt::PF_NORMAL)
				{
					fprintf(stderr, "you cannot specify more than one output format\n");
					delete inspector;
					return EXIT_SUCCESS;
				}

				event_buffer_format = sinsp_evt::PF_HEX;
				break;
			case 'X':
				if(event_buffer_format != sinsp_evt::PF_NORMAL)
				{
					fprintf(stderr, "you cannot specify more than one output format\n");
					delete inspector;
					return EXIT_SUCCESS;
				}

				event_buffer_format = sinsp_evt::PF_HEXASCII;
				break;
			case 'z':
				compress = true;
				break;
			default:
				break;
			}
		}

		inspector->set_buffer_format(event_buffer_format);

		//
		// If -l was specified, print the fields and exit
		//
		if(list_flds)
		{
			if(verbose)
			{
				//
				// -ll shows the fields verbosely, i.e. with more information
				// like the type
				//
				list_fields(true);
			}
			else
			{
				list_fields(false);
			}

			res = EXIT_SUCCESS;
			goto exit;
		}

		string filter;

		//
		// the filter is at the end of the command line
		//
		if(optind + n_filterargs < argc)
		{
#ifdef HAS_FILTERING
			for(int32_t j = optind + n_filterargs; j < argc; j++)
			{
				filter += argv[j];
				if(j < argc)
				{
					filter += " ";
				}
			}

			if(is_filter_display)
			{
				display_filter = new sinsp_filter(inspector, filter);
			}
#else
			fprintf(stderr, "filtering not compiled.\n");
			res = EXIT_FAILURE;
			goto exit;
#endif
		}

		if(signal(SIGINT, signal_callback) == SIG_ERR)
		{
			fprintf(stderr, "An error occurred while setting SIGINT signal handler.\n");
			res = EXIT_FAILURE;
			goto exit;
		}

		if(signal(SIGTERM, signal_callback) == SIG_ERR)
		{
			fprintf(stderr, "An error occurred while setting SIGTERM signal handler.\n");
			res = EXIT_FAILURE;
			goto exit;
		}

		//
		// Insert the right time format based on the -t flag
		//
		replace_in_place(output_format, "<TIME>", timefmt);

		//
		// Create the event formatter
		//
		sinsp_evt_formatter formatter(inspector, output_format);

		for(uint32_t j = 0; j < infiles.size() || infiles.size() == 0; j++)
		{
#ifdef HAS_FILTERING
			if(filter.size() && !is_filter_display)
			{
				inspector->set_filter(filter);
			}
#endif

			//
			// Launch the capture
			//
			bool open_success = true;

			if(infiles.size() != 0)
			{
				initialize_chisels();

				//
				// We have a file to open
				//
				inspector->open(infiles[j]);
			}
			else
			{
				if(j > 0)
				{
					break;
				}

				initialize_chisels();

				//
				// No file to open, this is a live capture
				//
#if defined(HAS_CAPTURE)
				if(print_progress)
				{
					fprintf(stderr, "the -P flag cannot be used with live captures.\n");
					res = EXIT_FAILURE;
					goto exit;
				}

				try
				{
					inspector->open("");
				}
				catch(sinsp_exception e)
				{
					open_success = false;
				}
#else
				//
				// Starting live capture
				// If this fails on Windows and OSX, don't try with any driver
				//
				inspector->open("");
#endif

				//
				// Starting the live capture failed, try to load the driver with
				// modprobe.
				//
				if(!open_success)
				{
					open_success = true;

					system("modprobe sysdig-probe > /dev/null 2> /dev/null");

					inspector->open("");
				}
			}

			if(snaplen != 0)
			{
				inspector->set_snaplen(snaplen);
			}

			duration = ((double)clock()) / CLOCKS_PER_SEC;

			if(outfile != "")
			{
				inspector->autodump_start(outfile, compress);
			}

			//
			// Notify the chisels that the capture is starting
			//
			chisels_on_capture_start();

			cinfo = do_inspect(inspector,
				cnt,
				quiet,
				absolute_times,
				print_progress,
				display_filter,
				summary_table,
				&formatter);

			duration = ((double)clock()) / CLOCKS_PER_SEC - duration;

			scap_stats cstats;
			inspector->get_capture_stats(&cstats);

			if(verbose)
			{
				fprintf(stderr, "Driver Events:%" PRIu64 "\nDriver Drops:%" PRIu64 "\n",
					cstats.n_evts,
					cstats.n_drops);

				fprintf(stderr, "Elapsed time: %.3lf, Captured Events: %" PRIu64 ", %.2lf eps\n",
					duration,
					cinfo.m_nevts,
					(double)cinfo.m_nevts / duration);
			}

			//
			// Done. Close the capture.
			//
			inspector->close();

		}
	}
	catch(sinsp_exception& e)
	{
		cerr << e.what() << endl;
		handle_end_of_file(print_progress);
		res = EXIT_FAILURE;
	}
	catch(...)
	{
		handle_end_of_file(print_progress);
		res = EXIT_FAILURE;
	}

exit:

	//
	// If there's a summary table, sort and print it
	//
	if(summary_table != NULL)
	{
		print_summary_table(inspector, summary_table, 100);
	}

	free_chisels();

	if(inspector)
	{
		delete inspector;
	}

	if(display_filter)
	{
		delete display_filter;
	}

#ifdef _WIN32
	_CrtDumpMemoryLeaks();
#endif

	return res;
}
Esempio n. 11
0
void list_events(int day_filter, int mon_filter, int year_filter) {
	unsigned int current_page = 1, max_page, index_page = 0;
	unsigned int mod = myVector.size() % 12;
	int key, n_keys = 0, selected_event_index;
	char type_keys[66];

	erase();
	titlebar();
	refresh();
	resize_term(40, 80);

	attron(COLOR_PAIR(3));
	mvprintw(2, 1, "List Event(s)");
	mvprintw(3, 1, "-------------");

	// Draw table
	mvvline(5, 1, 0, 29);
	mvvline(5, 6, 0, 29);
	mvvline(5, 51, 0, 29);
	mvvline(5, 70, 0, 29);
	mvvline(5, 78, 0, 29);
	mvhline(5, 1, 0, 78);
	mvhline(7, 1, 0, 78);
	mvhline(33, 1, 0, 78);

	// Print out some text
	mvprintw(6, 3, "No");
	mvprintw(6, 8, "Event Name");
	mvprintw(6, 53, "Date");
	mvprintw(6, 72, "Time");

	refresh();

	WINDOW *wID, *wNAME, *wDATE, *wTIME, *wDET, *wSTAT;

	wID = newwin(25, 4, 8, 2);
	wrefresh(wID);

	wNAME = newwin(25, 42, 8, 8);
	wrefresh(wNAME);

	wDATE = newwin(25, 18, 8, 52);
	wrefresh(wDATE);

	wTIME = newwin(25, 7, 8, 71);
	wrefresh(wTIME);

	wDET = newwin(4, 78, 36, 1);
	wattron(wDET, COLOR_PAIR(6));
	mvwprintw(wDET, 0, 0, "Press LEFT or RIGHT to change the page. Type any event number and press E to \nedit, D to delete, R to swap two events or ENTER for more details.\nOr you can press S to sort all the events. To go back, press ESC.");
	wrefresh(wDET);

	wSTAT = newwin(1, 78, 39, 1);
	wrefresh(wSTAT);

	// Declare variable for filter purpose
	std::vector<my_event> filter;
	std::vector<my_event> *list;
	my_event temp;

	// Apply filter for saved events. Copy data to the temporary local vector and print to the list.
	// Optional function. Maybe not implemented for now.
	// Since the code is identical, only the logical expression different. So it can be simpified but not for now.
	if (day_filter != 0 || mon_filter != 0 || year_filter != 0) {
		for (unsigned int z = 0; z < myVector.size(); z++) {
			if (year_filter != 0) {
				if (myVector[z].year == year_filter) {
					temp.hour = myVector[z].hour;
					temp.min = myVector[z].min;
					temp.day = myVector[z].day;
					temp.nmon = myVector[z].nmon;
					temp.year = myVector[z].year;
					temp.save_name(myVector[z].name);
					temp.save_loc(myVector[z].loc);
					//temp.save_desc(myVector[z].desc);
					filter.push_back(temp);
				}
			}
			if (mon_filter != 0) {
				if (myVector[z].nmon == mon_filter) {
					temp.hour = myVector[z].hour;
					temp.min = myVector[z].min;
					temp.day = myVector[z].day;
					temp.nmon = myVector[z].nmon;
					temp.year = myVector[z].year;
					temp.save_name(myVector[z].name);
					temp.save_loc(myVector[z].loc);
					//temp.save_desc(myVector[z].desc);
					filter.push_back(temp);
				}
			}
			if (day_filter != 0) {
				if (myVector[z].day == day_filter) {
					temp.hour = myVector[z].hour;
					temp.min = myVector[z].min;
					temp.day = myVector[z].day;
					temp.nmon = myVector[z].nmon;
					temp.year = myVector[z].year;
					temp.save_name(myVector[z].name);
					temp.save_loc(myVector[z].loc);
					//temp.save_desc(myVector[z].desc);
					filter.push_back(temp);
				}
			}
			if (day_filter != 0 && mon_filter != 0) {
				if (myVector[z].day == day_filter && myVector[z].nmon == mon_filter) {
					temp.hour = myVector[z].hour;
					temp.min = myVector[z].min;
					temp.day = myVector[z].day;
					temp.nmon = myVector[z].nmon;
					temp.year = myVector[z].year;
					temp.save_name(myVector[z].name);
					temp.save_loc(myVector[z].loc);
					//temp.save_desc(myVector[z].desc);
					filter.push_back(temp);
				}
			}
			if (year_filter != 0 && mon_filter != 0) {
				if (myVector[z].year == year_filter && myVector[z].nmon == mon_filter) {
					temp.hour = myVector[z].hour;
					temp.min = myVector[z].min;
					temp.day = myVector[z].day;
					temp.nmon = myVector[z].nmon;
					temp.year = myVector[z].year;
					temp.save_name(myVector[z].name);
					temp.save_loc(myVector[z].loc);
					//temp.save_desc(myVector[z].desc);
					filter.push_back(temp);
				}
			}
			if (day_filter != 0 && mon_filter != 0 && year_filter != 0) {
				if (myVector[z].day == day_filter && myVector[z].nmon == mon_filter && myVector[z].year == year_filter) {
					temp.hour = myVector[z].hour;
					temp.min = myVector[z].min;
					temp.day = myVector[z].day;
					temp.nmon = myVector[z].nmon;
					temp.year = myVector[z].year;
					temp.save_name(myVector[z].name);
					temp.save_loc(myVector[z].loc);
					//temp.save_desc(myVector[z].desc);
					filter.push_back(temp);
				}
			}
		}
		list = &filter;
	}
	else list = &myVector;

	if (mod != 0) max_page = (int)(ceil((*list).size() / 12)) + 1;
	else max_page = (*list).size() / 12;

	while (1) {

		werase(wID);
		werase(wNAME);
		werase(wDATE);
		werase(wTIME);
		mvprintw(34, 1, "Page: %i/%i", current_page, max_page);

		int n_line = 1;
		for (unsigned int i = index_page; i < index_page + 12; i++) {
			if (i < (*list).size()) {
				mvwprintw(wID, n_line, 1, "%i", i + 1);
				mvwprintw(wNAME, n_line, 0, "%s", (*list)[i].name);
				mvwprintw(wDATE, n_line, 1, "%i %s %i", (*list)[i].day, mon_name((*list)[i].nmon), (*list)[i].year);
				wformatted_time(wTIME, n_line, 1, (*list)[i].hour, (*list)[i].min);
				wrefresh(wID);
				wrefresh(wNAME);
				wrefresh(wDATE);
				wrefresh(wTIME);
				n_line += 2;
			}
		}

		key = getch();
		//mvprintw(39, 1, "%i", key);

		if (key == 115 || key == 83) {
			werase(wDET);
			wattron(wDET, COLOR_PAIR(6));
			mvwprintw(wDET, 0, 0, "Press 1 to sort by Day, 2 to sort by Month or 3 to sort by Year.\nPress ESC to go back.");
			wattroff(wDET, COLOR_PAIR(6));
			wrefresh(wDET);
			werase(wSTAT);
			while (1) {
				key = getch();
				if (!(key >= 49 && key <= 51) || key != 27) {
					werase(wDET);
					wattron(wDET, COLOR_PAIR(5));
					mvwprintw(wDET, 0, 0, "Invalid selection...");
					wattroff(wDET, COLOR_PAIR(5));
					wrefresh(wDET);
				}
				if (key == 49) {
					std::sort(myVector.begin(), myVector.end(), SortDay());
					break;
				}
				if (key == 50) {
					std::sort(myVector.begin(), myVector.end(), SortMonth());
					break;
				}
				if (key == 51) {
					std::sort(myVector.begin(), myVector.end(), SortYear());
					break;
				}
				if (key == 27) break;
			}
			break;
		}

		if ((key >= 48 && key <= 57) || key == 8) {
			if (key >= 48 && key <= 57) {
				if (n_keys <= 66) {
					werase(wSTAT);
					type_keys[n_keys] = char(key);
					n_keys++;

					wattron(wSTAT, COLOR_PAIR(3));
					mvwprintw(wSTAT, 0, 0, "Event No: ");
					wattroff(wSTAT, COLOR_PAIR(3));

					wattron(wSTAT, COLOR_PAIR(7));
					for (int o = 0; o < n_keys; o++) wprintw(wSTAT, "%c", type_keys[o]);		// Show the user for any typed numbers
					wrefresh(wSTAT);
					wattroff(wSTAT, COLOR_PAIR(7));
				}
			}
			if (key == 8) {
				if (n_keys > 1) {
					werase(wSTAT);
					type_keys[n_keys] = ' ';
					type_keys[n_keys - 1] = ' ';
					n_keys--;

					wattron(wSTAT, COLOR_PAIR(3));
					mvwprintw(wSTAT, 0, 0, "Event No: ");
					wattroff(wSTAT, COLOR_PAIR(3));

					wattron(wSTAT, COLOR_PAIR(7));
					for (int o = 0; o < n_keys; o++) wprintw(wSTAT, "%c", type_keys[o]);
					wrefresh(wSTAT);
					wattroff(wSTAT, COLOR_PAIR(7));
				}
				else {
					werase(wSTAT);
					wrefresh(wSTAT);
					n_keys = 0;
				}
			}
		}

		// User pressed enter/E/D (all caps)
		if (key == 13 || key == 100 || key == 68 || key == 69 || key == 101 || key == 82 || key == 114) {
			if (n_keys > 0) {
				selected_event_index = atol(&type_keys[0]);
				if (selected_event_index >= 1 && selected_event_index <= int((*list).size())) break;
				else {
					werase(wSTAT);
					wrefresh(wSTAT);
					werase(wDET);
					wattron(wDET, COLOR_PAIR(5));
					mvwprintw(wDET, 0, 0, "Invalid number or out of range.\nPlease try again...");
					wattroff(wDET, COLOR_PAIR(5));
					wrefresh(wDET);
					for (int o = 0; o <= 66; o++) type_keys[o] = ' ';						// Clear the array
					n_keys = 0;																// Reset the number of key typed
				}
			}
		}

		if (key == 27) menu();

		if (key == KEY_RIGHT) {
			if (current_page < max_page) {
				index_page += 12;
				current_page++;
				continue;
			}
		}

		if (key == KEY_LEFT) {
			if (current_page > 1) {
				index_page -= 12;
				current_page--;
				continue;
			}
		}

		if (key == KEY_F(2)) {
			mvprintw(5, 1, "%i", myVector.size());
			//refresh();
		}

		if (key == KEY_F(1)) exit(0);
	}

	if (key == 13) data.show_details(selected_event_index - 1);
	if (key == 100 || key == 68) data.delete_event(selected_event_index - 1);
	if (key == 101 || key == 69) data.edit_event(selected_event_index - 1);

	// Sorting Lab 4
//	if (key == 82 || key == 114) {
		
	//}

	// Swapping Lab 3
	if (key == 82 || key == 114) {
		werase(wDET);
		wattron(wDET, COLOR_PAIR(6));
		mvwprintw(wDET, 0, 0, "Now enter the second event number to replace.\nPress ESC to cancel.");
		wattroff(wDET, COLOR_PAIR(6));
		wrefresh(wDET);
		werase(wSTAT);
		mvwprintw(wSTAT, 0, 0, "Event No To Replace: ");
		wrefresh(wSTAT);
		for (int o = 0; o <= 66; o++) type_keys[o] = ' ';						// Clear the array
		n_keys = 0;
		while (1) {
			key = getch();
			if (key == 27) break;
			if (key >= 48 && key <= 57) {
				if (n_keys <= 66) {
					werase(wSTAT);
					type_keys[n_keys] = char(key);
					n_keys++;

					wattron(wSTAT, COLOR_PAIR(3));
					mvwprintw(wSTAT, 0, 0, "Event No To Replace: ");
					wattroff(wSTAT, COLOR_PAIR(3));

					wattron(wSTAT, COLOR_PAIR(7));
					for (int o = 0; o < n_keys; o++) wprintw(wSTAT, "%c", type_keys[o]);		// Show the user for any typed numbers
					wrefresh(wSTAT);
					wattroff(wSTAT, COLOR_PAIR(7));
				}
			}
			if (key == 8) {
				if (n_keys > 1) {
					werase(wSTAT);
					type_keys[n_keys] = ' ';
					type_keys[n_keys - 1] = ' ';
					n_keys--;

					wattron(wSTAT, COLOR_PAIR(3));
					mvwprintw(wSTAT, 0, 0, "Event No To Replace: ");
					wattroff(wSTAT, COLOR_PAIR(3));

					wattron(wSTAT, COLOR_PAIR(7));
					for (int o = 0; o < n_keys; o++) wprintw(wSTAT, "%c", type_keys[o]);
					wrefresh(wSTAT);
					wattroff(wSTAT, COLOR_PAIR(7));
				}
				else {
					werase(wSTAT);
					wrefresh(wSTAT);
					n_keys = 0;
				}
			}

			if (key == 13 || key == 100) {
				if (n_keys > 0) {
					int sec_selected_event_index;
					sec_selected_event_index = atol(&type_keys[0]);
					if (sec_selected_event_index >= 1 && sec_selected_event_index <= int((*list).size()) && selected_event_index != sec_selected_event_index) {
						/*mvwprintw(wSTAT, 0, 0, "selected: %i, second: %i",selected_event_index,sec_selected_event_index);
						wrefresh(wSTAT);
						getch();*/
						swap(selected_event_index - 1, sec_selected_event_index - 1);
						break;
					}
					else {
						werase(wSTAT);
						wrefresh(wSTAT);
						werase(wDET);
						wattron(wDET, COLOR_PAIR(5));
						mvwprintw(wDET, 0, 0, "Invalid number or out of range.\nPlease try again...");
						wattroff(wDET, COLOR_PAIR(5));
						wrefresh(wDET);
						for (int o = 0; o <= 66; o++) type_keys[o] = ' ';						// Clear the array
						n_keys = 0;																// Reset the number of key typed
						werase(wSTAT);
						mvwprintw(wSTAT, 0, 0, "Event No To Replace: ");
						wrefresh(wSTAT);
					}
				}
			}
		}

	}

	list_events();
}
Esempio n. 12
0
// Menu function
void menu() {
	int key;

	resize_term(25, 80);
	erase();
	titlebar();
	noecho();

	attron(COLOR_PAIR(3));
	mvprintw(2, 1, "Menu");
	mvprintw(3, 1, "----");
	mvprintw(5, 1, "1) Create a new event");
	mvprintw(6, 1, "2) View or edit event");
	mvprintw(7, 1, "3) Change month / year (Selected: %s %i)", mon_name(selected_mon), selected_year);
	mvprintw(8, 1, "4) Save all events to file");
	mvprintw(9, 1, "Q) Quit program");
	//mvprintw(23, 1, "Created by Ijat (172205)");
	attron(COLOR_PAIR(8));
	mvprintw(23, 1, "(c) 2014 Ijat.my");
	attron(COLOR_PAIR(3));
	mvprintw(11, 1, "Your selection: ");
	refresh();

	// Check user input
	while (1) {
		key = getch();
		//mvprintw(23, 1, "%i", key);

		// Pressed 1
		if (key == 49) { create_new_event(false); }

		// Pressed 2
		if (key == 50) {
			if (event_saved == false) {
				attron(COLOR_PAIR(5));
				mvhline(23, 1, ' ', 78);
				mvprintw(23, 1, "No event(s) saved. Nothing to view. Please create a new event first!");
				refresh();
				attroff(COLOR_PAIR(5));
			}
			else if (event_saved == true) { //view_event(); 
				list_events();
			}
		}

		// Pressed 3
		if (key == 51) change_mon(); 

		if (key == 52) {
			if (event_saved == true) {
				attron(COLOR_PAIR(6));
				mvprintw(23, 1, "Saved to \"My Events.txt\"");
				data.print_details();
				attroff(COLOR_PAIR(6));
			}
			else {
				attron(COLOR_PAIR(5));
				mvhline(23, 1, ' ', 78);
				mvprintw(23, 1, "No event(s) to save. Please create a event first!");
				attroff(COLOR_PAIR(5));
			}
		}

		// Pressed Q
		if (key == 113 || key == 81) exit(0);
	}
}
Esempio n. 13
0
// A function to create the "create new event" page.
// This function is the most crucial part in the program which is handling user inputs/data
void create_new_event(bool edit, int z_index ) {
	// This will enable the input to be shown to the user when type.
	resize_term(40, 80);
	echo();

	// Variables
	char rawday, rawname, rawloc, rawhour, rawminute;	// Raw variables used for pdcurses function
	int confirmation;
	bool eventloop = false;									// Indicator for the loop
	int n_day, n_hour, n_minute;							// Day variable which is to be selected by the user

	// Loop until get a data to be saved in data object
	while (eventloop == false) {
		// Empty the console, add titlebar and redraw all.
		erase();
		titlebar();
		refresh();
		raw();

		attron(COLOR_PAIR(3));
		if (edit == true) {
			mvprintw(2, 1, "Edit Event");
			mvprintw(3, 1, "----------");
		}
		else {
			mvprintw(2, 1, "Create New Event");
			mvprintw(3, 1, "----------------");
		}

		mvprintw(20, 1, "Date\t\t:");
		mvprintw(22, 1, "Time\t\t:");
		mvprintw(24, 1, "Event name\t:");
		mvprintw(26, 1, "Location\t:");
		//mvprintw(28, 1, "Description\t:");
		
		// Disabled due to BUG002
		// A small window for description to fit in the text in nice allignment.
		/*WINDOW *wdesc;
		wdesc = newwin(3, 60, 28, 18);
		wattron(wdesc, COLOR_PAIR(3));*/

		// Show calendar, without any inputs
		mvprintw(4, 36, "Calendar");
		show_calendar(false, 14, 6);

		// Show status window (used to deliver message to the user about error, etc.)
		statuswin();

		// Update text in status window
		update_status("Please select the day for the event...\n\nTo go back, press ESC and ENTER",6);
		//refresh();

		// Do this loop until the program obtained a valid day

		do {
			mvhline(20, 18, ' ', 3);											// Clear a small portion of the console
			mvprintw(20, 21, "%s %i", mon_name(selected_mon), selected_year);	// Print the month and year
			mvgetnstr(20, 18, &rawday, 2);										// User input of the day
			if (rawday == 27) menu();												// If user pressed esc and enter, the program will go back to main menu
			n_day = atoi(&rawday);
			//n_day = day;														// A C-function to convert char * to int
			if (n_day == 0 || n_day > max_day_in_month) { update_status("Invalid day. Please enter a valid DAY in the selected month.\n\nTo go back, press ESC and ENTER.",5); }			// Inform user if the day not valid
			refresh();															// Redraw
		} while (n_day == 0 || n_day > max_day_in_month);						// Check if the day valid or not

		// Got a nice and valid n_day and print again to the screen.
		mvhline(20, 18, ' ', 60);												// Refresh the line
		mvprintw(20, 18, "%i %s %i", n_day, mon_name(selected_mon), selected_year);

		// Update to the current status.
		update_status("Please enter the hour in 24 hours...\nIf you enter some string, the result will be 0.", 6);

		// A loop that handle the time input. Runs loop until it gets the valid time.
		do {

			mvhline(22, 18, ' ', 6);											// Clear the line
			mvgetnstr(22, 18, &rawhour, 2);										// Get hour from user
			if (rawhour == 27) menu();											// If user input is ESC then go back to menu
			n_hour = atoi(&rawhour);											// Convert from char to int
			if ( !(n_hour >= 0 && n_hour < 24) ) {								// Check for valid hour
				update_status("Invalid hour. Enter a number in between 0-23. Please try again...", 5);
				continue;
			}
			else {
				mvprintw(22, 20, ":");
				update_status("Please enter the minute...\nIf you enter some string, the result will be 0.", 6);
				do {
					mvhline(22, 21, ' ', 3);
					mvgetnstr(22, 21, &rawminute, 2);
					if (rawminute == 27) menu();
					n_minute = atoi(&rawminute);								// Convert from char to int
					if (!(n_minute >= 0 && n_minute < 60)) {					// Check for valid minutes
						update_status("Invalid minute. Type a number in between 0-59. Please try again...", 5);
						continue;
					}
					else break;
				} while (1);
				break;
			}
		} while (1);

		// Print the time nicely.
		mvhline(22, 18, ' ', 6);
		formatted_time(22, 18, n_hour, n_minute);		// Print time in formatted form xx:yy

		// Update the status
		update_status("Now fill the name, location and description of the event.");

		// Get event name, location and description		// BUG001
		mvgetnstr(24, 18, &rawname, 28);				// First program bug detected here (Read below for more)
		data.save_name(&rawname);						// This function is used to copy rawname char * to another variable in normal char type. It copy the data to a more reliable variable.
														// This is because to prevent memory leak or maybe something else that causes the data in other the pointer (this is bad due to it affect other variable as well) overwritten by the typed data. Approximate more than 11 characters will cause the memory leak -- TESTED)
		mvgetnstr(26, 18, &rawloc, 28);					// Also, to prevent this bug, this function data.save_*** is called right after the user input the data.
		data.save_loc(&rawloc);							// This problem maybe related to the pdcurses library bug that cause the memory leak which affect other variables too.

		//mvwgetnstr(wdesc, 0, 0, &rawdesc, 28);		// BUG002
		//data.save_desc(&rawdesc);						// The program will crash when number of characters more than 28 chars. The cause still unknown. To fix whether to create another custom function to handle input (which is long) or decrease the numbers of characters (which is the quickest way to solve).

		refresh();

		// Clear status
		werase(wstatus);
		wrefresh(wstatus);

		// User confirmation
		mvprintw(32, 1, "Are you sure? (Y/N): ");
		refresh();

		// A loop to check only y/Y/n/N are allowed as a user input
		while (1) {
			mvhline(32, 22, ' ', 1);
			confirmation = getch();
			if (confirmation == 780 || confirmation == 110 || confirmation == 121 || confirmation == 891) { break; }
		}

		// If user type y/Y, the the loop ends
		if (confirmation == 121 || confirmation == 891){
			eventloop = true;								// To ensure that this will break the loop and will not continue anymore
			data.day = n_day;								// Save user inputs
			data.year = selected_year;
			data.nmon = selected_mon;

			// LAB-2
			data.hour = n_hour;
			data.min = n_minute;

			if (edit == true) {
				myVector.erase(myVector.begin() + z_index);
				myVector.insert(myVector.begin() + z_index, data);
				list_events();
			}
			else {
				myVector.push_back(data);
				event_saved = true;								// Tells the program about the saved data
				break;
			}
		}
	}

	if (edit == false) menu();
}
Esempio n. 14
0
//
// ARGUMENT PARSING AND PROGRAM SETUP
//
sysdig_init_res sysdig_init(int argc, char **argv)
{
	sysdig_init_res res;
	sinsp* inspector = NULL;
	vector<string> infiles;
	string outfile;
	int op;
	uint64_t cnt = -1;
	bool quiet = false;
	bool is_filter_display = false;
	bool verbose = false;
	bool list_flds = false;
	bool print_progress = false;
	bool compress = false;
	sinsp_evt::param_fmt event_buffer_format = sinsp_evt::PF_NORMAL;
	sinsp_filter* display_filter = NULL;
	double duration = 1;
	captureinfo cinfo;
	string output_format;
	uint32_t snaplen = 0;
	int long_index = 0;
	int32_t n_filterargs = 0;
	int cflag = 0;
	bool jflag = false;
	string cname;
	vector<summary_table_entry>* summary_table = NULL;
	string timefmt = "%evt.time";

	// These variables are for the cycle_writer engine
	int duration_seconds = 0;	
	int rollover_mb = 0;
	int file_limit = 0;
	bool do_cycle = false;

	static struct option long_options[] =
	{
		{"print-ascii", no_argument, 0, 'A' },
		{"print-base64", no_argument, 0, 'b' },
#ifdef HAS_CHISELS
		{"chisel", required_argument, 0, 'c' },
		{"list-chisels", no_argument, &cflag, 1 },
#endif
		{"compress", no_argument, 0, 'z' },
		{"displayflt", no_argument, 0, 'd' },
		{"debug", no_argument, 0, 'D'},
		{"fatfile", no_argument, 0, 'F'},
#ifndef DISABLE_CGW
		{"seconds", required_argument, 0, 'G' },
#endif
		{"help", no_argument, 0, 'h' },
#ifdef HAS_CHISELS
		{"chisel-info", required_argument, 0, 'i' },
#endif
#ifndef DISABLE_CGW
		{"file-size", required_argument, 0, 'C' },
#endif
		{"json", no_argument, 0, 'j' },
		{"list", no_argument, 0, 'l' },
		{"list-events", no_argument, 0, 'L' },
		{"numevents", required_argument, 0, 'n' },
		{"progress", required_argument, 0, 'P' },
		{"print", required_argument, 0, 'p' },
		{"quiet", no_argument, 0, 'q' },
		{"readfile", required_argument, 0, 'r' },
		{"snaplen", required_argument, 0, 's' },
		{"summary", no_argument, 0, 'S' },
		{"timetype", required_argument, 0, 't' },
		{"verbose", no_argument, 0, 'v' },
		{"version", no_argument, 0, 0 },
		{"writefile", required_argument, 0, 'w' },
#ifndef DISABLE_CGW
		{"limit", required_argument, 0, 'W' },
#endif
		{"print-hex", no_argument, 0, 'x'},
		{"print-hex-ascii", no_argument, 0, 'X'},
		{0, 0, 0, 0}
	};

	output_format = "*%evt.num <TIME> %evt.cpu %proc.name (%thread.tid) %evt.dir %evt.type %evt.info";
//	output_format = DEFAULT_OUTPUT_STR;

	try
	{
		inspector = new sinsp();

#ifdef HAS_CHISELS
		add_chisel_dirs(inspector);
#endif

		//
		// Parse the args
		//
		while((op = getopt_long(argc, argv,
                                        "Abc:"
#ifndef DISABLE_CGW
                                        "C:"
#endif
                                        "dDF"
#ifndef DISABLE_CGW
                                        "G:"
#endif
                                        "hi:jlLn:Pp:qr:Ss:t:v"
#ifndef DISABLE_CGW
                                        "W:"
#endif
                                        "w:xXz", long_options, &long_index)) != -1)
		{
			switch(op)
			{
			case 'A':
				if(event_buffer_format != sinsp_evt::PF_NORMAL)
				{
					fprintf(stderr, "you cannot specify more than one output format\n");
					delete inspector;
					return sysdig_init_res(EXIT_SUCCESS);
				}

				event_buffer_format = sinsp_evt::PF_EOLS;
				break;
			case 'b':
				if(event_buffer_format != sinsp_evt::PF_NORMAL)
				{
					fprintf(stderr, "you cannot specify more than one output format\n");
					delete inspector;
					return sysdig_init_res(EXIT_SUCCESS);
				}

				event_buffer_format = sinsp_evt::PF_BASE64;
				break;
			case 0:
				if(cflag != 1 && cflag != 2)
				{
					break;
				}

				if(cflag == 2)
				{
					cname = optarg;
				}
#ifdef HAS_CHISELS
			case 'c':
				{
					if(cflag == 0)
					{
						string ostr(optarg);

						if(ostr.size() >= 1)
						{
							if(ostr == "l")
							{
								cflag = 1;
							}
						}
					}

					if(cflag == 1)
					{
						vector<chisel_desc> chlist;
						sinsp_chisel::get_chisel_list(&chlist);
						list_chisels(&chlist, true);
						delete inspector;
						return sysdig_init_res(EXIT_SUCCESS);
					}

					sinsp_chisel* ch = new sinsp_chisel(inspector, optarg);
					parse_chisel_args(ch, inspector, optind, argc, argv, &n_filterargs);
					g_chisels.push_back(ch);
				}
#endif
				break;

#ifndef DISABLE_CGW
			// File-size
			case 'C':
				rollover_mb = atoi(optarg);
				if(rollover_mb <= 0)
				{
					throw sinsp_exception(string("invalid file size") + optarg);
					res.m_res = EXIT_FAILURE;
					goto exit;
				}

				// -C always implicates a cycle
				do_cycle = true;
				break;
#endif

			case 'D':
				inspector->set_debug_mode(true);
				break;
			case 'F':
				inspector->set_fatfile_dump_mode(true);
				break;
#ifndef DISABLE_CGW
			// Number of seconds between roll-over
			case 'G':
				duration_seconds = atoi(optarg);
				if(duration_seconds <= 0)
				{
					throw sinsp_exception(string("invalid duration") + optarg);
					res.m_res = EXIT_FAILURE;
					goto exit;
				}
				break;
#endif

#ifdef HAS_CHISELS
			// --chisel-info and -i
			case 'i':
				{
					cname = optarg;

					vector<chisel_desc> chlist;

					sinsp_chisel::get_chisel_list(&chlist);

					for(uint32_t j = 0; j < chlist.size(); j++)
					{
						if(chlist[j].m_name == cname)
						{
							print_chisel_info(&chlist[j]);
							delete inspector;
							return sysdig_init_res(EXIT_SUCCESS);
						}
					}

					throw sinsp_exception("chisel " + cname + " not found - use -cl to list them.");
				}
				break;
#endif

			case 'd':
				is_filter_display = true;
				break;
			case 'j':
				//
				// set the json flag to 1 for now, the data format will depend from the print format parameters
				//
				jflag = true;
				break;
			case 'h':
				usage();
				delete inspector;
				return sysdig_init_res(EXIT_SUCCESS);
			case 'l':
				list_flds = true;
				break;
			case 'L':
				list_events(inspector);
				delete inspector;
				return sysdig_init_res(EXIT_SUCCESS);
			case 'n':
				cnt = atoi(optarg);
				if(cnt <= 0)
				{
					throw sinsp_exception(string("invalid event count ") + optarg);
					res.m_res = EXIT_FAILURE;
					goto exit;
				}
				break;
			case 'P':
				print_progress = true;
				break;
			case 'p':
				if(string(optarg) == "p")
				{
					//
					// -pp shows the default output format, useful if the user wants to tweak it.
					//
					replace_in_place(output_format, "<TIME>", timefmt);
					printf("%s\n", output_format.c_str());
					delete inspector;
					return sysdig_init_res(EXIT_SUCCESS);
				}
				else
				{
					output_format = optarg;
				}

				break;
			case 'q':
				quiet = true;
				break;
			case 'r':
				infiles.push_back(optarg);
				break;
			case 'S':
				summary_table = new vector<summary_table_entry>;

				for(uint32_t j = 0; j < PPM_EVENT_MAX; j++)
				{
					summary_table->push_back(summary_table_entry(j, false));
				}

				for(uint32_t j = 0; j < PPM_SC_MAX * 2; j++)
				{
					summary_table->push_back(summary_table_entry(j, true));
				}

				break;
			case 's':
				snaplen = atoi(optarg);
				break;
			case 't':
				{
					string tms(optarg);

					if(tms == "h")
					{
						timefmt = "%evt.time";
					}
					else if(tms == "a")
					{
						timefmt = "%evt.rawtime.s.%evt.rawtime.ns";
					}
					else if(tms == "r")
					{
						timefmt = "%evt.reltime.s.%evt.reltime.ns";
					}
					else if(tms == "d")
					{
						timefmt = "%evt.latency.s.%evt.latency.ns";
					}
					else if(tms == "D")
					{
						timefmt = "%evt.deltatime.s.%evt.deltatime.ns";
					}
					else
					{
						fprintf(stderr, "invalid modifier for flag -t\n");
						delete inspector;
						return sysdig_init_res(EXIT_FAILURE);
					}
				}
				break;
			case 'v':
				verbose = true;
				break;
			case 'w':
				outfile = optarg;
				quiet = true;
				break;

#ifndef DISABLE_CGW
			// Number of capture files to cycle through
			case 'W':
				file_limit = atoi(optarg);
				if(file_limit <= 0)
				{
					throw sinsp_exception(string("invalid file limit") + optarg);
					res.m_res = EXIT_FAILURE;
					goto exit;
				}
				break;
#endif

			case 'x':
				if(event_buffer_format != sinsp_evt::PF_NORMAL)
				{
					fprintf(stderr, "you cannot specify more than one output format\n");
					delete inspector;
					return sysdig_init_res(EXIT_FAILURE);
				}

				event_buffer_format = sinsp_evt::PF_HEX;
				break;
			case 'X':
				if(event_buffer_format != sinsp_evt::PF_NORMAL)
				{
					fprintf(stderr, "you cannot specify more than one output format\n");
					delete inspector;
					return sysdig_init_res(EXIT_FAILURE);
				}

				event_buffer_format = sinsp_evt::PF_HEXASCII;
				break;
			case 'z':
				compress = true;
				break;
			default:
				break;
			}

			if(string(long_options[long_index].name) == "version")
			{
				printf("sysdig version %s\n", SYSDIG_VERSION);
				delete inspector;
				return sysdig_init_res(EXIT_SUCCESS);
			}
		}

		//
		// If -j was specified the event_buffer_format must be rewritten to account for it
		//
		if(jflag)
		{
			switch (event_buffer_format)
			{
				case sinsp_evt::PF_NORMAL:
					event_buffer_format = sinsp_evt::PF_JSON;
					break;
				case sinsp_evt::PF_EOLS:
					event_buffer_format = sinsp_evt::PF_JSONEOLS;
					break;
				case sinsp_evt::PF_HEX:
					event_buffer_format = sinsp_evt::PF_JSONHEX;
					break;
				case sinsp_evt::PF_HEXASCII:
					event_buffer_format = sinsp_evt::PF_JSONHEXASCII;
					break;
				case sinsp_evt::PF_BASE64:
					event_buffer_format = sinsp_evt::PF_JSONBASE64;
					break;
				default:
					// do nothing
					break;
			}
		}

		inspector->set_buffer_format(event_buffer_format);

		//
		// If -l was specified, print the fields and exit
		//
		if(list_flds)
		{
			if(verbose)
			{
				//
				// -ll shows the fields verbosely, i.e. with more information
				// like the type
				//
				list_fields(true);
			}
			else
			{
				list_fields(false);
			}

			res.m_res = EXIT_SUCCESS;
			goto exit;
		}

		string filter;

		//
		// the filter is at the end of the command line
		//
		if(optind + n_filterargs < argc)
		{
#ifdef HAS_FILTERING
			for(int32_t j = optind + n_filterargs; j < argc; j++)
			{
				filter += argv[j];
				if(j < argc)
				{
					filter += " ";
				}
			}

			if(is_filter_display)
			{
				display_filter = new sinsp_filter(inspector, filter);
			}
#else
			fprintf(stderr, "filtering not compiled.\n");
			res.m_res = EXIT_FAILURE;
			goto exit;
#endif
		}

		if(signal(SIGINT, signal_callback) == SIG_ERR)
		{
			fprintf(stderr, "An error occurred while setting SIGINT signal handler.\n");
			res.m_res = EXIT_FAILURE;
			goto exit;
		}

		if(signal(SIGTERM, signal_callback) == SIG_ERR)
		{
			fprintf(stderr, "An error occurred while setting SIGTERM signal handler.\n");
			res.m_res = EXIT_FAILURE;
			goto exit;
		}

		//
		// Insert the right time format based on the -t flag
		//
		replace_in_place(output_format, "<TIME>", timefmt);

		//
		// Create the event formatter
		//
		sinsp_evt_formatter formatter(inspector, output_format);

		for(uint32_t j = 0; j < infiles.size() || infiles.size() == 0; j++)
		{
#ifdef HAS_FILTERING
			if(filter.size() && !is_filter_display)
			{
				inspector->set_filter(filter);
			}
#endif

			//
			// Launch the capture
			//
			bool open_success = true;

			if(infiles.size() != 0)
			{
				initialize_chisels();

				//
				// We have a file to open
				//
				inspector->open(infiles[j]);
			}
			else
			{
				if(j > 0)
				{
					break;
				}

				initialize_chisels();

				//
				// No file to open, this is a live capture
				//
#if defined(HAS_CAPTURE)
				if(print_progress)
				{
					fprintf(stderr, "the -P flag cannot be used with live captures.\n");
					res.m_res = EXIT_FAILURE;
					goto exit;
				}

				try
				{
					inspector->open("");
				}
				catch(sinsp_exception e)
				{
					open_success = false;
				}
#else
				//
				// Starting live capture
				// If this fails on Windows and OSX, don't try with any driver
				//
				inspector->open("");
#endif

				//
				// Starting the live capture failed, try to load the driver with
				// modprobe.
				//
				if(!open_success)
				{
					open_success = true;

					system("modprobe sysdig-probe > /dev/null 2> /dev/null");

					inspector->open("");
				}
			}

			if(snaplen != 0)
			{
				inspector->set_snaplen(snaplen);
			}

			duration = ((double)clock()) / CLOCKS_PER_SEC;

			if(outfile != "")
			{
				inspector->setup_cycle_writer(outfile, rollover_mb, duration_seconds, file_limit, do_cycle, compress);
				inspector->autodump_next_file();
			}

			//
			// Notify the chisels that the capture is starting
			//
			chisels_on_capture_start();

			cinfo = do_inspect(inspector,
				cnt,
				quiet,
				jflag,
				print_progress,
				display_filter,
				summary_table,
				&formatter);

			duration = ((double)clock()) / CLOCKS_PER_SEC - duration;

			scap_stats cstats;
			inspector->get_capture_stats(&cstats);

			if(verbose)
			{
				fprintf(stderr, "Driver Events:%" PRIu64 "\nDriver Drops:%" PRIu64 "\n",
					cstats.n_evts,
					cstats.n_drops);

				fprintf(stderr, "Elapsed time: %.3lf, Captured Events: %" PRIu64 ", %.2lf eps\n",
					duration,
					cinfo.m_nevts,
					(double)cinfo.m_nevts / duration);
			}

			//
			// Done. Close the capture.
			//
			inspector->close();

		}
	}
	catch(sinsp_capture_interrupt_exception&)
	{
		handle_end_of_file(print_progress);
	}
	catch(sinsp_exception& e)
	{
		cerr << e.what() << endl;
		handle_end_of_file(print_progress);
		res.m_res = EXIT_FAILURE;
	}
	catch(...)
	{
		handle_end_of_file(print_progress);
		res.m_res = EXIT_FAILURE;
	}

exit:
	//
	// If any of the chisels is requesting another run,
	//
	for(vector<sinsp_chisel*>::iterator it = g_chisels.begin();
		it != g_chisels.end(); ++it)
	{
		string na;
		if((*it)->get_nextrun_args(&na))
		{
			res.m_next_run_args = sinsp_split(na, ' ');
		}
	}

	//
	// If there's a summary table, sort and print it
	//
	if(summary_table != NULL)
	{
		print_summary_table(inspector, summary_table, 100);
	}

	//
	// Free all the stuff that was allocated
	//
	free_chisels();

	if(inspector)
	{
		delete inspector;
	}

	if(display_filter)
	{
		delete display_filter;
	}

	return res;
}
Esempio n. 15
0
void 
process_command(int descr, dbref player, char *command)
{
    char   *arg1;
    char   *arg2;
    char   *full_command, *commandline=command, *commandstuff;
    char   *p;                  /* utility */
    char    pbuf[BUFFER_LEN];
    char    xbuf[BUFFER_LEN];
    char    ybuf[BUFFER_LEN];
    const char *path;
    struct frame *tmpfr;

    if (command == 0)
	abort();

    /* robustify player */
    if (player < 0 || player >= db_top ||
	    (Typeof(player) != TYPE_PLAYER && Typeof(player) != TYPE_THING)) {
	log_status("process_command: bad player %d\n", player);
	return;
    }

    if ((tp_log_commands || (tp_log_guests && Guest(OWNER(player)))) &&
	    (!(FLAGS(player)&(INTERACTIVE | READMODE)))) {
	log_command("%s%s%s%s(%d) in %s(%d):%s %s\n",
		    Mage(OWNER(player)) ? "WIZ: " : "",
		    (Typeof(player) != TYPE_PLAYER) ? NAME(player) : "",
		    (Typeof(player) != TYPE_PLAYER) ? " by " : "",
		    NAME(OWNER(player)), (int) player,
		    NAME(DBFETCH(player)->location),
		    (int) DBFETCH(player)->location,
		    (FLAGS(player) & INTERACTIVE) ?
		    " [interactive]" : " ", command);
    }

    if (FLAGS(player) & INTERACTIVE) {
	interactive(descr, player, command);
	return;
    }
    /* eat leading whitespace */
    while (*command && isspace(*command))
	command++;

    commandstuff = command;
    /* check for single-character commands */
    if (*command == SAY_TOKEN || *command == '\'') {
	sprintf(pbuf, "say %s", command + 1);
	command = &pbuf[0];
    } else if (*command == POSE_TOKEN || *command == ';') {
	sprintf(pbuf, "pose %s", command + 1);
	command = &pbuf[0];
    } else if ((*command == '|' || (*commandstuff++ == '\\' && *commandstuff == '\\') ) && can_move(descr, player, "spoof", 0)) {
      if(*command = '\\')
         sprintf(pbuf, "spoof %s", command + 2);
      else
         sprintf(pbuf, "spoof %s", command + 1);
      command = &pbuf[0];
    }

    /* if player is a wizard, and uses overide token to start line...*/
    /* ... then do NOT run actions, but run the command they specify. */
    if (!strcmp(command, WHO_COMMAND)) {
       char xxbuf[BUFFER_LEN];

       strcpy(xxbuf, "@");
       strcat(xxbuf, WHO_COMMAND);
       strcat(xxbuf, " ");
       strcat(xxbuf, command + sizeof(WHO_COMMAND) - 1);
       if (can_move(descr, player, xxbuf, 5)) {
          do_move(descr, player, xxbuf, 5);
       } else {
          pdump_who_users(descr, command + sizeof(WHO_COMMAND) - 1);
       }
       return;
    }

    if (!( *command == OVERIDE_TOKEN && TMage(player) )) {
	if( can_move(descr, player, command, 0) ) {
	    do_move(descr, player, command, 0); /* command is exact match for exit */
	    *match_args = 0;
	    *match_cmdname = 0; 
	    return;
	}
    }

	if (*command == OVERIDE_TOKEN && TMage(player))
	    command++;

	full_command = strcpy(xbuf, command);
	for (; *full_command && !isspace(*full_command); full_command++);
	if (*full_command)
	    full_command++;

	/* find arg1 -- move over command word */
	command = strcpy(ybuf, command);
	for (arg1 = command; *arg1 && !isspace(*arg1); arg1++);
	/* truncate command */
	if (*arg1)
	    *arg1++ = '\0';

	/* remember command for programs */
	strcpy(match_cmdname, command);

	/* move over spaces */
	while (*arg1 && isspace(*arg1))
	    arg1++;

	/* find end of arg1, start of arg2 */
	for (arg2 = arg1; *arg2 && *arg2 != ARG_DELIMITER; arg2++);

	/* truncate arg1 */
	for (p = arg2 - 1; p >= arg1 && isspace(*p); p--)
	    *p = '\0';

	/* go past delimiter if present */
	if (*arg2)
	    *arg2++ = '\0';
	while (*arg2 && isspace(*arg2))
	    arg2++;

	strcpy(match_cmdname, command);
	strcpy(match_args, full_command);

	switch (command[0]) {
	    case '@':
		switch (command[1]) {
		    case 'a':
		    case 'A':
			/* @action, @attach */
			switch (command[2]) {
			    case 'c':
			    case 'C':
				Matched("@action");
				do_action(descr, player, arg1, arg2);
				break;
			    case 'r':
			    case 'R':
				if (string_compare(command, "@armageddon"))
				    goto bad;
				do_armageddon(player, full_command);
				break;
			    case 't':
			    case 'T':
				Matched("@attach");
				do_attach(descr, player, arg1, arg2);
				break;
                      case 'n':
                      case 'N':
                        Matched("@ansidescribe");
                        do_ansidescribe(descr, player, arg1, arg2);
                        break;
			    default:
				goto bad;
			}
			break;
		    case 'b':
		    case 'B':
			Matched("@boot");
			do_boot(player, arg1);
			break;
		    case 'c':
		    case 'C':
			/* chown, contents, create */
			switch (command[2]) {
			    case 'h':
			    case 'H':
				switch (command[3]) {
				    case 'l':
				    case 'L':
					Matched("@chlock");
					do_chlock(descr, player, arg1, arg2);
					break;
				    case 'o':
				    case 'O':
					Matched("@chown");
					do_chown(descr, player, arg1, arg2);
					break;
				    default:
					goto bad;
				}
				break;
			    case 'o':
			    case 'O':
				switch (command[4]) {
				    case 'l':
				    case 'L':
					Matched("@conlock");
					do_conlock(descr, player, arg1, arg2);
					break;
				    case 't':
				    case 'T':
					Matched("@contents");
					do_contents(descr, player, arg1, arg2);
					break;
				    default:
					goto bad;
				}
				break;
			    case 'r':
			    case 'R':
				if (string_compare(command, "@credits")) {
				    Matched("@create");
				    do_create(player, arg1, arg2);
				} else {
				    do_credits(player);
				}
				break;
			    default:
				goto bad;
			}
			break;
		    case 'd':
		    case 'D':
			/* describe, dequeue, dig, or dump */
			switch (command[2]) {
			    case 'b':
			    case 'B':
				Matched("@dbginfo");
				do_serverdebug(descr, player, arg1, arg2);
				break;
			    case 'e':
			    case 'E':
#ifdef DELTADUMPS
				if(command[3] == 'l' || command[3] == 'L') {
				    Matched("@delta");
				    do_delta(player);
				} else
#endif
				{
                          if( (command[3] == 's' || command[3] == 'S') &&
                              (command[4] == 't' || command[4] == 'T') ) {
                            Matched("@destroy");
 				    do_recycle(descr, player, arg1);
                          } else {
				    Matched("@describe");
				    do_describe(descr, player, arg1, arg2);
                          }
				}
				break;
			    case 'i':
			    case 'I':
				Matched("@dig");
				do_dig(descr, player, arg1, arg2);
				break;
#ifdef DELTADUMPS
			    case 'l':
			    case 'L':
				Matched("@dlt");
				do_delta(player);
				break;
#endif
			    case 'o':
			    case 'O':
				Matched("@doing");
				if (!tp_who_doing) goto bad;
				do_doing(descr, player, arg1, arg2);
				break;
			    case 'r':
			    case 'R':
				Matched("@drop");
				do_drop_message(descr, player, arg1, arg2);
				break;
			    case 'u':
			    case 'U':
				Matched("@dump");
				do_dump(player, full_command);
				break;
			    default:
				goto bad;
			}
			break;
		    case 'e':
		    case 'E':
			switch (command[2]) {
			    case 'd':
			    case 'D':
				Matched("@edit");
				do_edit(descr, player, arg1);
				break;
			    case 'n':
			    case 'N':
				Matched("@entrances");
				do_entrances(descr, player, arg1, arg2);
				break;
			    case 'x':
			    case 'X':
				Matched("@examine");
				sane_dump_object(player, arg1);
				break;
			    default:
				goto bad;
			}
			break;
		    case 'f':
		    case 'F':
			/* fail, find, force, or frob */
			switch (command[2]) {
			    case 'a':
			    case 'A':
				Matched("@fail");
				do_fail(descr, player, arg1, arg2);
				break;
			    case 'i':
			    case 'I':
				if(command[3] == 'x' || command[3] == 'X') {
				    Matched("@fixwizbits");
				    do_fixw(player, full_command);
				} else {
				    Matched("@find");
				    do_find(player, arg1, arg2);
				}
				break;
			    case 'l':
			    case 'L':
				Matched("@flock");
				do_flock(descr, player, arg1, arg2);
				break;
			    case 'o':
			    case 'O':
				Matched("@force");
				do_force(descr, player, arg1, arg2);
				break;
			    case 'r':
			    case 'R':
				if (string_compare(command, "@frob"))
				    goto bad;
				do_frob(descr, player, arg1, arg2);
				break;
			    default:
				goto bad;
			}
			break;
		    case 'h':
		    case 'H':
                  switch (command[2]) {
                     case 'T':
                     case 't':
                        Matched("@htmldescribe");
                        do_htmldescribe(descr, player, arg1, arg2);
                        break;
                     default:
 			      Matched("@hopper");
			      do_hopper(player, arg1);
                        break;
                  }
			break;
		    case 'i':
		    case 'I':
                  switch(command[2]) {
                     case 'h':
                     case 'H':
   	   		      Matched("@ihtmldescribe");
			      do_ihtmldescribe(descr, player, arg1, arg2);
			      break;
                     case 'a':
                     case 'A':
                        Matched("@iansidescribe");
                        do_iansidescribe(descr, player, arg1, arg2);
                        break;
                     default:
   			      Matched("@idescribe");
			      do_idescribe(descr, player, arg1, arg2);
			      break;
                  }
                  break;
		    case 'k':
		    case 'K':
			Matched("@kill");
			do_dequeue(descr, player, arg1);
			break;
		    case 'l':
		    case 'L':
			/* lock or link */
			switch (command[2]) {
			    case 'i':
			    case 'I':
				switch (command[3]) {
				    case 'n':
				    case 'N':
					Matched("@link");
					do_link(descr, player, arg1, arg2);
					break;
				    case 's':
				    case 'S':
					Matched("@list");
					match_and_list(descr, player, arg1, arg2, 1);
					break;
				    default:
					goto bad;
				}
				break;
			    case 'o':
			    case 'O':
				Matched("@lock");
				do_lock(descr, player, arg1, arg2);
				break;
			    default:
				goto bad;
			}
			break;
		    case 'm':
		    case 'M':
			switch (command[2]) {
			    case 'e':
			    case 'E':
				Matched("@memory");
				do_memory(player);
				break;
			    case 'c':
			    case 'C':
				switch (command[4]) {
				   case '2':
				     Matched("@mcp2muf");
				     match_and_list(descr, player, arg1, arg2, 0);
				     break;
				   default:
				     Matched("@mcp");
				     do_prog(descr, player, arg1, 1);
				     break;
				}
                     default:
                        goto bad;
			}
			break;
		    case 'n':
		    case 'N':
			/* @name or @newpassword */
			switch (command[2]) {
			    case 'a':
			    case 'A':
				Matched("@name");
				do_name(descr, player, arg1, arg2);
				break;
			    case 'e':
			    case 'E':
				if (string_compare(command, "@newpassword"))
				    goto bad;
				do_newpassword(player, arg1, arg2);
				break;
			    default:
				goto bad;
			}
			break;
		    case 'o':
		    case 'O':
			switch (command[2]) {
			    case 'd':
			    case 'D':
				Matched("@odrop");
				do_odrop(descr, player, arg1, arg2);
				break;
			    case 'e':
			    case 'E':
				Matched("@oecho");
				do_oecho(descr, player, arg1, arg2);
				break;
			    case 'f':
			    case 'F':
				Matched("@ofail");
				do_ofail(descr, player, arg1, arg2);
				break;
			    case 'p':
			    case 'P':
				Matched("@open");
				do_open(descr, player, arg1, arg2);
				break;
			    case 's':
			    case 'S':
				Matched("@osuccess");
				do_osuccess(descr, player, arg1, arg2);
				break;
			    case 'w':
			    case 'W':
				Matched("@owned");
				do_owned(player, arg1, arg2);
				break;
			    default:
				goto bad;
			}
			break;
		    case 'p':
		    case 'P':
			switch (command[2]) {
			    case 'a':
			    case 'A':
				Matched("@password");
				do_password(player, arg1, arg2);
				break;
			    case 'c':
			    case 'C':
				Matched("@pcreate");
				do_pcreate(player, arg1, arg2);
				break;
			    case 'e':
			    case 'E':
				Matched("@pecho");
				do_pecho(descr, player, arg1, arg2);
				break;
			    case 'r':
			    case 'R':
				if (string_prefix("@program", command)) {
				    do_prog(descr, player, arg1, 0);
				    break;
				} else if (string_prefix("@proginfo", command)) {
				    do_proginfo(player, arg1);
				    break;
				} else {
				    Matched("@propset");
				    do_propset(descr, player, arg1, arg2);
				    break;
				}
			    case 's':
			    case 'S':
				Matched("@ps");
				list_events(player);
				break;
			    case 'u':
			    case 'U':
				Matched("@purge");
				do_purge(descr, player, arg1, arg2);
				break;
			    default:
				goto bad;
			}
			break;
		    case 'r':
		    case 'R':
			switch (command[3]) {
			    case 'c':
			    case 'C':
				Matched("@recycle");
				do_recycle(descr, player, arg1);
				break;
			    case 's':
			    case 'S':
				if (!string_compare(command, "@restart")) {
				    do_restart(player, full_command);
				} else if (!string_compare(command, "@restrict")) {
				    do_restrict(player, arg1);
				} else {
				    goto bad;
				}
				break;
			    default:
				goto bad;
			}
			break;
		    case 's':
		    case 'S':
			/* set, shutdown, success */
			switch (command[2]) {
			    case 'a':
			    case 'A':
				if (!string_compare(command, "@sanity")) {
				    sanity(player);
				} else if (!string_compare(command, "@sanchange")) {
				    sanechange(player, full_command);
				} else if (!string_compare(command, "@sanfix")) {
				    sanfix(player);
				} else {
				    goto bad;
				}
				break;
			    case 'e':
			    case 'E':
				Matched("@set");
				do_set(descr, player, arg1, arg2);
				break;
			    case 'h':
			    case 'H':
				if (!string_compare(command, "@shout")) {
				    do_wall(player, full_command);
				    break;
				}
				if (string_compare(command, "@shutdown"))
				    goto bad;
				do_shutdown(player, arg1);
				break;
			    case 't':
			    case 'T':
				Matched("@stats");
				do_stats(player, arg1);
				break;
			    case 'u':
			    case 'U':
				Matched("@success");
				do_success(descr, player, arg1, arg2);
				break;
			    case 'w':
			    case 'W':
				Matched("@sweep");
				do_sweep(descr, player, arg1);
				break;
			    default:
				goto bad;
			}
			break;
		    case 't':
		    case 'T':
			switch (command[2]) {
			    case 'e':
			    case 'E':
				Matched("@teleport");
				do_teleport(descr, player, arg1, arg2);
				break;
                      case 'o':
                      case 'O':
				if (string_compare(command, "@toad"))
				    goto bad;
				do_frob(descr, player, arg1, arg2);
				break;
			    case 'r':
			    case 'R':
				Matched("@trace");
				do_trace(descr, player, arg1, atoi(arg2));
				break;
			    case 'u':
			    case 'U':
				Matched("@tune");
				do_tune(player, arg1, arg2);
				break;
			    default:
				goto bad;
			}
			break;
		    case 'u':
		    case 'U':
			switch (command[2]) {
			    case 'N':
			    case 'n':
				if (string_prefix(command, "@unlink")) {
				    do_unlink(descr, player, arg1);
				} else if (string_prefix(command, "@unlock")) {
				    do_unlock(descr, player, arg1);
				} else if (string_prefix(command, "@uncompile")) {
				    do_uncompile(player);
				} else {
				    goto bad;
				}
				break;

#ifndef NO_USAGE_COMMAND
			    case 'S':
			    case 's':
				Matched("@usage");
				do_usage(player);
				break;
#endif

			    default:
				goto bad;
				break;
			}
			break;
		    case 'v':
		    case 'V':
			Matched("@version");
			anotify_nolisten2(player, CRIMSON "ProtoMUCK " PROTOBASE PURPLE " (" RED VERSION WHITE " -- " AQUA NEONVER PURPLE ")" );
			break;
		    case 'w':
		    case 'W':
			if (string_compare(command, "@wall"))
			    goto bad;
			do_wall(player, full_command);
			break;
		    default:
			goto bad;
		}
		break;
          case '&':
            do_mush_set(descr, player, arg1, arg2, command);
            break;
	    case 'd':
	    case 'D':
		switch (command[1]) {
		    case 'b':
		    case 'B':
			Matched("dboot");
			do_dboot(player, arg1);
			break;
		    case 'i':
		    case 'I':
			Matched("dinfo");
			do_dinfo(player, arg1);
			break;
		    case 'r':
		    case 'R':
			Matched("drop");
			do_drop(descr, player, arg1, arg2);
			break;
		    case 'w':
		    case 'W':
			Matched("dwall");
			do_dwall(player, arg1, arg2);
			break;
		    default:
			goto bad;
		}
		break;
	    case 'e':
	    case 'E':
		switch (command[1]) {
		    case 'm':
		    case 'M':
			Matched("emote");
			do_pose(descr, player, full_command);
			break;
		    case 'x':
		    case 'X':
		    case '\0':
			Matched("examine");
			do_examine(descr, player, arg1, arg2);
			break;
		    default:
			goto bad;
		}
		break;
	    case 'g':
	    case 'G':
		/* get, give, go, or gripe */
		switch (command[1]) {
		    case 'e':
		    case 'E':
			Matched("get");
			do_get(descr, player, arg1, arg2);
			break;
		    case 'i':
		    case 'I':
			Matched("give");
			do_give(descr, player, arg1, atoi(arg2));
			break;
		    case 'o':
		    case 'O':
			Matched("goto");
			do_move(descr, player, arg1, 0);
			break;
		    case 'r':
		    case 'R':
			if(command[2]=='i' || command[2]=='I') {
				if (string_compare(command, "gripe"))
				    goto bad;
				do_gripe(player, full_command);
				break;
			}
		    default:
			goto bad;
		}
		break;
	    case 'h':
	    case 'H':
		switch (command[1]) {
		    case 'a':
		    case 'A':
			Matched("hand");
			do_drop(descr, player, arg1, arg2);
			break;
		    case 'e':
		    case 'E':
			Matched("help");
			do_help(player, arg1, arg2);
			break;
		    default:
			goto bad;
		}
		break;
	    case 'i':
	    case 'I':
		if (string_compare(command, "info")) {
		    Matched("inventory");
		    do_inventory(player);
		} else {
		    do_info(player, arg1, arg2);
		}
		break;
	    case 'l':
	    case 'L':
		if (string_prefix("look", command)) {
		    do_look_at(descr, player, arg1, arg2);
		    break;
		} else {
		    Matched("leave");
		    do_leave(descr, player);
		    break;
		}
	    case 'm':
	    case 'M':
		if (string_prefix(command, "move")) {
		    do_move(descr, player, arg1, 0);
		    break;
		} else if (!string_compare(command, "motd")) {
		    do_motd(player, full_command);
		    break;
		} else if (!string_compare(command, "mpi")) {
		    do_mpihelp(player, arg1, arg2);
		    break;
		} else {
		    if (string_compare(command, "man"))
			goto bad;
		    do_man(player, arg1, arg2);
		}
		break;
	    case 'n':
	    case 'N':
		/* news */
		Matched("news");
		do_news(player, arg1, arg2);
		break;
	    case 'p':
	    case 'P':
		switch (command[1]) {
		    case 'a':
		    case 'A':
		    case '\0':
			Matched("page");
			do_page(descr, player, arg1, arg2);
			break;
		    case 'o':
		    case 'O':
			Matched("pose");
			do_pose(descr, player, full_command);
			break;
		    case 'u':
		    case 'U':
			Matched("put");
			do_drop(descr, player, arg1, arg2);
			break;
		    default:
			goto bad;
		}
		break;
	    case 'r':
	    case 'R':
		switch (command[1]) {
		    case 'e':
		    case 'E':
			if(command[2] == 'q' || command[2] == 'Q'){
			    Matched("request");
			    request(player, NULL, commandline);
			} else {
			    Matched("read");    /* undocumented alias for look */
			    do_look_at(descr, player, arg1, arg2);
			}
			break;
		    default:
			goto bad;
		}
		break;
	    case 's':
	    case 'S':
		/* say, "score" */
		switch (command[1]) {
		    case 'a':
		    case 'A':
			Matched("say");
			do_say(descr, player, full_command);
			break;
		    case 'c':
		    case 'C':
		    case '\0':
			if( command[1] &&
			    (command[2] == 'a' || command[2] == 'A' )) {
			    Matched("scan");
			    do_sweep(descr, player, arg1);
			} else {
			    Matched("score");
			    do_score(player, 1);
			}
			break;
		    default:
			goto bad;
		}
		break;
	    case 't':
	    case 'T':
		switch (command[1]) {
		    case 'a':
		    case 'A':
			Matched("take");
			do_get(descr, player, arg1, arg2);
			break;
		    case 'h':
		    case 'H':
			Matched("throw");
			do_drop(descr, player, arg1, arg2);
			break;
		    default:
			goto bad;
		}
		break;
	    case 'w':
	    case 'W':
		switch (command[1]){
		    case 'c':
		    case 'C':
			Matched("wc");
			do_wizchat(player, full_command);
			break;
		    case 'i':
		    case 'I':
			Matched("wizchat");
			do_wizchat(player, arg1);
			break;
		    case 'h':
		    case 'H':
		    case '\0':
			Matched("whisper");
			do_whisper(descr, player, arg1, arg2);
			break;
		    default:
			goto bad;
		}
		break;
	    default:
	bad:
 		if ( Typeof(tp_huh_command) == TYPE_PROGRAM && !(player == -1)) {
			tmpfr = interp(descr, player, DBFETCH(player)->location, tp_huh_command, (dbref)-4, FOREGROUND, STD_REGUID);
			if (!tmpfr)
				goto bad2;
			(void) interp_loop(player, tp_huh_command, tmpfr, 0);
            } else {
   		   bad2:
                  anotify_fmt(player, CINFO "%s",tp_huh_mesg);
			if (tp_log_failed_commands && !controls(player, DBFETCH(player)->location)) {
		    		log_status("HUH from %s(%d) in %s(%d)[%s]: %s %s\n", NAME(player), player,
                        NAME(DBFETCH(player)->location),
			      DBFETCH(player)->location,
			      NAME(OWNER(DBFETCH(player)->location)), command,
			      full_command);
			}
		}
		break;
	}

}