LLDir_Solaris::LLDir_Solaris()
{
	mDirDelimiter = "/";
	mCurrentDirIndex = -1;
	mCurrentDirCount = -1;
	mDirp = NULL;

	char tmp_str[LL_MAX_PATH];	/* Flawfinder: ignore */ 
	if (getcwd(tmp_str, LL_MAX_PATH) == NULL)
	{
		strcpy(tmp_str, "/tmp");
		llwarns << "Could not get current directory; changing to "
				<< tmp_str << llendl;
		if (chdir(tmp_str) == -1)
		{
			llerrs << "Could not change directory to " << tmp_str << llendl;
		}
	}

	mExecutableFilename = "";
	mExecutablePathAndName = "";
	mExecutableDir = strdup(tmp_str);
	mWorkingDir = strdup(tmp_str);
	mAppRODataDir = strdup(tmp_str);
	mOSUserDir = getCurrentUserHome(tmp_str);
	mOSUserAppDir = "";
	mLindenUserDir = tmp_str;

	char path [LL_MAX_PATH];	/* Flawfinder: ignore */ 

	sprintf(path, "/proc/%d/psinfo", (int)getpid());
	int proc_fd = -1;
	if((proc_fd = open(path, O_RDONLY)) == -1){
		llwarns << "unable to open " << path << llendl;
		return;
	}
	psinfo_t proc_psinfo;
	if(read(proc_fd, &proc_psinfo, sizeof(psinfo_t)) != sizeof(psinfo_t)){
		llwarns << "Unable to read " << path << llendl;
		close(proc_fd);
		return;
	}

	close(proc_fd);

	mExecutableFilename = strdup(proc_psinfo.pr_fname);
	llinfos << "mExecutableFilename = [" << mExecutableFilename << "]" << llendl;

	sprintf(path, "/proc/%d/path/a.out", (int)getpid());

	char execpath[LL_MAX_PATH];
	if(readlink(path, execpath, LL_MAX_PATH) == -1){
		llwarns << "Unable to read link from " << path << llendl;
		return;
	}

	char *p = execpath;			// nuke trash in link, if any exists
	int i = 0;
	while(*p != NULL && ++i < LL_MAX_PATH && isprint((int)(*p++)));
	*p = NULL;

	mExecutablePathAndName = strdup(execpath);
	llinfos << "mExecutablePathAndName = [" << mExecutablePathAndName << "]" << llendl;

	//NOTE: Why force people to cd into the package directory?
	//      Look for INWORLDZ env variable and use it, if set.

	char *dcf = getenv("INWORLDZ");
	if(dcf != NULL){
		(void)strcpy(path, dcf);
		(void)strcat(path, "/bin");	//NOTE:  make sure we point at the bin
		mExecutableDir = strdup(path);
	}else{
			// plunk a null at last '/' to get exec dir
		char *s = execpath + strlen(execpath) -1;
		while(*s != '/' && s != execpath){
			--s;
		}
	
		if(s != execpath){
			*s = (char)NULL;
	
			mExecutableDir = strdup(execpath);
			llinfos << "mExecutableDir = [" << mExecutableDir << "]" << llendl;
		}
	}
	
	mLLPluginDir = mExecutableDir + mDirDelimiter + "llplugin";

	// *TODO: don't use /tmp, use $HOME/.secondlife/tmp or something.
	mTempDir = "/tmp";
}
Example #2
0
static char printable_char(int c)
{
	return isascii(c) && isprint(c) ? c : '?';
}
Example #3
0
static ssize_t
qp_write(Sfio_t* sp, const void* buf, size_t n, Sfdisc_t* disc)
{
	register State_t*	state = (State_t*)CODEX(disc)->data;
	register unsigned char*	s;
	register unsigned char*	e;
	register int		c;
	register int		col;

 again:
	if (state->pp)
	{
		s = state->prv;
		e = state->pp;
		state->col = 0;
	}
	else
	{
		s = (unsigned char*)buf;
		e = s + n;
		col = state->col;
	}
	for (;;)
	{
		if (s >= e)
		{
			if (state->pp)
			{
				state->pp = 0;
				state->col = col;
				goto again;
			}
			break;
		}
		c = *s++;
		if (!col++)
		{
			if (c == 'F')
			{
				if ((e - s) < 4)
				{
					s--;
					col--;
					state->pp = state->prv;
					for (c = 0; c < (e - s); ++c)
						*state->pp++ = s[c];
					break;
				}
				else if (s[0] == 'r' && s[1] == 'o' && s[2] == 'm' && s[3] == ' ')
					goto quote;
			}
			else if (c == '.')
			{
				if ((e - s) < 1)
				{
					s--;
					col--;
					state->pp = state->prv;
					*state->pp++ = c;
					break;
				}
				else if (s[0] == '\r' || s[0] == '\n')
					goto quote;
			}
		}
		if (c == '\n')
		{
			col = 0;
			PUTCHAR(state, c);
			continue;
		}
		else if (col >= (LINE - 4))
		{
			col = 0;
			PUTCHAR(state, '=');
			PUTCHAR(state, '\n');
		}
		if (c == ' ' || c == '\t')
		{
			if ((e - s) < 1)
			{
				s--;
				col--;
				state->pp = state->prv;
				*state->pp++ = c;
				break;
			}
			else if (s[0] == '\r' || s[0] == '\n')
				goto quote;
			else
			{
				if (c == '\t')
					col |= 7;
				PUTCHAR(state, c);
				continue;
			}
		}
#if CC_NATIVE == CC_ASCII
		else if (c >= 0x21 && c <= 0x7e && c != '=')
#else
		else if (isprint(c) && !iscntrl(c) && c != '=')
#endif
		{
			PUTCHAR(state, c);
			continue;
		}
	quote:
		col += 2;
		PUTCHAR(state, '=');
		PUTCHAR(state, hex[(c >> 4) & 0xF]);
		PUTCHAR(state, hex[c & 0xF]);
	}
	state->col = col;
	return n;
}
Example #4
0
static bool dumpOSCmsg(int inSize, char* inData, bool skipStatus = false)
{
	int size;
	const char *data;

	if (inData[0]) {
		const char *addr = inData;
		if (skipStatus) {
			if (strcmp(addr, "/status") == 0 || strcmp(addr, "status") == 0) // skip /status messages
				return false; // nothing has been printed
		}

		data = OSCstrskip(inData);
		size = inSize - (data - inData);
		scprintf("[ \"%s\",", addr);
	} else {
		scprintf("[ %d,", OSCint(inData));
		data = inData + 4;
		size = inSize - 4;
	}

	sc_msg_iter msg(size, data);

	while (msg.remain())
	{
		char c = msg.nextTag('i');
		switch(c)
		{
		case 'i' :
			scprintf(" %d", msg.geti());
			break;
		case 'f' :
			scprintf(" %g", msg.getf());
			break;
		case 'd' :
			scprintf(" %g", msg.getd());
			break;
		case 's' :
			scprintf(" \"%s\"", msg.gets());
			break;
		case '[' :
			scprintf(" [");
			msg.count ++;
			break;
		case ']' :
			scprintf(" ]");
			msg.count ++;
			break;
		case 'b' :
			scprintf(" DATA[%zu]", msg.getbsize());
			msg.skipb();
			break;
		case 'm' : {
			char midi [4];
			msg.getb (midi, 4);
			scprintf(" MIDI[0x%02x 0x%02x 0x%02x 0x%02x]", midi[0], midi[1], midi[2], midi[3]);
			break;
		}
		case 'c' :
			scprintf(" %c", (char)msg.geti());
			break;
		case 't' :
			scprintf(" %" PRId64 "", msg.gett());
			break;
		case 'T' :
			scprintf(" true");
			msg.count ++;
			break;
		case 'F' :
			scprintf(" false");
			msg.count ++;
			break;
		case 'I' :
			scprintf(" infinitum");
			msg.count ++;
			break;
		case 'N' :
			scprintf(" nil");
			msg.count ++;
			break;
		default :
			scprintf(" !unknown tag '%c' 0x%02x !", isprint(c)?c:'?', (unsigned char)c & 255);
			goto leave;
		}
		if (msg.remain() && (c!= '[')) scprintf(",");
	}
leave:
	scprintf(" ]");
	return true;  // something has been printed
}
Example #5
0
/*
 * Dumps data in Hex+ASCII format as:
 *
 * 00000000: 01 01 43 20 30 70 72 6F 70 65 72 74 69 65 73 20  |..C 0properties |
 *
 */
void sniffer_print_hexdump(FILE *file, guint8 *data, guint32 len,
			   guint8 indent, bool print_len)
{
	guint8 digits;
	guint32 offset;
	guint32 total;
	guint32 output_len;
	gchar line[LINE_SIZE];
	gchar *hexa = NULL, *human = NULL;
	guint8 offset_len;
	guint8 human_offset;
	gchar *fmt;

	if (len == 0)
		return;

	offset = 0;
	digits = 0;
	total = 0;

	if (opts.snap_len && len > opts.snap_len)
		output_len = opts.snap_len;
	else
		output_len = len;

	if (output_len > 0xFFFF) {
		offset_len = 8;
		human_offset = HUMAN_READABLE_OFFSET + 4;
		fmt = "%08X: ";
	} else {
		offset_len = 4;
		human_offset = HUMAN_READABLE_OFFSET;
		fmt = "%04X: ";
	}

	if (print_len) {
		if (indent)
			fprintf(file, "%*c", indent, ' ');

		fprintf(file, "Total length: %u bytes\n", len);
	}

	while (total < output_len) {
		if (digits == 0) {
			memset(line, ' ', human_offset);

			sprintf(line, fmt, offset);

			offset += 16;

			hexa = line + offset_len + 2;

			human = line + human_offset;
			*human++ = '|';
		}

		sprintf(hexa, "%02hhX ", data[total]);
		*human++ = isprint((int)data[total]) ? (char)data[total] : '.';
		hexa += 3;

		if (++digits >= 16) {
			*hexa = ' ';
			strcpy(human, "|");
			if (indent)
				fprintf(file, "%*c", indent, ' ');
			fprintf(file, "%s\n", line);

			digits = 0;
		}

		total++;
	}

	if ((output_len & 0xF) != 0) {
		*hexa = ' ';
		strcpy(human, "|");
		if (indent)
			fprintf(file, "%*c", indent, ' ');
		fprintf(file, "%s\n", line);
	}

	if (output_len != len) {
		if (indent)
			fprintf(file, "%*c", indent, ' ');
		fprintf(file, "--- truncated ---\n");
	}
}
Example #6
0
int
main(int argc, char **argv)
{
	int c, column;
	int n;
	int rval;

	setlocale(LC_CTYPE, "");

	/* handle obsolete syntax */
	while (argc > 1 && argv[1][0] == '-' &&
	    isdigit((unsigned char)argv[1][1])) {
		getstops(&argv[1][1]);
		argc--; argv++;
	}

	while ((c = getopt (argc, argv, "t:")) != -1) {
		switch (c) {
		case 't':
			getstops(optarg);
			break;
		case '?':
		default:
			usage();
			/* NOTREACHED */
		}
	}
	argc -= optind;
	argv += optind;

	rval = 0;
	do {
		if (argc > 0) {
			if (freopen(argv[0], "r", stdin) == NULL) {
				warn("%s", argv[0]);
				rval = 1;
				argc--, argv++;
				continue;
			}
			argc--, argv++;
		}
		column = 0;
		while ((c = getchar()) != EOF) {
			switch (c) {
			case '\t':
				if (nstops == 0) {
					do {
						putchar(' ');
						column++;
					} while (column & 07);
					continue;
				}
				if (nstops == 1) {
					do {
						putchar(' ');
						column++;
					} while (((column - 1) % tabstops[0]) != (tabstops[0] - 1));
					continue;
				}
				for (n = 0; n < nstops; n++)
					if (tabstops[n] > column)
						break;
				if (n == nstops) {
					putchar(' ');
					column++;
					continue;
				}
				while (column < tabstops[n]) {
					putchar(' ');
					column++;
				}
				continue;

			case '\b':
				if (column)
					column--;
				putchar('\b');
				continue;

			default:
				putchar(c);
				if (isprint(c))
					column++;
				continue;

			case '\n':
				putchar(c);
				column = 0;
				continue;
			}
		}
	} while (argc > 0);
	exit(rval);
}
Example #7
0
/* options__process
 * A snippet from main() to get all the options sent via CLI, then verifies them.
 */
void options__process(int argc, char **argv) {
  /* Reset everything since there isn't an initialization function for Options structs. */
  /* Page Information */
  opts.page_directory = (char *)malloc(strlen("sample_data") + 1); strcpy(opts.page_directory, "sample_data");
  opts.page_count = 0;
  opts.page_limit = MAX_PAGE_LIMIT;
  opts.smallest_page = UINT16_MAX;
  opts.biggest_page = 0;
  opts.dataset_size = 0;
  opts.dataset_max = MAX_DATASET_MAX;
  /* Resource Control */
  opts.max_memory = 10 * 1024 * 1024;
  opts.fixed_ratio = -1;
  opts.workers = sysconf(_SC_NPROCESSORS_ONLN) > 0 ? (uint16_t)sysconf(_SC_NPROCESSORS_ONLN) : 1;
  opts.cpu_count = sysconf(_SC_NPROCESSORS_ONLN) > 0 ? (uint16_t)sysconf(_SC_NPROCESSORS_ONLN) : 1;
  /* Tyche Management */
  opts.duration = 5;
  opts.compressor_id = LZ4_COMPRESSOR_ID;
  opts.compressor_level = 1;
  opts.min_pages_retrieved = 5;
  opts.max_pages_retrieved = 5;
  opts.bias_percent = 1.0;
  opts.bias_aggregate = 1.0;
  opts.update_frequency = 0.0;
  opts.delete_frequency = 0.0;
  /* Run Test? */
  opts.test = NULL;
  opts.extended_test_options = NULL;
  /* Niceness Features */
  opts.quiet = 0;
  opts.verbosity = 0;

  /* Process everything passed from CLI now. */
  char *save_ptr = NULL;
  char *token = NULL;
  int c = 0;
  opterr = 0;
  while ((c = getopt(argc, argv, "b:B:c:Cd:D:f:hm:M:n:p:qt:U:w:X:v")) != -1) {
    switch (c) {
      case 'b':
        opts.dataset_max = (uint64_t)atoll(optarg);
        break;
      case 'B':
        token = strtok_r(optarg, ",", &save_ptr);
        if(token != NULL)
          opts.bias_percent = 1.0 * atof(token) / 100;
        token = strtok_r(NULL, ",", &save_ptr);
        if (token != NULL)
          opts.bias_aggregate = 1.0 * atof(token) / 100;
        break;
      case 'c':
        if(strcmp(optarg, "lz4") != 0 && strcmp(optarg, "zlib") != 0 && strcmp(optarg, "zstd"))
          show_error(E_BAD_CLI, "You must specify either 'lz4' or 'zlib' for compression (-c), not: %s", optarg);
        if(strcmp(optarg, "lz4") == 0)
          opts.compressor_id = LZ4_COMPRESSOR_ID;
        if(strcmp(optarg, "zlib") == 0)
          opts.compressor_id = ZLIB_COMPRESSOR_ID;
        if(strcmp(optarg, "zstd") == 0)
          opts.compressor_id = ZSTD_COMPRESSOR_ID;
        break;
      case 'C':
        opts.compressor_id = NO_COMPRESSOR_ID;
        break;
      case 'd':
        opts.duration = (uint16_t)atoi(optarg);
        if (atoi(optarg) > MAX_DURATION)
          opts.duration = MAX_DURATION;
        break;
      case 'D':
        opts.delete_frequency = 1.0 * atof(optarg) / 100;
        break;
      case 'f':
        opts.fixed_ratio = (int8_t)atoi(optarg);
        break;
      case 'h':
        options__show_help();
        exit(E_OK);
        break;
      case 'm':
        opts.max_memory = (uint64_t)atoll(optarg);
        break;
      case 'M':
        token = strtok_r(optarg, ",", &save_ptr);
        if(token != NULL)
          opts.min_pages_retrieved = atoi(token);
        token = strtok_r(NULL, ",", &save_ptr);
        if (token != NULL)
          opts.max_pages_retrieved = atoi(token);
        break;
      case 'n':
        opts.page_limit = (uint32_t)atoll(optarg);
        break;
      case 'p':
        opts.page_directory = optarg;
        break;
      case 'q':
        opts.quiet = 1;
        break;
      case 't':
        if (opts.test != NULL)
          show_error(E_BAD_CLI, "You cannot specify the -t option more than once.");
        opts.test = optarg;
        break;
      case 'U':
        opts.update_frequency = 1.0 * atof(optarg) / 100;
        break;
      case 'w':
        opts.workers = (uint16_t)atoi(optarg);
        if (atoi(optarg) > MAX_WORKERS)
          opts.workers = MAX_WORKERS;
        break;
      case 'X':
        free(opts.extended_test_options);
        opts.extended_test_options = optarg;
        if(strcmp(opts.extended_test_options, "help") == 0) {
          options__show_extended_test_options();
          exit(E_OK);
        }
        break;
      case 'v':
        if(opts.verbosity >= MAX_VERBOSITY)
          show_error(E_BAD_CLI, "Verbosity is already at maximum value: %d", opts.verbosity);
        opts.verbosity++;
        break;
      case '?':
        options__show_help();
        if (optopt == 'b' || optopt == 'B' || optopt == 'c' || optopt == 'd' || optopt == 'D' || optopt == 'f' || optopt == 'm' || optopt == 'M' || optopt == 'n' || optopt == 'p' || optopt == 't' || optopt == 'U' || optopt == 'w' || optopt == 'X')
          show_error(E_BAD_CLI, "Option -%c requires an argument.", optopt);
        if (isprint (optopt))
          show_error(E_BAD_CLI, "Unknown option `-%c'.", optopt);
        show_error(E_BAD_CLI, "Unknown option character `\\x%x'.\n", optopt);
        break;
      default:
        options__show_help();
        exit(E_BAD_CLI);
    }
  }

  /* Pre-flight Checks */
  // -- A page directory is always required.  If it's an invalid path, the io__* functions will catch it.
  if (opts.page_directory == NULL)
    show_error(E_BAD_CLI, "You must specify a directory to search for pages for the test (-p).");
  // -- Memory needs to be at least MIN_MEMORY and less than the installed physical memory.
  const size_t PHYSICAL_MEMORY = (size_t)sysconf(_SC_PHYS_PAGES) * (size_t)sysconf(_SC_PAGESIZE);
  if (opts.max_memory < MIN_MEMORY)
    show_error(E_BAD_CLI, "The memory argument you supplied (-m) is too low.  You sent %"PRIu64", but a minimum of %"PRIu64" is required.", opts.max_memory, MIN_MEMORY);
  if (PHYSICAL_MEMORY == 0)
    show_error(E_GENERIC, "Unable to discern the amount of memory this system has.  Can't be sure we have enough memory to do this test.");
  if (opts.max_memory > PHYSICAL_MEMORY)
    show_error(E_BAD_CLI, "The memory argument you supplied (-m) is too high.  You sent %"PRIu64", but your system maximum physical memory is %d.", opts.max_memory, PHYSICAL_MEMORY);
  // -- Fixed ratio should be -1 (not fixed) or 1 to 100.  Zero is either an atoi() error or nonsensical (can't have just a compressed list and 0% raw.
  if (opts.fixed_ratio == 0)
    show_error(E_BAD_CLI, "The fixed ratio (-f) is 0.  You either sent invalid input (atoi() failed), or you misunderstood the option; fixed size of 0 would mean 0% for raw buffers which is nonsensical.");
  if (opts.fixed_ratio < -1)
    show_error(E_BAD_CLI, "The fixed ratio (-f) cannot be negative... that's just weird.  Why did you send %"PRIi8"?", opts.fixed_ratio);
  if (opts.fixed_ratio > 100)
    show_error(E_BAD_CLI, "The fixed ratio (-f) cannot be over 100... you can't have more than 100%% of your memory assigned to something.  You sent %"PRIi8".", opts.fixed_ratio);
  // -- Workers must be 1+.  Will be 0 if atoi() fails or user is derp.
  if (opts.workers == 0)
    show_error(E_BAD_CLI, "The worker count (-w) is 0.  You either sent invalid input (atoi() failed), or you misunderstood the option.  You need at least 1 worker to, ya know, do work.");
  if (opts.workers == MAX_WORKERS)
    show_error(E_BAD_CLI, "You specified more workers (-w) than allowed (max: %d).", MAX_WORKERS);
  // -- Duration must be non-zero and less than MAX_DURATION.
  if (opts.duration == 0)
    show_error(E_BAD_CLI, "The duration (-d) is 0.  You either sent invalid input (atoi() failed), or you misunderstood the option.  The test must run for at least 1 second.");
  if (opts.duration == MAX_DURATION)
    show_error(E_BAD_CLI, "You specified a duration (-d) greater than the max allowed (%d).", MAX_DURATION);
  // -- Dataset max cannot be 0.  Other than that... shrugs.
  if (opts.dataset_max == 0)
    show_error(E_BAD_CLI, "The maximum dataset bytes (-b) is 0.  You either sent invalid input (atoi() failed), or you misunderstood the option; it limits the number of bytes the scan functions will find before moving on with the test.");
  // -- Page limit cannot be 0.
  if (opts.page_limit == 0)
    show_error(E_BAD_CLI, "The page limit (-n) is 0.  You either sent invalid input (atoi() failed), or you misunderstood the option; it limits the number of pages the scan functions will find before moving on with the test.");
  // -- When compression is disabled, warn the user!
  if (opts.compressor_id == NO_COMPRESSOR_ID)
    fprintf(stderr, "WARNING!!  Compression is DISABLED (you sent -C).\n");
  // -- If bias isn't between 0 and 100 we're in trouble.
  if (opts.bias_percent < 0 || opts.bias_percent > 100)
    show_error(E_BAD_CLI, "The bias percentage (-B X,Y) must be between 0 and 100 inclusive, not %d.\n", opts.bias_percent);
  if (opts.bias_aggregate < 0 || opts.bias_aggregate > 100)
    show_error(E_BAD_CLI, "The bias aggregate (-B X,Y) must be between 0 and 100 inclusive, not %d.\n", opts.bias_aggregate);
  // -- If the update or delete frequencies aren't between 0 and 100 we're in trouble.
  if (opts.update_frequency < 0 || opts.update_frequency > 100)
    show_error(E_BAD_CLI, "The update frequency (-U) must be between 0 and 100 inclusive, not %d.\n", opts.update_frequency);
  if (opts.delete_frequency < 0 || opts.delete_frequency > 100)
    show_error(E_BAD_CLI, "The delete frequency (-D) must be between 0 and 100 inclusive, not %d.\n", opts.delete_frequency);
  // -- The min pages retrieved in a round can't greater than max...
  if (opts.min_pages_retrieved > opts.max_pages_retrieved)
    show_error(E_BAD_CLI, "You can't set the minimum pages per round (X) higher than the maximum per round (Y) for -M.\n");

  return;
}
Example #8
0
void main ()
{
  const char * command;
  int flags;

  vBSP430platformInitialize_ni();
  (void)iBSP430consoleInitialize();
  vBSP430cliSetDiagnosticFunction(iBSP430cliConsoleDiagnostic);
  cprintf("\ncli example " __DATE__ " " __TIME__ "\n");
#if configBSP430_CLI_COMMAND_COMPLETION - 0
  cprintf("Command completion is available.\n");
#endif /* configBSP430_CLI_COMMAND_COMPLETION */
  vBSP430ledSet(0, 1);
  cprintf("\nLED lit when not awaiting input\n");

  /* NOTE: The control flow in this is a bit tricky, as we're trying
   * to leave interrupts enabled during the main body of the loop,
   * while they must be disabled when processing input to recognize a
   * command.  The flags variable preserves state across multiple loop
   * iterations until all relevant activities have completed. */
  commandSet = LAST_COMMAND;
  command = NULL;
  flags = eBSP430cliConsole_REPAINT;

  BSP430_CORE_ENABLE_INTERRUPT();
  while (1) {
    if (flags & eBSP430cliConsole_ANY_ESCAPE) {
      int c;
      while (0 <= ((c = cgetchar()))) {
        cprintf("escape char 0x%02x (%u) '%c'\n", c, c, isprint(c) ? c : '.');
        /* Technically CSI is a single character 0x9b representing
         * ESC+[.  In the two-character mode accepted here, we use the
         * value for the second character. */
#define KEY_CSI '['
        if ((KEY_CSI == c) && (flags & eBSP430cliConsole_PROCESS_ESCAPE)) {
          flags &= ~eBSP430cliConsole_PROCESS_ESCAPE;
          flags |= eBSP430cliConsole_IN_ESCAPE;
        } else if ((64 <= c) && (c <= 126)) {
          flags &= ~eBSP430cliConsole_ANY_ESCAPE;
          cprintf("Leaving escape mode\n");
          break;
        }
      }
    }
    if (flags & eBSP430cliConsole_DO_COMPLETION) {
      flags &= ~eBSP430cliConsole_DO_COMPLETION;
      flags |= iBSP430cliConsoleBufferCompletion(commandSet, &command);
    }
    if (flags & eBSP430cliConsole_READY) {
      int rv;

      rv = iBSP430cliExecuteCommand(commandSet, 0, command);
      if (0 != rv) {
        cprintf("Command execution returned %d\n", rv);
      }
      /* Ensure prompt is rewritten, but not the command we just
       * ran */
      flags |= eBSP430cliConsole_REPAINT;
      command = NULL;
    }
    if (flags & eBSP430cliConsole_REPAINT) {
      /* Draw the prompt along with whatever's left in the command
       * buffer.  Note use of leading carriage return in case an edit
       * left material on the current line. */
      cprintf("\r> %s", command ? command : "");
      flags &= ~eBSP430cliConsole_REPAINT;
    }
    if (flags & eBSP430cliConsole_REPAINT_BEL) {
      cputchar('\a');
      flags &= ~eBSP430cliConsole_REPAINT_BEL;
    }
    BSP430_CORE_DISABLE_INTERRUPT();
    do {
      if (flags & eBSP430cliConsole_READY) {
        /* Clear the command we just completed */
        vBSP430cliConsoleBufferClear_ni();
        flags &= ~eBSP430cliConsole_READY;
      }
      do {
        /* Unless we're processing application-specific escape
         * characters let iBSP430cliConsoleBufferProcessInput_ni()
         * process any input characters that have already been
         * received. */
        if (! (flags & eBSP430cliConsole_ANY_ESCAPE)) {
          flags |= iBSP430cliConsoleBufferProcessInput_ni();
        }
        if (0 == flags) {
          /* Sleep until something wakes us, such as console input.
           * Then turn off interrupts and loop back to read that
           * input. */
          vBSP430ledSet(0, 0);
          BSP430_CORE_LPM_ENTER_NI(LPM0_bits);
          BSP430_CORE_DISABLE_INTERRUPT();
          vBSP430ledSet(0, 1);
        }
        /* Repeat if still nothing to do */
      } while (! flags);

      /* Got something to do; get the command contents in place so
       * we can update the screen. */
      command = xBSP430cliConsoleBuffer_ni();
    } while (0);
    BSP430_CORE_ENABLE_INTERRUPT();
  }
}
Example #9
0
/* Set every byte of row->hl (that corresponds to every character in the line)
 * to the right syntax highlight type (HL_* defines). */
void editorUpdateSyntax(erow *row) {
    row->hl = realloc(row->hl,row->rsize);
    memset(row->hl,HL_NORMAL,row->rsize);

    if (E.syntax == NULL) return; /* No syntax, everything is HL_NORMAL. */

    int i, prev_sep, in_string, in_comment;
    char *p;
    char **keywords = E.syntax->keywords;
    char *scs = E.syntax->singleline_comment_start;
    char *mcs = E.syntax->multiline_comment_start;
    char *mce = E.syntax->multiline_comment_end;

    /* Point to the first non-space char. */
    p = row->render;
    i = 0; /* Current char offset */
    while(*p && isspace(*p)) {
        p++;
        i++;
    }
    prev_sep = 1; /* Tell the parser if 'i' points to start of word. */
    in_string = 0; /* Are we inside "" or '' ? */
    in_comment = 0; /* Are we inside multi-line comment? */

    /* If the previous line has an open comment, this line starts
     * with an open comment state. */
    if (row->idx > 0 && editorRowHasOpenComment(&E.row[row->idx-1]))
        in_comment = 1;

    while(*p) {
        /* Handle // comments. */
        if (prev_sep && *p == scs[0] && *(p+1) == scs[1]) {
            /* From here to end is a comment */
            memset(row->hl+i,HL_COMMENT,row->size-i);
            return;
        }

        /* Handle multi line comments. */
        if (in_comment) {
            row->hl[i] = HL_MLCOMMENT;
            if (*p == mce[0] && *(p+1) == mce[1]) {
                row->hl[i+1] = HL_MLCOMMENT;
                p += 2; i += 2;
                in_comment = 0;
                prev_sep = 1;
                continue;
            } else {
                prev_sep = 0;
                p++; i++;
                continue;
            }
        } else if (*p == mcs[0] && *(p+1) == mcs[1]) {
            row->hl[i] = HL_MLCOMMENT;
            row->hl[i+1] = HL_MLCOMMENT;
            p += 2; i += 2;
            in_comment = 1;
            prev_sep = 0;
            continue;
        }

        /* Handle "" and '' */
        if (in_string) {
            row->hl[i] = HL_STRING;
            if (*p == '\\') {
                row->hl[i+1] = HL_STRING;
                p += 2; i += 2;
                prev_sep = 0;
                continue;
            }
            if (*p == in_string) in_string = 0;
            p++; i++;
            continue;
        } else {
            if (*p == '"' || *p == '\'') {
                in_string = *p;
                row->hl[i] = HL_STRING;
                p++; i++;
                prev_sep = 0;
                continue;
            }
        }

        /* Handle non printable chars. */
        if (!isprint(*p)) {
            row->hl[i] = HL_NONPRINT;
            p++; i++;
            prev_sep = 0;
            continue;
        }

        /* Handle numbers */
        if ((isdigit(*p) && (prev_sep || row->hl[i-1] == HL_NUMBER)) ||
            (*p == '.' && i >0 && row->hl[i-1] == HL_NUMBER)) {
            row->hl[i] = HL_NUMBER;
            p++; i++;
            prev_sep = 0;
            continue;
        }

        /* Handle keywords and lib calls */
        if (prev_sep) {
            int j;
            for (j = 0; keywords[j]; j++) {
                int klen = strlen(keywords[j]);
                int kw2 = keywords[j][klen-1] == '|';
                if (kw2) klen--;

                if (!memcmp(p,keywords[j],klen) &&
                    is_separator(*(p+klen)))
                {
                    /* Keyword */
                    memset(row->hl+i,kw2 ? HL_KEYWORD2 : HL_KEYWORD1,klen);
                    p += klen;
                    i += klen;
                    break;
                }
            }
            if (keywords[j] != NULL) {
                prev_sep = 0;
                continue; /* We had a keyword match */
            }
        }

        /* Not special chars */
        prev_sep = is_separator(*p);
        p++; i++;
    }

    /* Propagate syntax change to the next row if the open commen
     * state changed. This may recursively affect all the following rows
     * in the file. */
    int oc = editorRowHasOpenComment(row);
    if (row->hl_oc != oc && row->idx+1 < E.numrows)
        editorUpdateSyntax(&E.row[row->idx+1]);
    row->hl_oc = oc;
}
Example #10
0
// generic error handler - if err is nonzero, prints error message and exits program.
void CheckError(OSStatus error, const char *operation) {
	if (error == noErr) return;
	
	char str[20];
	// see if it appears to be a 4-char-code
	*(UInt32 *)(str + 1) = CFSwapInt32HostToBig(error);
	if (isprint(str[1]) && isprint(str[2]) && isprint(str[3]) && isprint(str[4])) {
		str[0] = str[5] = '\'';
		str[6] = '\0';
	} else {
		// no, format it as an integer
		sprintf(str, "%d", (int)error);
	}
	fprintf(stderr, "Error: %s (%s)\n", operation, str);
    
    
    // from Audio Unit Processing Graph Services Reference
    switch(error) {
        case kAUGraphErr_NodeNotFound:
            fprintf(stderr, "Error:kAUGraphErr_NodeNotFound \n");
            break;
        case kAUGraphErr_OutputNodeErr:
            fprintf(stderr, "Error:kAUGraphErr_OutputNodeErr \n");
            break;
        case kAUGraphErr_InvalidConnection:
            fprintf(stderr, "Error:kAUGraphErr_InvalidConnection \n");
            break;
        case kAUGraphErr_CannotDoInCurrentContext:
            fprintf(stderr, "Error:kAUGraphErr_CannotDoInCurrentContext \n");
            break;
        case kAUGraphErr_InvalidAudioUnit:
            fprintf(stderr, "Error:kAUGraphErr_InvalidAudioUnit \n");
            break;
        case kMIDIInvalidClient :
            fprintf(stderr, "kMIDIInvalidClient ");
            break;
            
        case kMIDIInvalidPort :
            fprintf(stderr, "kMIDIInvalidPort ");
            break;
            
        case kMIDIWrongEndpointType :
            fprintf(stderr, "kMIDIWrongEndpointType"); 
            break;
            
        case kMIDINoConnection :
            fprintf(stderr, "kMIDINoConnection ");
            break;
            
        case kMIDIUnknownEndpoint :
            fprintf(stderr, "kMIDIUnknownEndpoint ");
            break;
            
        case kMIDIUnknownProperty :
            fprintf(stderr, "kMIDIUnknownProperty ");
            break;
            
        case kMIDIWrongPropertyType :
            fprintf(stderr, "kMIDIWrongPropertyType ");
            break;
            
        case kMIDINoCurrentSetup :
            fprintf(stderr, "kMIDINoCurrentSetup ");
            break;
            
        case kMIDIMessageSendErr :
            fprintf(stderr, "kMIDIMessageSendErr ");
            break;
            
        case kMIDIServerStartErr :
            fprintf(stderr, "kMIDIServerStartErr ");
            break;
            
        case kMIDISetupFormatErr :
            fprintf(stderr, "kMIDISetupFormatErr ");
            break;
            
        case kMIDIWrongThread :
            fprintf(stderr, "kMIDIWrongThread ");
            break;
            
        case kMIDIObjectNotFound :
            fprintf(stderr, "kMIDIObjectNotFound ");
            break;
            
        case kMIDIIDNotUnique :
            fprintf(stderr, "kMIDIIDNotUnique ");
            break;
            
        case kAudioToolboxErr_InvalidSequenceType :
            fprintf(stderr, " kAudioToolboxErr_InvalidSequenceType ");
            break;
            
        case kAudioToolboxErr_TrackIndexError :
            fprintf(stderr, " kAudioToolboxErr_TrackIndexError ");
            break;
            
        case kAudioToolboxErr_TrackNotFound :
            fprintf(stderr, " kAudioToolboxErr_TrackNotFound ");
            break;
            
        case kAudioToolboxErr_EndOfTrack :
            fprintf(stderr, " kAudioToolboxErr_EndOfTrack ");
            break;
            
        case kAudioToolboxErr_StartOfTrack :
            fprintf(stderr, " kAudioToolboxErr_StartOfTrack ");
            break;
            
        case kAudioToolboxErr_IllegalTrackDestination	:
            fprintf(stderr, " kAudioToolboxErr_IllegalTrackDestination");
            break;
            
        case kAudioToolboxErr_NoSequence 		:
            fprintf(stderr, " kAudioToolboxErr_NoSequence ");
            break;
            
        case kAudioToolboxErr_InvalidEventType		:
            fprintf(stderr, " kAudioToolboxErr_InvalidEventType");
            break;
            
        case kAudioToolboxErr_InvalidPlayerState	:
            fprintf(stderr, " kAudioToolboxErr_InvalidPlayerState");
            break;
            
//        case kAudioToolboxErr_CannotDoInCurrentContext	:
//            fprintf(stderr, " kAudioToolboxErr_CannotDoInCurrentContext");
//            break;
            
        case kAudioUnitErr_InvalidProperty		:
            fprintf(stderr, " kAudioUnitErr_InvalidProperty");
            break;
            
        case kAudioUnitErr_InvalidParameter		:
            fprintf(stderr, " kAudioUnitErr_InvalidParameter");
            break;
            
        case kAudioUnitErr_InvalidElement		:
            fprintf(stderr, " kAudioUnitErr_InvalidElement");
            break;
            
        case kAudioUnitErr_NoConnection			:
            fprintf(stderr, " kAudioUnitErr_NoConnection");
            break;
            
        case kAudioUnitErr_FailedInitialization		:
            fprintf(stderr, " kAudioUnitErr_FailedInitialization");
            break;
            
        case kAudioUnitErr_TooManyFramesToProcess	:
            fprintf(stderr, " kAudioUnitErr_TooManyFramesToProcess");
            break;
            
        case kAudioUnitErr_InvalidFile			:
            fprintf(stderr, " kAudioUnitErr_InvalidFile");
            break;
            
        case kAudioUnitErr_FormatNotSupported		:
            fprintf(stderr, " kAudioUnitErr_FormatNotSupported");
            break;
            
        case kAudioUnitErr_Uninitialized		:
            fprintf(stderr, " kAudioUnitErr_Uninitialized");
            break;
            
        case kAudioUnitErr_InvalidScope			:
            fprintf(stderr, " kAudioUnitErr_InvalidScope");
            break;
            
        case kAudioUnitErr_PropertyNotWritable		:
            fprintf(stderr, " kAudioUnitErr_PropertyNotWritable");
            break;
            
        case kAudioUnitErr_InvalidPropertyValue		:
            fprintf(stderr, " kAudioUnitErr_InvalidPropertyValue");
            break;
            
        case kAudioUnitErr_PropertyNotInUse		:
            fprintf(stderr, " kAudioUnitErr_PropertyNotInUse");
            break;
            
        case kAudioUnitErr_Initialized			:
            fprintf(stderr, " kAudioUnitErr_Initialized");
            break;
            
        case kAudioUnitErr_InvalidOfflineRender		:
            fprintf(stderr, " kAudioUnitErr_InvalidOfflineRender");
            break;
            
        case kAudioUnitErr_Unauthorized			:
            fprintf(stderr, " kAudioUnitErr_Unauthorized");
            break;
	}
	exit(1);
}
/*
 * Log an SSH packet.
 * If n_blanks != 0, blank or omit some parts.
 * Set of blanking areas must be in increasing order.
 */
void log_packet(void *handle, int direction, int type,
		char *texttype, const void *data, int len,
		int n_blanks, const struct logblank_t *blanks,
		const unsigned long *seq,
                unsigned downstream_id, const char *additional_log_text)
{
    struct LogContext *ctx = (struct LogContext *)handle;
    char dumpdata[80], smalldata[5];
    int p = 0, b = 0, omitted = 0;
    int output_pos = 0; /* NZ if pending output in dumpdata */

    if (!(ctx->logtype == LGTYP_SSHRAW ||
          (ctx->logtype == LGTYP_PACKETS && texttype)))
	return;

    /* Packet header. */
    if (texttype) {
        logprintf(ctx, "%s packet ",
                  direction == PKT_INCOMING ? "Incoming" : "Outgoing");

	if (seq)
	    logprintf(ctx, "#0x%lx, ", *seq);

        logprintf(ctx, "type %d / 0x%02x (%s)", type, type, texttype);

        if (downstream_id) {
	    logprintf(ctx, " on behalf of downstream #%u", downstream_id);
            if (additional_log_text)
                logprintf(ctx, " (%s)", additional_log_text);
        }

        logprintf(ctx, "\r\n");
    } else {
        /*
         * Raw data is logged with a timestamp, so that it's possible
         * to determine whether a mysterious delay occurred at the
         * client or server end. (Timestamping the raw data avoids
         * cluttering the normal case of only logging decrypted SSH
         * messages, and also adds conceptual rigour in the case where
         * an SSH message arrives in several pieces.)
         */
        char buf[256];
        struct tm tm;
	tm = ltime();
	strftime(buf, 24, "%Y-%m-%d %H:%M:%S", &tm);
        logprintf(ctx, "%s raw data at %s\r\n",
                  direction == PKT_INCOMING ? "Incoming" : "Outgoing",
                  buf);
    }

    /*
     * Output a hex/ASCII dump of the packet body, blanking/omitting
     * parts as specified.
     */
    while (p < len) {
	int blktype;

	/* Move to a current entry in the blanking array. */
	while ((b < n_blanks) &&
	       (p >= blanks[b].offset + blanks[b].len))
	    b++;
	/* Work out what type of blanking to apply to
	 * this byte. */
	blktype = PKTLOG_EMIT; /* default */
	if ((b < n_blanks) &&
	    (p >= blanks[b].offset) &&
	    (p < blanks[b].offset + blanks[b].len))
	    blktype = blanks[b].type;

	/* If we're about to stop omitting, it's time to say how
	 * much we omitted. */
	if ((blktype != PKTLOG_OMIT) && omitted) {
	    logprintf(ctx, "  (%d byte%s omitted)\r\n",
		      omitted, (omitted==1?"":"s"));
	    omitted = 0;
	}

	/* (Re-)initialise dumpdata as necessary
	 * (start of row, or if we've just stopped omitting) */
	if (!output_pos && !omitted)
	    szprintf(dumpdata, sizeof(dumpdata),
		     "  %08x%*s\r\n", p-(p%16), 1+3*16+2+16, "");

	/* Deal with the current byte. */
	if (blktype == PKTLOG_OMIT) {
	    omitted++;
	} else {
	    int c;
	    if (blktype == PKTLOG_BLANK) {
		c = 'X';
		szprintf(smalldata, sizeof(smalldata), "XX");
	    } else {  /* PKTLOG_EMIT */
		c = ((unsigned char *)data)[p];
		szprintf(smalldata, sizeof(smalldata), "%02x", c);
	    }
	    dumpdata[10+2+3*(p%16)] = smalldata[0];
	    dumpdata[10+2+3*(p%16)+1] = smalldata[1];
	    dumpdata[10+1+3*16+2+(p%16)] = (isprint(c) ? c : '.');
	    output_pos = (p%16) + 1;
	}

	p++;

	/* Flush row if necessary */
	if (((p % 16) == 0) || (p == len) || omitted) {
	    if (output_pos) {
		strcpy(dumpdata + 10+1+3*16+2+output_pos, "\r\n");
		logwrite(ctx, dumpdata, strlen(dumpdata));
		output_pos = 0;
	    }
	}

    }

    /* Tidy up */
    if (omitted)
	logprintf(ctx, "  (%d byte%s omitted)\r\n",
		  omitted, (omitted==1?"":"s"));
    logflush(ctx);
}
Example #12
0
static void write_propval_string(FILE *f, struct data val)
{
	const char *str = val.val;
	int i;
	int newchunk = 1;
	struct marker *m = val.markers;

	assert(str[val.len-1] == '\0');

	for (i = 0; i < (val.len-1); i++) {
		char c = str[i];

		if (newchunk) {
			while (m && (m->offset <= i)) {
				if (m->type == LABEL) {
					assert(m->offset == i);
					fprintf(f, "%s: ", m->ref);
				}
				m = m->next;
			}
			fprintf(f, "\"");
			newchunk = 0;
		}

		switch (c) {
		case '\a':
			fprintf(f, "\\a");
			break;
		case '\b':
			fprintf(f, "\\b");
			break;
		case '\t':
			fprintf(f, "\\t");
			break;
		case '\n':
			fprintf(f, "\\n");
			break;
		case '\v':
			fprintf(f, "\\v");
			break;
		case '\f':
			fprintf(f, "\\f");
			break;
		case '\r':
			fprintf(f, "\\r");
			break;
		case '\\':
			fprintf(f, "\\\\");
			break;
		case '\"':
			fprintf(f, "\\\"");
			break;
		case '\0':
			fprintf(f, "\", ");
			newchunk = 1;
			break;
		default:
			if (isprint(c))
				fprintf(f, "%c", c);
			else
				fprintf(f, "\\x%02hhx", c);
		}
	}
	fprintf(f, "\"");

	/* Wrap up any labels at the end of the value */
	for_each_marker_of_type(m, LABEL) {
		assert (m->offset == val.len);
		fprintf(f, " %s:", m->ref);
	}
Example #13
0
int isstring(char c)
{
	return (isprint(c)
		|| (c == '\0')
		|| strchr("\a\b\t\n\v\f\r", c));
}
/* read in command line arguments and store in global variables for easy
 * access by other functions.
 */
void getCommandLine(int argc, char **argv)
{
    /* optopt--if an unknown option character is found
     * optind--index of next element in argv
     * optarg--argument for option that requires argument
     * "x:" colon after x means argument required
     */
    int c;
    int index;

    while ((c = getopt(argc, argv, "m:a:h:i:t:s:erbv")) != -1)
        switch(c) {
        case 'm':
            TableSize = atoi(optarg);
            break;
        case 'a':
            LoadFactor = atof(optarg);
            break;
        case 's':
            Seed = atoi(optarg);
            break;
        case 't':
            Trials = atoi(optarg);
            break;
        case 'v':
            Verbose = TRUE;
            break;
        case 'e':
            EquilibriumTest = TRUE;
            break;
        case 'r':
            RetrieveTest = TRUE;
            break;
        case 'b':
            RehashTest = TRUE;
            break;
        case 'h':
            if (strcmp(optarg, "linear") == 0)
                ProbeDec = LINEAR;
            else if (strcmp(optarg, "double") == 0)
                ProbeDec = DOUBLE;
            else if (strcmp(optarg, "chain") == 0)
                ProbeDec = CHAIN;
            else {
                fprintf(stderr, "invalid type of probing decrement: %s\n", optarg);
                fprintf(stderr, "must be {linear | double | chain}\n");
                exit(1);
            }
            break;
        case 'i':
            if (strcmp(optarg, "rand") == 0)
                TableType = RAND;
            else if (strcmp(optarg, "seq") == 0)
                TableType = SEQ;
            else if (strcmp(optarg, "fold") == 0)
                TableType = FOLD;
            else if (strcmp(optarg, "worst") == 0)
                TableType = WORST;
            else {
                fprintf(stderr, "invalid type of address generation: %s\n", optarg);
                fprintf(stderr, "must be {rand | seq | fold | worst}\n");
                exit(1);
            }
            break;
        case '?':
            if (isprint(optopt))
                fprintf(stderr, "Unknown option %c.\n", optopt);
            else
                fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
        default:
            printf("Lab7 command line options\n");
            printf("General options ---------\n");
            printf("  -m 11     table size\n");
            printf("  -a 0.9    load factor\n");
            printf("  -h linear|double|chain\n");
            printf("            Type of probing decrement\n");
            printf("  -r        run retrieve test driver \n");
            printf("  -b        run basic test driver \n");
            printf("  -e        run equilibrium test driver\n");
            printf("  -i rand|seq|fold|worst\n");
            printf("            type of keys for retrieve test driver \n");
            printf("\nOptions for test driver ---------\n");
            printf("  -t 50000  number of trials in drivers\n");
            printf("  -v        turn on verbose prints (default off)\n");
            printf("  -s 26214  seed for random number generator\n");
            exit(1);
        }
    for (index = optind; index < argc; index++)
        printf("Non-option argument %s\n", argv[index]);
}
int main(int argc, char **argv)
{
	char command = 'n';
	char help_flag = 0;
	char non_option_flag = 0;
	unsigned int length = 1;
	char *input_file_name = NULL;
	char *output_file_name = NULL;
	int i, c;

	opterr = 0;

	while ((c = getopt (argc, argv, "edhl:i:o:")) != -1) {
		switch (c) {
		case 'e':
			command = 'e';
			break;
		case 'd':
			command = 'd';
			break;
		case 'h':
			help_flag = 1;
			break;
		case 'l':
			length = *optarg - 48;
			printf("Length = %i\n",length);
			break;
		case 'i':
			input_file_name = optarg;
			break;
		case 'o':
			output_file_name = optarg;
			break;
		case '?':
			if (optopt == 'c')
				fprintf (stderr, "Option -%c requires an argument.\n", optopt);
			else if (isprint (optopt))
				fprintf (stderr, "Unknown option `-%c'.\n", optopt);
			else
				fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);
			return 1;
		default:
			abort();
		}
	}

	for (i = optind; i < argc; i++) {
		if (!non_option_flag)
			non_option_flag = 1;
		printf("Non-option argument: %s\n", argv[i]);
	}

	if (non_option_flag)
		return 1;

	else if (help_flag || (argc == 1))
		show_help(argv[0]);

	else if (command != 'n') {

		if (!input_file_name)
			printf("You need to specify an input file\n");

		else if (!output_file_name)
			printf("You need to specify an output file\n");

		else if (length < 1)
			printf("You need to specify a positive length\n");

		else
			process_command(command, input_file_name, output_file_name, length);

	}
	return 0;
}
Example #16
0
status_t
BGopherRequest::_ProtocolLoop()
{
	if (fSocket == NULL)
		return B_NO_MEMORY;

	if (!_ResolveHostName()) {
		_EmitDebug(B_URL_PROTOCOL_DEBUG_ERROR,
			"Unable to resolve hostname (%s), aborting.",
				fUrl.Host().String());
		return B_SERVER_NOT_FOUND;
	}

	_EmitDebug(B_URL_PROTOCOL_DEBUG_TEXT, "Connection to %s on port %d.",
		fUrl.Authority().String(), fRemoteAddr.Port());
	status_t connectError = fSocket->Connect(fRemoteAddr);

	if (connectError != B_OK) {
		_EmitDebug(B_URL_PROTOCOL_DEBUG_ERROR, "Socket connection error %s",
			strerror(connectError));
		return connectError;
	}

	//! ProtocolHook:ConnectionOpened
	if (fListener != NULL)
		fListener->ConnectionOpened(this);

	_EmitDebug(B_URL_PROTOCOL_DEBUG_TEXT,
		"Connection opened, sending request.");

	_SendRequest();
	_EmitDebug(B_URL_PROTOCOL_DEBUG_TEXT, "Request sent.");

	// Receive loop
	bool receiveEnd = false;
	status_t readError = B_OK;
	ssize_t bytesRead = 0;
	//ssize_t bytesReceived = 0;
	//ssize_t bytesTotal = 0;
	bool dataValidated = false;
	BStackOrHeapArray<char, 4096> chunk(kGopherBufferSize);

	while (!fQuit && !receiveEnd) {
		fSocket->WaitForReadable();
		bytesRead = fSocket->Read(chunk, kGopherBufferSize);

		if (bytesRead < 0) {
			readError = bytesRead;
			break;
		} else if (bytesRead == 0)
			receiveEnd = true;

		fInputBuffer.AppendData(chunk, bytesRead);

		if (!dataValidated) {
			size_t i;
			// on error (file doesn't exist, ...) the server sends
			// a faked directory entry with an error message
			if (fInputBuffer.Size() && fInputBuffer.Data()[0] == '3') {
				int tabs = 0;
				bool crlf = false;

				// make sure the buffer only contains printable characters
				// and has at least 3 tabs before a CRLF
				for (i = 0; i < fInputBuffer.Size(); i++) {
					char c = fInputBuffer.Data()[i];
					if (c == '\t') {
						if (!crlf)
							tabs++;
					} else if (c == '\r' || c == '\n') {
						if (tabs < 3)
							break;
						crlf = true;
					} else if (!isprint(fInputBuffer.Data()[i])) {
						crlf = false;
						break;
					}
				}
				if (crlf && tabs > 2 && tabs < 5) {
					// TODO:
					//if enough data
					// else continue
					fItemType = GOPHER_TYPE_DIRECTORY;
					readError = B_RESOURCE_NOT_FOUND;
					// continue parsing the error text anyway
				}
			}
			// special case for buggy(?) Gophernicus/1.5
			static const char *buggy = "Error: File or directory not found!";
			if (fInputBuffer.Size() > strlen(buggy)
				&& !memcmp(fInputBuffer.Data(), buggy, strlen(buggy))) {
				fItemType = GOPHER_TYPE_DIRECTORY;
				readError = B_RESOURCE_NOT_FOUND;
				// continue parsing the error text anyway
				// but it won't look good
			}
			

			// now we probably have correct data
			dataValidated = true;

			//! ProtocolHook:ResponseStarted
			if (fListener != NULL)
				fListener->ResponseStarted(this);

			// we don't really have headers but well...
			//! ProtocolHook:HeadersReceived
			if (fListener != NULL)
				fListener->HeadersReceived(this);

			// now we can assign MIME type if we know it
			const char *mime = "application/octet-stream";
			for (i = 0; gopher_type_map[i].type != GOPHER_TYPE_NONE; i++) {
				if (gopher_type_map[i].type == fItemType) {
					mime = gopher_type_map[i].mime;
					break;
				}
			}
			fResult.SetContentType(mime);
		}

		if (_NeedsParsing())
			_ParseInput(receiveEnd);
		else if (fInputBuffer.Size()) {
			// send input directly
			fListener->DataReceived(this, (const char *)fInputBuffer.Data(),
								fPosition, fInputBuffer.Size());

			fPosition += fInputBuffer.Size();

			// XXX: this is plain stupid, we already copied the data
			// and just want to drop it...
			char *inputTempBuffer = new(std::nothrow) char[bytesRead];
			if (inputTempBuffer == NULL) {
				readError = B_NO_MEMORY;
				break;
			}
			fInputBuffer.RemoveData(inputTempBuffer, fInputBuffer.Size());
			delete[] inputTempBuffer;
		}
	}

	if (fPosition > 0) {
		fResult.SetLength(fPosition);
		fListener->DownloadProgress(this, fPosition, fPosition);
	}

	fSocket->Disconnect();

	if (readError != B_OK)
		return readError;

	return fQuit ? B_INTERRUPTED : B_OK;
}
Example #17
0
void debug_view_memory::view_update()
{
	const debug_view_memory_source &source = downcast<const debug_view_memory_source &>(*m_source);

	// if we need to recompute, do it now
	if (needs_recompute())
		recompute();

	// get positional data
	const memory_view_pos &posdata = s_memory_pos_table[m_bytes_per_chunk];

	// loop over visible rows
	for (UINT32 row = 0; row < m_visible.y; row++)
	{
		debug_view_char *destmin = m_viewdata + row * m_visible.x;
		debug_view_char *destmax = destmin + m_visible.x;
		debug_view_char *destrow = destmin - m_topleft.x;
		UINT32 effrow = m_topleft.y + row;

		// reset the line of data; section 1 is normal, others are ancillary, cursor is selected
		debug_view_char *dest = destmin;
		for (int ch = 0; ch < m_visible.x; ch++, dest++)
		{
			UINT32 effcol = m_topleft.x + ch;
			dest->byte = ' ';
			dest->attrib = DCA_ANCILLARY;
			if (m_section[1].contains(effcol))
			{
				dest->attrib = DCA_NORMAL;
				if (m_cursor_visible && effrow == m_cursor.y && effcol == m_cursor.x)
					dest->attrib |= DCA_SELECTED;
			}
		}

		// if this visible row is valid, add it to the buffer
		if (effrow < m_total.y)
		{
			offs_t addrbyte = m_byte_offset + effrow * m_bytes_per_row;
			offs_t address = (source.m_space != NULL) ? source.m_space->byte_to_address(addrbyte) : addrbyte;
			char addrtext[20];

			// generate the address
			sprintf(addrtext, m_addrformat, address);
			dest = destrow + m_section[0].m_pos + 1;
			for (int ch = 0; addrtext[ch] != 0 && ch < m_section[0].m_width - 1; ch++, dest++)
				if (dest >= destmin && dest < destmax)
					dest->byte = addrtext[ch];

			// generate the data
			for (int chunknum = 0; chunknum < m_chunks_per_row; chunknum++)
			{
				int chunkindex = m_reverse_view ? (m_chunks_per_row - 1 - chunknum) : chunknum;

				UINT64 chunkdata;
				bool ismapped = read(m_bytes_per_chunk, addrbyte + chunknum * m_bytes_per_chunk, chunkdata);
				dest = destrow + m_section[1].m_pos + 1 + chunkindex * posdata.m_spacing;
				for (int ch = 0; ch < posdata.m_spacing; ch++, dest++)
					if (dest >= destmin && dest < destmax)
					{
						UINT8 shift = posdata.m_shift[ch];
						if (shift < 64)
							dest->byte = ismapped ? "0123456789ABCDEF"[(chunkdata >> shift) & 0x0f] : '*';
					}
			}

			// generate the ASCII data
			if (m_section[2].m_width > 0)
			{
				dest = destrow + m_section[2].m_pos + 1;
				for (int ch = 0; ch < m_bytes_per_row; ch++, dest++)
					if (dest >= destmin && dest < destmax)
					{
						UINT64 chval;
						bool ismapped = read(1, addrbyte + ch, chval);
						dest->byte = (ismapped && isprint(chval)) ? chval : '.';
					}
			}
		}
Example #18
0
static int ser_recv(union filedescriptor *fd, unsigned char * buf, size_t buflen)
{
  struct timeval timeout, to2;
  fd_set rfds;
  int nfds;
  int rc;
  unsigned char * p = buf;
  size_t len = 0;

  timeout.tv_sec  = serial_recv_timeout / 1000L;
  timeout.tv_usec = (serial_recv_timeout % 1000L) * 1000;
  to2 = timeout;

  while (len < buflen) {
  reselect:
    FD_ZERO(&rfds);
    FD_SET(fd->ifd, &rfds);

    nfds = select(fd->ifd + 1, &rfds, NULL, NULL, &to2);
    if (nfds == 0) {
      if (verbose > 1)
	fprintf(stderr,
		"%s: ser_recv(): programmer is not responding\n",
		progname);
      return -1;
    }
    else if (nfds == -1) {
      if (errno == EINTR || errno == EAGAIN) {
	fprintf(stderr,
		"%s: ser_recv(): programmer is not responding,reselecting\n",
		progname);
        goto reselect;
      }
      else {
        fprintf(stderr, "%s: ser_recv(): select(): %s\n",
                progname, strerror(errno));
        exit(1);
      }
    }

    rc = read(fd->ifd, p, (buflen - len > 1024) ? 1024 : buflen - len);
    if (rc < 0) {
      fprintf(stderr, "%s: ser_recv(): read error: %s\n",
              progname, strerror(errno));
      exit(1);
    }
    p += rc;
    len += rc;
  }

  p = buf;

  if (verbose > 3)
  {
      fprintf(stderr, "%s: Recv: ", progname);

      while (len) {
        unsigned char c = *p;
        if (isprint(c)) {
          fprintf(stderr, "%c ", c);
        }
        else {
          fprintf(stderr, ". ");
        }
        fprintf(stderr, "[%02x] ", c);

        p++;
        len--;
      }
      fprintf(stderr, "\n");
  }

  return 0;
}
Example #19
0
BOOL
command(int commandc)
{
	char	filename[PATHLEN + 1];	/* file path name */
	MOUSEEVENT *p;			/* mouse data */
	int	c, i;
	FILE	*file;
	HISTORY *curritem, *item;	/* command history */
	char	*s;

	switch (commandc) {

	case ctrl('C'):	/* toggle caseless mode */
		if (caseless == NO) {
			caseless = YES;
			putmsg2("Caseless mode is now ON");
		} else {
			caseless = NO;
			putmsg2("Caseless mode is now OFF");
		}
		egrepcaseless(caseless);	/* turn on/off -i flag */
		return (NO);

	case ctrl('R'):	/* rebuild the cross reference */
		if (isuptodate == YES) {
			putmsg("The -d option prevents rebuilding the "
			    "symbol database");
			return (NO);
		}
		exitcurses();
		freefilelist();		/* remake the source file list */
		makefilelist();
		rebuild();
		if (errorsfound == YES) {
			errorsfound = NO;
			askforreturn();
		}
		entercurses();
		putmsg("");		/* clear any previous message */
		totallines = 0;
		topline = nextline = 1;
		break;

	case ctrl('X'):	/* mouse selection */
		if ((p = getmouseevent()) == NULL) {
			return (NO);	/* unknown control sequence */
		}
		/* if the button number is a scrollbar tag */
		if (p->button == '0') {
			scrollbar(p);
			break;
		}
		/* ignore a sweep */
		if (p->x2 >= 0) {
			return (NO);
		}
		/* if this is a line selection */
		if (p->y1 < FLDLINE) {

			/* find the selected line */
			/* note: the selection is forced into range */
			for (i = disprefs - 1; i > 0; --i) {
				if (p->y1 >= displine[i]) {
					break;
				}
			}
			/* display it in the file with the editor */
			editref(i);
		} else {	/* this is an input field selection */
			field = mouseselection(p, FLDLINE, FIELDS);
			setfield();
			resetcmd();
			return (NO);
		}
		break;

	case '\t':	/* go to next input field */
	case '\n':
	case '\r':
	case ctrl('N'):
	case KEY_DOWN:
	case KEY_ENTER:
	case KEY_RIGHT:
		field = (field + 1) % FIELDS;
		setfield();
		resetcmd();
		return (NO);

	case ctrl('P'):	/* go to previous input field */
	case KEY_UP:
	case KEY_LEFT:
		field = (field + (FIELDS - 1)) % FIELDS;
		setfield();
		resetcmd();
		return (NO);
	case KEY_HOME:	/* go to first input field */
		field = 0;
		setfield();
		resetcmd();
		return (NO);

	case KEY_LL:	/* go to last input field */
		field = FIELDS - 1;
		setfield();
		resetcmd();
		return (NO);
	case ' ':	/* display next page */
	case '+':
	case ctrl('V'):
	case KEY_NPAGE:
		/* don't redisplay if there are no lines */
		if (totallines == 0) {
			return (NO);
		}
		/*
		 * note: seekline() is not used to move to the next
		 * page because display() leaves the file pointer at
		 * the next page to optimize paging forward
		 */
		break;

	case '-':	/* display previous page */
	case KEY_PPAGE:
		/* don't redisplay if there are no lines */
		if (totallines == 0) {
			return (NO);
		}
		i = topline;		/* save the current top line */
		nextline = topline;	/* go back to this page */

		/* if on first page but not at beginning, go to beginning */
		if (nextline > 1 && nextline <= mdisprefs) {
			nextline = 1;
		} else {	/* go back the maximum displayable lines */
			nextline -= mdisprefs;

			/* if this was the first page, go to the last page */
			if (nextline < 1) {
				nextline = totallines - mdisprefs + 1;
				if (nextline < 1) {
					nextline = 1;
				}
				/* old top is past last line */
				i = totallines + 1;
			}
		}
		/*
		 * move down til the bottom line is just before the
		 * previous top line
		 */
		c = nextline;
		for (;;) {
			seekline(nextline);
			display();
			if (i - bottomline <= 0) {
				break;
			}
			nextline = ++c;
		}
		return (NO);	/* display already up to date */

	case '>':	/* write or append the lines to a file */
		if (totallines == 0) {
			putmsg("There are no lines to write to a file");
		} else {	/* get the file name */
			(void) move(PRLINE, 0);
			(void) addstr("Write to file: ");
			s = "w";
			if ((c = mygetch()) == '>') {
				(void) move(PRLINE, 0);
				(void) addstr(appendprompt);
				c = '\0';
				s = "a";
			}
			if (c != '\r' && c != '\n' && c != KEY_ENTER &&
			    c != KEY_BREAK &&
			    getaline(newpat, COLS - sizeof (appendprompt), c,
			    NO) > 0) {
				shellpath(filename, sizeof (filename), newpat);
				if ((file = fopen(filename, s)) == NULL) {
					cannotopen(filename);
				} else {
					seekline(1);
					while ((c = getc(refsfound)) != EOF) {
						(void) putc(c, file);
					}
					seekline(topline);
					(void) fclose(file);
				}
			}
			clearprompt();
		}
		return (NO);	/* return to the previous field */

	case '<':	/* read lines from a file */
		(void) move(PRLINE, 0);
		(void) addstr(readprompt);
		if (getaline(newpat, COLS - sizeof (readprompt), '\0',
		    NO) > 0) {
			clearprompt();
			shellpath(filename, sizeof (filename), newpat);
			if (readrefs(filename) == NO) {
				putmsg2("Ignoring an empty file");
				return (NO);
			}
			return (YES);
		}
		clearprompt();
		return (NO);

	case '^':	/* pipe the lines through a shell command */
	case '|':	/* pipe the lines to a shell command */
		if (totallines == 0) {
			putmsg("There are no lines to pipe to a shell command");
			return (NO);
		}
		/* get the shell command */
		(void) move(PRLINE, 0);
		(void) addstr(pipeprompt);
		if (getaline(newpat,
		    COLS - sizeof (pipeprompt), '\0', NO) == 0) {
			clearprompt();
			return (NO);
		}
		/* if the ^ command, redirect output to a temp file */
		if (commandc == '^') {
			(void) strcat(strcat(newpat, " >"), temp2);
		}
		exitcurses();
		if ((file = mypopen(newpat, "w")) == NULL) {
			(void) fprintf(stderr,
			    "cscope: cannot open pipe to shell command: %s\n",
			    newpat);
		} else {
			seekline(1);
			while ((c = getc(refsfound)) != EOF) {
				(void) putc(c, file);
			}
			seekline(topline);
			(void) mypclose(file);
		}
		if (commandc == '^') {
			if (readrefs(temp2) == NO) {
				putmsg("Ignoring empty output of ^ command");
			}
		}
		askforreturn();
		entercurses();
		break;

	case ctrl('L'):	/* redraw screen */
	case KEY_CLEAR:
		(void) clearok(curscr, TRUE);
		(void) wrefresh(curscr);
		drawscrollbar(topline, bottomline, totallines);
		return (NO);

	case '!':	/* shell escape */
		(void) execute(shell, shell, (char *)NULL);
		seekline(topline);
		break;

	case '?':	/* help */
		(void) clear();
		help();
		(void) clear();
		seekline(topline);
		break;

	case ctrl('E'):	/* edit all lines */
		editall();
		break;

	case ctrl('A'):	/* repeat last pattern */
	case ctrl('Y'):	/* (old command) */
		if (*pattern != '\0') {
			(void) addstr(pattern);
			goto repeat;
		}
		break;

	case ctrl('B'):		/* cmd history back */
	case ctrl('F'):		/* cmd history fwd */
		curritem = currentcmd();
		item = (commandc == ctrl('F')) ? nextcmd() : prevcmd();
		clearmsg2();
		if (curritem == item) {
			/* inform user that we're at history end */
			putmsg2(
			    "End of input field and search pattern history");
		}
		if (item) {
			field = item->field;
			setfield();
			atfield();
			(void) addstr(item->text);
			(void) strcpy(pattern, item->text);
			switch (c = mygetch()) {
			case '\r':
			case '\n':
			case KEY_ENTER:
				goto repeat;
			default:
				ungetch(c);
				atfield();
				(void) clrtoeol(); /* clear current field */
				break;
			}
		}
		return (NO);

	case '\\':	/* next character is not a command */
		(void) addch('\\');	/* display the quote character */

		/* get a character from the terminal */
		if ((commandc = mygetch()) == EOF) {
			return (NO);	/* quit */
		}
		(void) addstr("\b \b");	/* erase the quote character */
		goto ispat;

	case '.':
		atfield();	/* move back to the input field */
		/* FALLTHROUGH */
	default:
		/* edit a selected line */
		if (isdigit(commandc) && commandc != '0' && !mouse) {
			if (returnrequired == NO) {
				editref(commandc - '1');
			} else {
				(void) move(PRLINE, 0);
				(void) addstr(selectionprompt);
				if (getaline(newpat,
				    COLS - sizeof (selectionprompt), commandc,
				    NO) > 0 &&
				    (i = atoi(newpat)) > 0) {
					editref(i - 1);
				}
				clearprompt();
			}
		} else if (isprint(commandc)) {
			/* this is the start of a pattern */
ispat:
			if (getaline(newpat, COLS - fldcolumn - 1, commandc,
			    caseless) > 0) {
					(void) strcpy(pattern, newpat);
					resetcmd();	/* reset history */
repeat:
				addcmd(field, pattern);	/* add to history */
				if (field == CHANGE) {
					/* prompt for the new text */
					(void) move(PRLINE, 0);
					(void) addstr(toprompt);
					(void) getaline(newpat,
					    COLS - sizeof (toprompt), '\0', NO);
				}
				/* search for the pattern */
				if (search() == YES) {
					switch (field) {
					case DEFINITION:
					case FILENAME:
						if (totallines > 1) {
							break;
						}
						topline = 1;
						editref(0);
						break;
					case CHANGE:
						return (changestring());
					}
				} else if (field == FILENAME &&
				    access(newpat, READ) == 0) {
					/* try to edit the file anyway */
					edit(newpat, "1");
				}
			} else {	/* no pattern--the input was erased */
				return (NO);
			}
		} else {	/* control character */
			return (NO);
		}
	}
	return (YES);
}
Example #20
0
inline void debug_dump_hex(const void* dumpdata, int dumplen)
{
	int offset, i, j, k;
	FILE *fptmp = stdout;
	unsigned char *ucptr = (unsigned char*)dumpdata;

	if (DEBUG_LEVEL > 2)
		return;
	/*{
		char buff[24];
		time_t now = time(NULL);
		strftime(buff, 20, "%Y-%m-%d %H:%M:%S\n", localtime(&now));
		fprintf(fptmp, buff);
	}*/
	fprintf(fptmp, "OFFSET       -0--1--2--3--4--5--6--7-*-8--9--a--b--c--d--e--f- DISPLAY\n");
    offset = i = 0;
    
    while (i < dumplen)
    {
        fprintf(fptmp, "%05x(%05d) ", offset, offset);
        for (j = 0; (j < 16) && (i < dumplen); j++, i++)
        {
            if (j < 7)
            {
                fprintf(fptmp, "%02x ", *(ucptr + i));
            }
            else if (j == 7)
            {
                fprintf(fptmp, "%02x -", *(ucptr + i));
            }
            else
            {
                fprintf(fptmp, " %02x", *(ucptr + i));
            }
        }
        
        for (k = j; k < 16; k++)
        {
            fprintf(fptmp, "   ");
        }
        
        if (j < 8)
        {
            fprintf(fptmp, " ");
        }
        
        fprintf(fptmp, " ");
		
        for (k = 0; k < j; k++)
        {
            if (isprint(*(ucptr + i - j + k)))
            {
                fprintf(fptmp, "%c", *(ucptr + i - j + k));
            }
            else
            {
                fprintf(fptmp, ".");
            }
        }
        
        fprintf(fptmp, "\n");
		
        offset += 16;
    }
    
    fprintf(fptmp, "\n");
}
Example #21
0
/*
 * Log an SSH packet.
 * If n_blanks != 0, blank or omit some parts.
 * Set of blanking areas must be in increasing order.
 */
void log_packet(void *handle, int direction, int type,
		char *texttype, const void *data, int len,
		int n_blanks, const struct logblank_t *blanks,
		const unsigned long *seq)
{
    struct LogContext *ctx = (struct LogContext *)handle;
    char dumpdata[80], smalldata[5];
    int p = 0, b = 0, omitted = 0;
    int output_pos = 0; /* NZ if pending output in dumpdata */

    if (!(ctx->cfg.logtype == LGTYP_SSHRAW ||
          (ctx->cfg.logtype == LGTYP_PACKETS && texttype)))
	return;

    /* Packet header. */
    if (texttype) {
	if (seq) {
	    logprintf(ctx, "%s packet #0x%lx, type %d / 0x%02x (%s)\r\n",
		      direction == PKT_INCOMING ? "Incoming" : "Outgoing",
		      *seq, type, type, texttype);
	} else {
	    logprintf(ctx, "%s packet type %d / 0x%02x (%s)\r\n",
		      direction == PKT_INCOMING ? "Incoming" : "Outgoing",
		      type, type, texttype);
	}
    } else {
        logprintf(ctx, "%s raw data\r\n",
                  direction == PKT_INCOMING ? "Incoming" : "Outgoing");
    }

    /*
     * Output a hex/ASCII dump of the packet body, blanking/omitting
     * parts as specified.
     */
    while (p < len) {
	int blktype;

	/* Move to a current entry in the blanking array. */
	while ((b < n_blanks) &&
	       (p >= blanks[b].offset + blanks[b].len))
	    b++;
	/* Work out what type of blanking to apply to
	 * this byte. */
	blktype = PKTLOG_EMIT; /* default */
	if ((b < n_blanks) &&
	    (p >= blanks[b].offset) &&
	    (p < blanks[b].offset + blanks[b].len))
	    blktype = blanks[b].type;

	/* If we're about to stop omitting, it's time to say how
	 * much we omitted. */
	if ((blktype != PKTLOG_OMIT) && omitted) {
	    logprintf(ctx, "  (%d byte%s omitted)\r\n",
		      omitted, (omitted==1?"":"s"));
	    omitted = 0;
	}

	/* (Re-)initialise dumpdata as necessary
	 * (start of row, or if we've just stopped omitting) */
	if (!output_pos && !omitted)
	    sprintf(dumpdata, "  %08x%*s\r\n", p-(p%16), 1+3*16+2+16, "");

	/* Deal with the current byte. */
	if (blktype == PKTLOG_OMIT) {
	    omitted++;
	} else {
	    int c;
	    if (blktype == PKTLOG_BLANK) {
		c = 'X';
		sprintf(smalldata, "XX");
	    } else {  /* PKTLOG_EMIT */
		c = ((unsigned char *)data)[p];
		sprintf(smalldata, "%02x", c);
	    }
	    dumpdata[10+2+3*(p%16)] = smalldata[0];
	    dumpdata[10+2+3*(p%16)+1] = smalldata[1];
	    dumpdata[10+1+3*16+2+(p%16)] = (isprint(c) ? c : '.');
	    output_pos = (p%16) + 1;
	}

	p++;

	/* Flush row if necessary */
	if (((p % 16) == 0) || (p == len) || omitted) {
	    if (output_pos) {
		strcpy(dumpdata + 10+1+3*16+2+output_pos, "\r\n");
		logwrite(ctx, dumpdata, strlen(dumpdata));
		output_pos = 0;
	    }
	}

    }

    /* Tidy up */
    if (omitted)
	logprintf(ctx, "  (%d byte%s omitted)\r\n",
		  omitted, (omitted==1?"":"s"));
    logflush(ctx);
}
Example #22
0
void _hexdump(const char *const caption,
		const void *const buffer, size_t length)
{
	char line[
		ADDRESS_LENGTH + 1 + /* Address */
		BYTES_PER_LINE / 8 + /* Extra separator between every 8 bytes */
		BYTES_PER_LINE * 3 + 1 + /* Byte printed in hex */
		2 +                  /* Left bar */
		BYTES_PER_LINE +     /* Byte Printed in ASCII */
		1 +                  /* Right bar */
		1                    /* Terminator */
	];
	char *pline;
	unsigned char *p = (unsigned char *) buffer;
	size_t done = 0;
	size_t i;
	int printed;

	if (caption)
		my_puts(caption);

	if (!length || !buffer) {
		my_puts("<absent>");

	} else
		while (length > done) {
			pline = line;
			/* Address */
			printed = sprintf(pline, "%0*zX ", ADDRESS_LENGTH, p - (unsigned char *) buffer);

			if (printed < 0)
				return;

			pline += printed;

			for (i = 0; i < BYTES_PER_LINE; i++) {
				/* Extra separator between every 8 bytes */
				if ((i % 8) == 0) {
					printed = sprintf(pline, " ");

					if (printed < 0)
						return;

					pline += printed;
				}

				/* Byte printed in hex */
				if (done + i >= length)
					printed = sprintf(pline, "   ");

				else
					printed = sprintf(pline, "%02X ", p[i]);

				if (printed < 0)
					return;

				pline += printed;
			}

			/* Left bar */
			printed = sprintf(pline, " |");

			if (printed < 0)
				return;

			pline += printed;

			/* Byte Printed in ASCII */
			for (i = 0; i < BYTES_PER_LINE; i++) {
				if (done + i >= length)
					printed = 0;

				else {
					if (isprint(p[i]))
						printed = sprintf(pline, "%c", p[i]);

					else
						printed = sprintf(pline, ".");
				}

				if (printed < 0)
					return;

				pline += printed;
			}

			/* Right bar */
			printed = sprintf(pline, "|");

			if (printed < 0)
				return;

			pline += printed;
			/* Terminator */
			*pline = '\0';
			my_puts(line);
			done += BYTES_PER_LINE;
			p += BYTES_PER_LINE;
		}
}
Example #23
0
/** \brief parse configuration file.
*
* \param[in,out] as Pointer to session handle
* \param[in] filename Path to the configuration file
* \return 0 if parsing was successful, -1 if an error occured.
*/
int parse_config_file(struct auto_handle *as, const char *filename) {
  FILE *fp = NULL;
  char *line = NULL;
  char opt[MAX_OPT_LEN + 1];
  char *param = NULL;
  char erbuf[100];
  char c;		/* for the "" and '' check */
  int line_num = 0;
  int line_pos;	/* line pos */
  int opt_pos;	/* opt pos */
  int param_pos;	/* param pos */
  int parse_error = 0;
  int opt_good = 0;
  int param_good = 0;
  struct stat fs;
  option_type type;

  if(stat(filename, &fs) == -1)  {
    return -1;
  }
  dbg_printf(P_INFO2, "Configuration file size: %d", fs.st_size);

  if ((fp = fopen(filename, "rb")) == NULL) {
    perror("fopen");
    return -1;
  }

  if ((line = am_malloc(fs.st_size + 1)) == NULL) {
    dbg_printf(P_ERROR, "Can't allocate memory for 'line': %s (%ldb)", strerror(errno), fs.st_size + 1);
    return -1;
  }

  if(fread(line, fs.st_size, 1, fp) != 1) {
    perror("fread");
    fclose(fp);
    am_free(line);
    return -1;
  }
  if(fp) {
    fclose(fp);
  }
  line_pos = 0;

  param = (char*)am_malloc(MAX_PARAM_LEN + 1);
  if(!param) {
    dbg_printf(P_ERROR, "Can't allocate memory for 'param': %s (%ldb)", strerror(errno), MAX_PARAM_LEN + 1);
    am_free(line);
    return -1;
  }

  while(line_pos != fs.st_size) {
    /* skip whitespaces */
    while (isspace(line[line_pos])) {
      if(line[line_pos] == '\n') {
        dbg_printf(P_INFO2, "skipping newline (line %d)", line_num);
        line_num++;
      }
      ++line_pos;
    }

    if(line_pos >= fs.st_size) {
      break;
    }

    /* comment */
    if (line[line_pos] == '#') {
      dbg_printf(P_INFO2, "skipping comment (line %d)", line_num);
      while (line[line_pos] != '\n') {
        ++line_pos;
      }
      ++line_num;
      ++line_pos;  /* skip the newline as well */
      continue;
    }

    /* read option */
    for (opt_pos = 0; isprint(line[line_pos]) && line[line_pos] != ' ' &&
      line[line_pos] != '#' && line[line_pos] != '='; /* NOTHING */) {
        opt[opt_pos++] = line[line_pos++];
        if (opt_pos >= MAX_OPT_LEN) {
          dbg_printf(P_ERROR, "too long option at line %d", line_num);
          parse_error = 1;
          opt_good = 0;
        }
    }
    if (opt_pos == 0 || parse_error == 1) {
      dbg_printf(P_ERROR, "parse error at line %d (pos: %d)", line_num, line_pos);
      parse_error = 1;
      break;
    } else {
      opt[opt_pos] = '\0';
      opt_good = 1;
    }
    /* skip whitespaces */
    while (isspace(line[line_pos])) {
      if(line[line_pos] == '\n') {
        line_num++;
        dbg_printf(P_INFO2, "skipping newline (line %d)", line_num);
      }
      ++line_pos;
    }

    if(line_pos >= fs.st_size) {
      break;
    }

    /* check for '=' */
    if (line[line_pos++] != '=') {
      snprintf(erbuf, sizeof(erbuf), "Option '%s' needs a parameter (line %d)", opt, line_num);
      parse_error = 1;
      break;
    }

    /* skip whitespaces */
    while (isspace(line[line_pos])) {
      if(line[line_pos] == '\n') {
        line_num++;
        dbg_printf(P_INFO2, "skipping newline (line %d)", line_num);
      }
      ++line_pos;
    }

    if(line_pos >= fs.st_size) {
      break;
    }

    /* read the parameter */

    /* case 1: single string, no linebreaks allowed */
    if (line[line_pos] == '"' || line[line_pos] == '\'') {
      c = line[line_pos]; /* single or double quote */
      ++line_pos;  /* skip quote */
      parse_error = 0;
      for (param_pos = 0; line[line_pos] != c; /* NOTHING */) {
        if(line_pos < fs.st_size && param_pos < MAX_PARAM_LEN && line[line_pos] != '\n') {
          param[param_pos++] = line[line_pos++];
        } else {
          snprintf(erbuf, sizeof(erbuf), "Option %s has a too long parameter (line %d)\n",opt, line_num);
          parse_error = 1;
          break;
        }
      }
      if(parse_error == 0) {
        line_pos++;	/* skip the closing " or ' */
        type = CONF_TYPE_STRING;
      } else {
        break;
      }
      /* case 2: multiple items, linebreaks allowed */
    } else if (line[line_pos] == '{') {
      dbg_printf(P_INFO2, "reading multiline param", line_num);
      ++line_pos;
      parse_error = 0;
      for (param_pos = 0; line[line_pos] != '}'; /* NOTHING */) {
        if(line_pos < fs.st_size && param_pos < MAX_PARAM_LEN) {
          param[param_pos++] = line[line_pos++];
          if(line[line_pos] == '\n')
            line_num++;
        } else {
          snprintf(erbuf, sizeof(erbuf), "Option %s has a too long parameter (line %d)\n", opt, line_num);
          parse_error = 1;
          break;
        }
      }
      dbg_printf(P_INFO2, "multiline param: param_good=%d", param_good);
      if(parse_error == 0) {
        line_pos++;	/* skip the closing '}' */
        type = CONF_TYPE_STRINGLIST;
      } else {
        break;
      }
      /* Case 3: integers */
    } else {
      parse_error = 0;
      for (param_pos = 0; isprint(line[line_pos]) && !isspace(line[line_pos])
        && line[line_pos] != '#'; /* NOTHING */) {
          param[param_pos++] = line[line_pos++];
          if (param_pos >= MAX_PARAM_LEN) {
            snprintf(erbuf, sizeof(erbuf), "Option %s has a too long parameter (line %d)\n", opt, line_num);
            parse_error = 1;
            break;
          }
      }
      if(parse_error == 0) {
        type = CONF_TYPE_INT;
      } else {
        break;
      }
    }
    param[param_pos] = '\0';
    dbg_printf(P_INFO2, "[parse_config_file] option: %s", opt);
    dbg_printf(P_INFO2, "[parse_config_file] param: %s (%d byte)", param, strlen(param));
    dbg_printf(P_INFO2, "[parse_config_file] -----------------");
    set_option(as, opt, param, type);

    /* skip whitespaces */
    while (isspace(line[line_pos])) {
      if(line[line_pos] == '\n')
        line_num++;
      ++line_pos;
    }
    if(line_pos >= fs.st_size) {
      break;
    }
  }

  am_free(line);
  am_free(param);

  return (parse_error == 1) ? -1 : 0;
}
Example #24
0
int main (int argc, char **argv) {
    char c;
    unsigned int width = 1920;
    unsigned int height = 2520;
    int is_rgb = 0;
    unsigned int rounds = -1;
    char *fname = (char*)"waterfall_grey_1920_2520.raw", *filtstr = (char*)"1,2,1,2,4,2,1,2,1";

    printf("Options:\n"
        "\t-f file\t\tSet the name of the image file\n"
        "\t-w width\tSet the width of the image\n"
        "\t-h height\tSet the height of the image\n"
        "\t-c\t\tSpecify an RGB image\n"
        "\t-v filter\tNine comma separated coefficients for the convolution filter (left to right, up to down)\n"
        "\t-r rounds\tNumber of rounds to run the algorithm (will run until convergence if not specified)\n"
    );

    // parse parameters
    opterr = 0;
    while ((c = getopt (argc, argv, "f:w:h:cv:r:")) != -1)
        switch (c) {
        case 'f':
        fname = optarg;
        break;
        case 'w':
        width = atoi(optarg);
        break;
        case 'h':
        height = atoi(optarg);
        break;
        case 'c':
        is_rgb = 1;
        break;
        case 'v':
        filtstr = optarg;
        break;
        case 'r':
        rounds = atoi(optarg);
        break;
        case '?':
        if (isprint (optopt))
            fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
            fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);
        return 1;
        default:
        abort ();
    }

    printf("Running with parameters:\nfilename = %s, width = %d, height = %d, RGB = %s, filter = %s, rounds = %d\n",
        fname, width, height, is_rgb == 0 ? "no" : "yes", filtstr, rounds);

    // calculate file size
    unsigned int fsize = width * height;
    if (is_rgb == 1)
        fsize *= 3;
    unsigned char *file_buf = (unsigned char*) malloc(fsize);

    FILE *f_input = fopen(fname, "rb");
    unsigned int bytes_read = 0;
    while (bytes_read < fsize)
        bytes_read += fread(&file_buf[bytes_read], 1, fsize - bytes_read, f_input);
    fclose(f_input);

    unsigned short flt[9];

    // read filter from the string
    char *filtstr_dup = strdup(filtstr);
    char *token = strtok(filtstr_dup, ",");
    if (token != NULL) {
        for (int i = 0; i < 9 && token != NULL; i++) {
            flt[i] = atoi(token);
            token = strtok(NULL, ",");
        }
    }
    free(filtstr_dup);

    // run the CUDA code and print the time
    printf("Elapsed time: %f\n", convolutionGPU(width, height, flt, is_rgb, rounds, fsize, file_buf));

    FILE *f_out = fopen("out.raw", "wb");
    fwrite(file_buf, 1, fsize, f_out);
    fclose(f_out);

    free(file_buf);

    return 0;
}
Example #25
0
int PR_IsEmptyString(const char * s) {

//   if(*s > 0x20) { return(0); }
   if(isprint(*s)) { return(0); }
   else { return(1); }
}
Example #26
0
int main (int argc, char **argv)
{
	int do_get = 0;
	int do_set = 0;
	char *pvalue = NULL;
	pid_t pid=0;
	int priority=0;
	int policy = -1;
	int index;
	int c;

	printf("sched_pp (V1.0) (c) M.Behr, 2013\n");
	opterr = 0;

	while ((c = getopt (argc, argv, "gs:p:P:")) != -1)
		switch (c)
		{
		case 'g':
			do_get = 1;
			break;
		case 's':
			do_set = 1;
			priority = atol(optarg);
			break;
		case 'p':
			pvalue = optarg;
			pid=atol(pvalue);
			break;
		case 'P':
			if (!strcmp(optarg, "SCHED_FIFO")) policy = SCHED_FIFO;
			else if (!strcmp(optarg, "SCHED_RR")) policy = SCHED_RR;
			else if (!strcmp(optarg, "SCHED_OTHER")) policy = SCHED_OTHER;
			else{
				fprintf(stderr, "Unknown policy <%s>.\n", optarg);
				return 2;
			}
			break;
		case '?':
			if (optopt == 'p' || optopt == 's' || optopt == 'P')
				fprintf (stderr, "Option -%c requires an argument.\n", optopt);
			else if (isprint (optopt))
				fprintf (stderr, "Unknown option `-%c'.\n", optopt);
			else
				fprintf (stderr,
						"Unknown option character `\\x%x'.\n",
						optopt);
			return 1;
		default:
			abort ();
		}

	for (index = optind; index < argc; index++)
		printf ("Non-option argument %s\n", argv[index]);

	if (!do_get && !do_set){
		printf("Usage:\nsched_pp -p <pid> [-g] [-s <priority>] [-P<policy=SCHED_FIFO|SCHED_RR|SCHED_OTHER>]\n");
	}

	if (do_get){
		print_params(pid, 0);
	}

	if (do_set){
		int cur_policy;
		/* print before */
		print_params(pid, &cur_policy);

		if (policy != -1){
			printf("trying to change pid %d to policy %d and priority %d:\n", pid, policy, priority);
			if (policy != SCHED_OTHER)
				set_policy(pid, policy, priority);
			else{
				set_policy(pid, policy, 0); /* SCHED_OTHER only allows 0 for that priority */
				set_priority(pid, policy, priority);
			}

		}else{
			printf("trying to change pid %d to priority %d:\n Params now:\n", pid, priority);
			set_priority(pid, cur_policy, priority);
		}
		/* print afterwards */
		print_params(pid, 0);
	}

	return 0;
}
Example #27
0
/**
 * Main routine, start of the program execution.
 * \param argc the number of arguments
 * \param argv pointer to the arguments array
 * \return don't return on sucess, -1 on error
 * \see main_loop
 */
int main(int argc, char** argv)
{
	/* configure by default logging to syslog */
	int cfg_log_stderr = 1;
	FILE* cfg_stream;
	int c,r;
	char *tmp;
	int tmp_len;
	int port;
	int proto;
	char *options;
	int ret;
	unsigned int seed;
	int rfd;

	/*init*/
	ret=-1;
	my_argc=argc; my_argv=argv;

	/* process pkg mem size from command line */
	opterr=0;
	options="f:cCm:M:b:l:n:N:rRvdDFETSVhw:t:u:g:P:G:W:o:";

	while((c=getopt(argc,argv,options))!=-1){
		switch(c){
			case 'M':
					pkg_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
					if (tmp &&(*tmp)){
						LM_ERR("bad pkgmem size number: -m %s\n", optarg);
						goto error00;
					};

					break;
		}
	}
	/*init pkg mallocs (before parsing cfg but after parsing cmd line !)*/
	if (init_pkg_mallocs()==-1)
		goto error00;

	init_route_lists();

	/* process command line (get port no, cfg. file path etc) */
	/* first reset getopt */
	optind = 1;
	while((c=getopt(argc,argv,options))!=-1){
		switch(c){
			case 'f':
					cfg_file=optarg;
					break;
			case 'C':
					config_check |= 2;
			case 'c':
					if (config_check==3)
						break;
					config_check |= 1;
					cfg_log_stderr=1; /* force stderr logging */
					break;
			case 'm':
					shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
					if (tmp &&(*tmp)){
						LM_ERR("bad shmem size number: -m %s\n", optarg);
						goto error00;
					};
					break;
			case 'M':
					/* ignoring it, parsed previously */
					break;
			case 'b':
					maxbuffer=strtol(optarg, &tmp, 10);
					if (tmp &&(*tmp)){
						LM_ERR("bad max buffer size number: -b %s\n", optarg);
						goto error00;
					}
					break;
			case 'l':
					if (parse_phostport(optarg, strlen(optarg), &tmp, &tmp_len,
											&port, &proto)<0){
						LM_ERR("bad -l address specifier: %s\n", optarg);
						goto error00;
					}
					tmp[tmp_len]=0; /* null terminate the host */
					/* add a new addr. to our address list */
					if (add_cmd_listener(tmp, port, proto)!=0){
						LM_ERR("failed to add new listen address\n");
						goto error00;
					}
					break;
			case 'n':
					children_no=strtol(optarg, &tmp, 10);
					if ((tmp==0) ||(*tmp)){
						LM_ERR("bad process number: -n %s\n", optarg);
						goto error00;
					}
					break;
			case 'v':
					check_via=1;
					break;
			case 'r':
					received_dns|=DO_DNS;
					break;
			case 'R':
					received_dns|=DO_REV_DNS;
				    break;
			case 'd':
					*log_level = debug_mode ? L_DBG : (*log_level)+1;
					break;
			case 'D':
					debug_mode=1;
					*log_level = L_DBG;
					break;
			case 'F':
					no_daemon_mode=1;
					break;
			case 'E':
					cfg_log_stderr=1;
					break;
			case 'N':
					tcp_children_no=strtol(optarg, &tmp, 10);
					if ((tmp==0) ||(*tmp)){
						LM_ERR("bad process number: -N %s\n", optarg);
						goto error00;
					}
					break;
			case 'W':
					io_poll_method=get_poll_type(optarg);
					if (io_poll_method==POLL_NONE){
						LM_ERR("bad poll method name: -W %s\ntry "
							"one of %s.\n", optarg, poll_support);
						goto error00;
					}
					break;
			case 'V':
					printf("version: %s\n", version);
					printf("flags: %s\n", flags );
					print_ct_constants();
					printf("%s compiled on %s with %s\n", __FILE__,
							compiled, COMPILER );
					exit(0);
					break;
			case 'h':
					printf("version: %s\n", version);
					printf("%s",help_msg);
					exit(0);
					break;
			case 'w':
					working_dir=optarg;
					break;
			case 't':
					chroot_dir=optarg;
					break;
			case 'u':
					user=optarg;
					break;
			case 'g':
					group=optarg;
					break;
			case 'P':
					pid_file=optarg;
					break;
			case 'G':
					pgid_file=optarg;
					break;
			case 'o':
					if (add_arg_var(optarg) < 0)
						LM_ERR("cannot add option %s\n", optarg);
					break;
			case '?':
					if (isprint(optopt))
						LM_ERR("Unknown option `-%c`.\n", optopt);
					else
						LM_ERR("Unknown option character `\\x%x`.\n", optopt);
					goto error00;
			case ':':
					LM_ERR("Option `-%c` requires an argument.\n", optopt);
					goto error00;
			default:
					abort();
		}
	}

	log_stderr = cfg_log_stderr;

	/* fill missing arguments with the default values*/
	if (cfg_file==0) cfg_file=CFG_FILE;

	/* load config file or die */
	cfg_stream=fopen (cfg_file, "r");
	if (cfg_stream==0){
		LM_ERR("loading config file(%s): %s\n", cfg_file,
				strerror(errno));
		goto error00;
	}

	/* seed the prng, try to use /dev/urandom if possible */
	/* no debugging information is logged, because the standard
	   log level prior the config file parsing is L_NOTICE */
	seed=0;
	if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){
try_again:
		if (read(rfd, (void*)&seed, sizeof(seed))==-1){
			if (errno==EINTR) goto try_again; /* interrupted by signal */
			LM_WARN("could not read from /dev/urandom (%d)\n", errno);
		}
		LM_DBG("initialize the pseudo random generator from "
			"/dev/urandom\n");
		LM_DBG("read %u from /dev/urandom\n", seed);
			close(rfd);
	}else{
		LM_WARN("could not open /dev/urandom (%d)\n", errno);
		LM_WARN("using a unsafe seed for the pseudo random number generator");
	}
	seed+=getpid()+time(0);
	LM_DBG("seeding PRNG with %u\n", seed);
	srand(seed);
	LM_DBG("test random number %u\n", rand());

	/*register builtin  modules*/
	register_builtin_modules();

	/* init avps */
	if (init_global_avps() != 0) {
		LM_ERR("error while initializing avps\n");
		goto error;
	}

	/* used for parser debugging */
#ifdef DEBUG_PARSER
	yydebug = 1;
#endif

	/*
	 * initializes transport interfaces - we initialize them here because we
	 * can have listening interfaces declared in the command line
	 */
	if (trans_init() < 0) {
		LM_ERR("cannot initialize transport interface\n");
		goto error;
	}

		/* get uid/gid */
	if (user){
		if (user2uid(&uid, &gid, user)<0){
			LM_ERR("bad user name/uid number: -u %s\n", user);
			goto error00;
		}
	}
	if (group){
		if (group2gid(&gid, group)<0){
			LM_ERR("bad group name/gid number: -u %s\n", group);
			goto error00;
		}
	}

		/*init shm mallocs
	 *  this must be here
	 *     -to allow setting shm mem size from the command line
	 *     -it must be also before init_timer and init_tcp
	 *     -it must be after we know uid (so that in the SYSV sems case,
	 *        the sems will have the correct euid)
	 * --andrei */
	if (init_shm_mallocs()==-1)
		goto error;

	if (init_stats_collector() < 0) {
		LM_ERR("failed to initialize statistics\n");
		goto error;
	}

	/* parse the config file, prior to this only default values
	   e.g. for debugging settings will be used */
	yyin=cfg_stream;
	if ((yyparse()!=0)||(cfg_errors)){
		LM_ERR("bad config file (%d errors)\n", cfg_errors);
		goto error00;
	}

	if (config_check>1 && check_rls()!=0) {
		LM_ERR("bad function call in config file\n");
		return ret;
	}

	if (solve_module_dependencies(modules) != 0) {
		LM_ERR("failed to solve module dependencies\n");
		return -1;
	}

	/* init the resolver, before fixing the config */
	resolv_init();

	fix_poll_method( &io_poll_method );

	/* fix temporary listeners added in the cmd line */
	if (fix_cmd_listeners() < 0) {
		LM_ERR("cannot add temproray listeners\n");
		return ret;
	}

	/* load transport protocols */
	if (trans_load() < 0) {
		LM_ERR("cannot load transport protocols\n");
		goto error;
	}

	/* fix parameters */
	if (working_dir==0) working_dir="/";

	if (fix_all_socket_lists()!=0){
		LM_ERR("failed to initialize list addresses\n");
		goto error00;
	}
	/* print all the listen addresses */
	printf("Listening on \n");
	print_all_socket_lists();
	printf("Aliases: \n");
	/*print_aliases();*/
	print_aliases();
	printf("\n");

	if (config_check){
		LM_NOTICE("config file ok, exiting...\n");
		return 0;
	}

	time(&startup_time);

	/* Init statistics */
	init_shm_statistics();

	/*init UDP networking layer*/
	if (udp_init()<0){
		LM_CRIT("could not initialize tcp\n");
		goto error;
	}
	/*init TCP networking layer*/
	if (tcp_init()<0){
		LM_CRIT("could not initialize tcp\n");
		goto error;
	}

	if (create_status_pipe() < 0) {
		LM_ERR("failed to create status pipe\n");
		goto error;
	}

	if (debug_mode) {

		LM_NOTICE("DEBUG MODE activated\n");
		if (no_daemon_mode==0) {
			LM_NOTICE("disabling daemon mode (found enabled)\n");
			no_daemon_mode = 1;
		}
		if (log_stderr==0) {
			LM_NOTICE("enabling logging to standard error (found disabled)\n");
			log_stderr = 1;
		}
		if (*log_level<L_DBG) {
			LM_NOTICE("setting logging to debug level (found on %d)\n",
				*log_level);
			*log_level = L_DBG;
		}
		if (disable_core_dump) {
			LM_NOTICE("enabling core dumping (found off)\n");
			disable_core_dump = 0;
		}
		if (udp_count_processes()!=0) {
			if (children_no!=2) {
				LM_NOTICE("setting UDP children to 2 (found %d)\n",
					children_no);
				children_no = 2;
			}
		}
		if (tcp_count_processes()!=0) {
			if (tcp_children_no!=2) {
				LM_NOTICE("setting TCP children to 2 (found %d)\n",
					tcp_children_no);
				tcp_children_no = 2;
			}
		}

	} else { /* debug_mode */

		/* init_daemon */
		if ( daemonize((log_name==0)?argv[0]:log_name, &own_pgid) <0 )
			goto error;

	}

	/* install signal handlers */
	if (install_sigs() != 0){
		LM_ERR("could not install the signal handlers\n");
		goto error;
	}

	if (disable_core_dump) set_core_dump(0, 0);
	else set_core_dump(1, shm_mem_size+pkg_mem_size+4*1024*1024);
	if (open_files_limit>0) {
		if(set_open_fds_limit()<0){
			LM_ERR("ERROR: error could not increase file limits\n");
			goto error;
		}
	}

	/* print OpenSIPS version to log for history tracking */
	LM_NOTICE("version: %s\n", version);

	/* print some data about the configuration */
	LM_INFO("using %ld Mb shared memory\n", ((shm_mem_size/1024)/1024));
	LM_INFO("using %ld Mb private memory per process\n",
		((pkg_mem_size/1024)/1024));

	/* init async reactor */
	if (init_reactor_size()<0) {
		LM_CRIT("failed to init internal reactor, exiting...\n");
		goto error;
	}

	/* init timer */
	if (init_timer()<0){
		LM_CRIT("could not initialize timer, exiting...\n");
		goto error;
	}

	/* init serial forking engine */
	if (init_serialization()!=0) {
		LM_ERR("failed to initialize serialization\n");
		goto error;
	}
	/* Init MI */
	if (init_mi_core()<0) {
		LM_ERR("failed to initialize MI core\n");
		goto error;
	}

	/* Register core events */
	if (evi_register_core() != 0) {
		LM_ERR("failed register core events\n");
		goto error;
	}

	/* init black list engine */
	if (init_black_lists()!=0) {
		LM_CRIT("failed to init blacklists\n");
		goto error;
	}
	/* init resolver's blacklist */
	if (resolv_blacklist_init()!=0) {
		LM_CRIT("failed to create DNS blacklist\n");
		goto error;
	}

	/* init modules */
	if (init_modules() != 0) {
		LM_ERR("error while initializing modules\n");
		goto error;
	}

	/* register route timers */
	if(register_route_timers() < 0) {
		LM_ERR("Failed to register timer\n");
		goto error;
	}

	/* check pv context list */
	if(pv_contextlist_check() != 0) {
		LM_ERR("used pv context that was not defined\n");
		goto error;
	}

	/* init query list now in shm
	 * so all processes that will be forked from now on
	 * will have access to it
	 *
	 * if it fails, give it a try and carry on */
	if (init_ql_support() != 0) {
		LM_ERR("failed to initialise buffering query list\n");
		query_buffer_size = 0;
		*query_list = NULL;
	}

	/* init multi processes support */
	if (init_multi_proc_support()!=0) {
		LM_ERR("failed to init multi-proc support\n");
		goto error;
	}

	#ifdef PKG_MALLOC
	/* init stats support for pkg mem */
	if (init_pkg_stats(counted_processes)!=0) {
		LM_ERR("failed to init stats for pkg\n");
		goto error;
	}
	#endif

	/* init avps */
	if (init_extra_avps() != 0) {
		LM_ERR("error while initializing avps\n");
		goto error;
	}

	/* fix routing lists */
	if ( (r=fix_rls())!=0){
		LM_ERR("failed to fix configuration with err code %d\n", r);
		goto error;
	}

	if (init_log_level() != 0) {
		LM_ERR("failed to init logging levels\n");
		goto error;
	}

	if (trans_init_all_listeners()<0) {
		LM_ERR("failed to init all SIP listeners, aborting\n");
		goto error;
	}

	/* all processes should have access to all the sockets (for sending)
	 * so we open all first*/
	if (do_suid(uid, gid)==-1)
		goto error;

	ret = main_loop();

error:
	/*kill everything*/
	kill_all_children(SIGTERM);
	/*clean-up*/
	cleanup(0);
error00:
	LM_NOTICE("Exiting....\n");
	return ret;
}
Example #28
0
int main(int argc, char **argv) {

	int arg, refresh_interval, i;
	struct timeval t1, t2;
	time_t elapsed_time;

	first_run = 1;
	refresh_interval = 1000;

	while((arg = getopt(argc, argv, "t:h"))!=-1) {
		switch(arg) {
			case 't':
				if((sscanf(optarg, "%d", &refresh_interval))) refresh_interval = refresh_interval*1000;
				else {
					fprintf(stderr, "Update interval must be an integer value\n");
					print_usage(1);
					return 1;
				}
				break;
			case 'h':
				print_usage(0);
				return 0;
				break;
			case '?':
				if(isprint(optopt)) {
					print_usage(1);
					return 1;
				}
				else printf("Unknown error parsing command line arguments: 0x%08x\n", optopt);
				break;
			default:
				break;
		}
	}

	for(i=optind; i<argc; i++) printf("Useless command line argument: %s\n", argv[i]);

	printf("{\"version\":1}\n");
	printf("[[],\n");

	conf();

	while(1) {
		gettimeofday(&t1, NULL);

		fflush(stdout);
		printf("[\n");

		update();

		printf("{\"full_text\":\"\"}");

		printf("],\n");

		gettimeofday(&t2, NULL);
		elapsed_time = ((t2.tv_sec-t1.tv_sec)*1000)+((t2.tv_usec-t1.tv_usec)/1000);
		if(elapsed_time<refresh_interval) usleep((useconds_t)(refresh_interval-elapsed_time)*1000);
	}

	return 0;
}
Example #29
0
void lexer_parser(parser &p, const char *s)
{
    MSG("[DEBUG] lexer_parser()\n");
    char *ptr = (char *)s;

    while(*ptr != '\0') {
        while(*ptr == ' ')
            ptr++;
        if(*(ptr+1) == '\0') {

        }
        if(isalpha(*ptr)) {
            char *begin = ptr;
            MSG("isalpha!\n");
            
            while((isalpha(*ptr) || isdigit(*ptr)) && ((ptr-begin) < 63)) {
            	MSG("%c\n", *ptr); ptr++;
            }
            
            p.tokens[p.num_tokens].type = IDENTIFIER;
            p.tokens[p.num_tokens].data = (char*)malloc(sizeof(char) * (ptr-begin));
            textcpy(begin, p.tokens[p.num_tokens].data, (ptr-begin));
            ptr--;
            p.num_tokens++;
        } else if(isdigit(*ptr)) {
            MSG("isdigit! : ");
            char *begin = ptr;
            while(isdigit(*ptr))
                ptr++;

            if(*ptr == '.') {
                if(isdigit(*(ptr+1)))
                    ptr++;
                while(isdigit(*ptr))
                    ptr++;
                MSG("float num\n");
                p.tokens[p.num_tokens].type = FLOAT_NUMBER;
            } else {
                MSG("int num\n");
                p.tokens[p.num_tokens].type = INT_NUMBER;
            }
            p.tokens[p.num_tokens].data = (char*) malloc(sizeof(char) * (ptr - begin));
            textcpy(begin, p.tokens[p.num_tokens].data, (ptr - begin));
            ptr--;
            p.num_tokens++;
        } else if(isprint(*ptr)) {
            MSG("isprint! : ");
            switch(*ptr) {

            case '(':
                MSG("(\n");
                p.tokens[p.num_tokens].type = PARENTHESIS_LEFT;
                p.tokens[p.num_tokens].data = (char*)malloc(sizeof(char) * 1);
                textcpy(ptr, p.tokens[p.num_tokens].data, 1);
                break;

            case ')':
                MSG(")\n");
                p.tokens[p.num_tokens].type = PARENTHESIS_RIGHT;
                p.tokens[p.num_tokens].data = (char*)malloc(sizeof(char) * 1);
                textcpy(ptr, p.tokens[p.num_tokens].data, 1);
                break;

            case '!':
                MSG("!\n");
                p.tokens[p.num_tokens].type = EXL;
                p.tokens[p.num_tokens].data = (char *)malloc(sizeof(char) * 1);
                textcpy(ptr, p.tokens[p.num_tokens].data, 1);
                break;

            case '^':
                MSG("^\n");
                p.tokens[p.num_tokens].type = CARET;
                p.tokens[p.num_tokens].data = (char*)malloc(sizeof(char) * 1);
                textcpy(ptr, p.tokens[p.num_tokens].data, 1);
                break;

            case '*':
                MSG("*\n");
                p.tokens[p.num_tokens].type = MULT;
                p.tokens[p.num_tokens].data = (char*)malloc(sizeof(char) * 1);
                textcpy(ptr, p.tokens[p.num_tokens].data, 1);
                break;

            case '/':
                MSG("/\n");
                p.tokens[p.num_tokens].type = DIV;
                p.tokens[p.num_tokens].data = (char*)malloc(sizeof(char) * 1);
                textcpy(ptr, p.tokens[p.num_tokens].data, 1);
                break;

            case '+':
                MSG("+\n");
                p.tokens[p.num_tokens].type = PLUS;
                p.tokens[p.num_tokens].data = (char*)malloc(sizeof(char) * 1);
                textcpy(ptr, p.tokens[p.num_tokens].data, 1);
                break;

            case '-':
                MSG("-\n");
                p.tokens[p.num_tokens].type = MINUS;
                p.tokens[p.num_tokens].data = (char*)malloc(sizeof(char) * 1);
                textcpy(ptr, p.tokens[p.num_tokens].data, 1);
                break;

            default:
                MSG("undefined token\n");
                return;
            };
            p.num_tokens++;
        }
        ptr++;
        if(*ptr == '\0') {
            MSG("null_symbol\n");
            p.tokens[p.num_tokens].data = (char*)malloc(sizeof(char) * 1);
            textcpy("]", p.tokens[p.num_tokens].data, 1);
            p.num_tokens++;
        }
    }
    MSG("close : lexer_parser()\n");
}
Example #30
0
bool PhpFunction::ctype_print(char text)
{
    PhpFunction::reset_function_execute_status("ctype/ctype_print: char");

    return (isprint(text) ? TRUE : FALSE);
}