Пример #1
0
static void process_buffer(struct synth_t *s, char *buf, ssize_t length)
{
	int start;
	int end;
	char txtBuf[maxBufferSize];
	size_t txtLen;

	start = 0;
	end = 0;
	while (start < length) {
		while ((buf[end] < 0 || buf[end] >= ' ') && end < length)
			end++;
		if (end != start) {
			txtLen = end - start;
			strncpy(txtBuf, buf + start, txtLen);
			*(txtBuf + txtLen) = 0;
			queue_add_text(txtBuf, txtLen);
		}
		if (end < length)
			start = end = end + process_command(s, buf, end);
		else
			start = length;
	}
}
Пример #2
0
void Parser::process_input(string _input)
{
  try
  {
    // Tokenize the input, divide the string input into minimal units
    tokenizer.tokenize_input(_input);
    
    string token;

    // Check if there is any token
    if(tokenizer.remaining_tokens() > 0)
    {
      token = tokenizer.peek();
    }
    else
    {
      // Most likely blank line, return
      return;
    }

    InputType type = get_input_type(token);
    switch(type)
    {
    case QUERY:
      process_query();
      break;
    default:
      process_command(type);
      break;
    }
  }
  catch(exception& e)
  {
    cout << "Exception: " << e.what() << endl;
  }
}
Пример #3
0
int RASocket::svc(void)
{
    //! Subnegotiation may differ per client - do not react on it
    subnegotiate();

    if (send("Authentication required\r\n") == -1)
        return -1;

    if (authenticate() == -1)
    {
        (void) send("Authentication failed\r\n");
        return -1;
    }

    // send motd
    if (send(std::string(sWorld->GetMotd()) + "\r\n") == -1)
        return -1;

    for (;;)
    {
        // show prompt
        const char* tc_prompt = "TC> ";
        if (size_t(peer().send(tc_prompt, strlen(tc_prompt))) != strlen(tc_prompt))
            return -1;

        std::string line;

        if (recv_line(line) == -1)
            return -1;

        if (process_command(line) == -1)
            return -1;
    }

    return 0;
}
/*
	main

	Initiate communication with the XBee module, then accept AT commands from
	STDIO, pass them to the XBee module and print the result.
*/
int main( void)
{
   char cmdstr[80];
	int status;
	int i;
	xbee_node_id_t *target = NULL;


	// initialize the serial and device layer for this XBee device
	if (xbee_dev_init( &my_xbee, &XBEE_SERPORT, xbee_awake_pin, xbee_reset_pin))
	{
		printf( "Failed to initialize device.\n");
		return 0;
	}

	// Initialize the WPAN layer of the XBee device driver.  This layer enables
	// endpoints and clusters, and is required for all ZigBee layers.
	xbee_wpan_init( &my_xbee, sample_endpoints);

	// Register handler to receive Node ID messages
	xbee_disc_add_node_id_handler( &my_xbee, &node_discovered);

	// Initialize the AT Command layer for this XBee device and have the
	// driver query it for basic information (hardware version, firmware version,
	// serial number, IEEE address, etc.)
	xbee_cmd_init_device( &my_xbee);
	printf( "Waiting for driver to query the XBee device...\n");
	do {
		xbee_dev_tick( &my_xbee);
		status = xbee_cmd_query_status( &my_xbee);
	} while (status == -EBUSY);
	if (status)
	{
		printf( "Error %d waiting for query to complete.\n", status);
	}

	// report on the settings
	xbee_dev_dump_settings( &my_xbee, XBEE_DEV_DUMP_FLAG_DEFAULT);

	print_menu();
	xbee_disc_discover_nodes( &my_xbee, NULL);

   while (1)
   {
      while (xbee_readline( cmdstr, sizeof cmdstr) == -EAGAIN)
      {
      	wpan_tick( &my_xbee.wpan_dev);
      	xbee_cmd_tick();
      }

		if (! strcmpi( cmdstr, "help") || ! strcmp( cmdstr, "?"))
		{
			print_menu();
		}
		else if (! strncmpi( cmdstr, "nd", 2))
      {
			// Initiate discovery for a specified node id (as parameter in command
			// or all node IDs.
			if (cmdstr[2] == ' ')
			{
				printf( "Looking for node [%s]...\n", &cmdstr[3]);
				xbee_disc_discover_nodes( &my_xbee, &cmdstr[3]);
			}
			else
			{
				puts( "Discovering nodes...");
				xbee_disc_discover_nodes( &my_xbee, NULL);
			}
      }
      else if (! strcmpi( cmdstr, "quit"))
      {
			return 0;
		}
      else if (! strncmpi( cmdstr, "AT", 2))
      {
			process_command( &my_xbee, cmdstr);
	   }
	   else if (! strcmpi( cmdstr, "target"))
	   {
	   	node_table_dump();
	   }
	   else if (! strncmpi( cmdstr, "target", 6))
	   {
	   	target = node_by_name( &cmdstr[7]);
	   	if (target == NULL)
	   	{
	   		printf( "couldn't find a target named '%s'\n", &cmdstr[7]);
	   	}
	   	else
	   	{
	   		printf( "target: ");
	   		xbee_disc_node_id_dump( target);
	   	}
	   }
	   else
	   {
	   	if (target == NULL)
	   	{
	   		puts( "you must first select a target with the `target` command");
	   	}
	   	else
	   	{
	   		i = strlen( cmdstr);
	   		printf( "sending %u bytes to '%s'\n", i, target->node_info);
	   		send_data( target, cmdstr, i);
	   	}
	   }
   }
}
Пример #5
0
void server::collect_inputs()
{
  out_socket *collect_server=NULL;
  for (view *f=player_list; f; )
  {
    view *next=f->next;
    if (is_server)
    {
      if (f->connect)
      {
    packet pk;
    if (get_pkt(f->connect,pk))
    {
      while (!pk.eop())
      {
        uint8_t cmd;
        if (pk.read((uint8_t *)&cmd,1)==1)
          if (!process_command(f,cmd,pk))
          { remove_player(f); f=NULL; }
      }
    } else
    {
      remove_player(f);
      f=NULL;
    }

      } else
      {
        f->get_input();
    add_change_log(f,next_out,1);
      }
    }
    else
    {
      if (f->local_player())
      {
        f->get_input();
    if (f->connect && !send_inputs(f))
          remove_from_server(f);
    else if (f->connect)
          collect_server=f->connect;  // take note that we should collect the input back from the server
      }
    }
    f=next;
  }

  if (collect_server)
  {
    packet pk;
    if (!get_pkt(collect_server,pk))
    {
      for (view *f=player_list; f; f=f->next)
        if (f->local_player())
      remove_from_server(f);
    }

    if (!client_do_packet(pk))
      printf("Error occurred while processing packet from server\n");
  }

  if (is_server && in)
    distribute_changes();

}
Пример #6
0
int
main(int argc, char *argv[])
{
	int c;
	FILE *f;
	int s;
	union {
	    struct sockaddr sa;
#if defined(AF_INET6) /*[*/
	    struct sockaddr_in6 sin6;
#else /*][*/
	    struct sockaddr_in sin;
#endif /*]*/
	} addr;
#if defined(AF_INET6) /*[*/
	int proto = AF_INET6;
#else /*][*/
	int proto = AF_INET;
#endif /*]*/
	int addrlen = sizeof(addr);
	int one = 1;
	socklen_t len;
	int flags;

	/* Parse command-line arguments */

	if ((me = strrchr(argv[0], '/')) != NULL) {
		me++;
	} else {
		me = argv[0];
	}

	while ((c = getopt(argc, argv, "p:")) != -1) {
		switch (c) {
		    case 'p':
			port = atoi(optarg);
			break;
		    default:
			usage();
		}
	}

	if (argc - optind != 1) {
		usage();
	}

	/* Open the file. */
	f = fopen(argv[optind], "r");
	if (f == NULL) {
		perror(argv[optind]);
		exit(1);
	}

	/* Listen on a socket. */
	s = socket(proto, SOCK_STREAM, 0);
	if (s < 0) {
		perror("socket");
		exit(1);
	}
	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&one,
	    sizeof(one)) < 0) {
		perror("setsockopt");
		exit(1);
	}
	(void) memset(&addr, '\0', sizeof(addr));
	addr.sa.sa_family = proto;
#if defined(AF_INET6) /*[*/
	addr.sin6.sin6_port = htons(port);
#else /*][*/
	addr.sin.sin_port = htons(port);
#endif /*]*/
	if (bind(s, &addr.sa, addrlen) < 0) {
		perror("bind");
		exit(1);
	}
	if (listen(s, 1) < 0) {
		perror("listen");
		exit(1);
	}
	if ((flags = fcntl(s, F_GETFL)) < 0) {
		perror("fcntl(F_GETFD)");
		exit(1);
	}

	if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0) {
		perror("fcntl(F_SETFD)");
		exit(1);
	}
	(void) signal(SIGPIPE, SIG_IGN);

	/* Accept connections and process them. */
	for (;;) {
		int s2;
#if defined(AF_INET6) /*[*/
		char buf[INET6_ADDRSTRLEN];
#endif /*]*/

		(void) memset((char *)&addr, '\0', sizeof(addr));

		addr.sa.sa_family = proto;
		len = addrlen;
		(void) printf("Waiting for connection on port %u.\n", port);
		for (;;) {
			fd_set rfds;
			int ns;

			FD_ZERO(&rfds);
			FD_SET(0, &rfds);
			FD_SET(s, &rfds);

			printf("playback> ");
			fflush(stdout);
			ns = select(s + 1, &rfds, NULL, NULL, NULL);
			if (ns < 0) {
				perror("select");
				exit(1);
			}
			if (FD_ISSET(0, &rfds)) {
				process_command(NULL, -1);
			}
			if (FD_ISSET(s, &rfds)) {
				break;
			}
		}
		s2 = accept(s, &addr.sa, &len);
		if (s2 < 0) {
			perror("accept");
			continue;
		}
		(void) printf("\nConnection from %s, port %u.\n",
#if defined(AF_INET6) /*[*/
		    inet_ntop(proto, &addr.sin6.sin6_addr, buf,
			INET6_ADDRSTRLEN) +
			 (IN6_IS_ADDR_V4MAPPED(&addr.sin6.sin6_addr)? 7: 0),
		    ntohs(addr.sin6.sin6_port)
#else /*][*/
		    inet_ntoa(addr.sin.sin_addr),
		    ntohs(addr.sin.sin_port)
#endif /*]*/
		);
		rewind(f);
		pstate = BASE;
		fdisp = 0;
		process(f, s2);
	}
}
Пример #7
0
/* trap handler: main entry point */
int 
__trap_to_gdb(struct cpu_user_regs *regs, unsigned long cookie)
{
    int rc = 0;
    unsigned long flags;

    if ( gdb_ctx->serhnd < 0 )
    {
        printk("Debugging connection not set up.\n");
        return -EBUSY;
    }

    /* We rely on our caller to ensure we're only on one processor
     * at a time... We should probably panic here, but given that
     * we're a debugger we should probably be a little tolerant of
     * things going wrong. */
    /* We don't want to use a spin lock here, because we're doing
       two distinct things:

       1 -- we don't want to run on more than one processor at a time,
            and
       2 -- we want to do something sensible if we re-enter ourselves.

       Spin locks are good for 1, but useless for 2. */
    if ( !atomic_dec_and_test(&gdb_ctx->running) )
    {
        printk("WARNING WARNING WARNING: Avoiding recursive gdb.\n");
        atomic_inc(&gdb_ctx->running);
        return -EBUSY;
    }

    if ( !gdb_ctx->connected )
    {
        printk("GDB connection activated.\n");
        gdb_arch_print_state(regs);
        gdb_ctx->connected = 1;
    }

    gdb_smp_pause();

    local_irq_save(flags);

    watchdog_disable();
    console_start_sync();

    /* Shouldn't really do this, but otherwise we stop for no
       obvious reason, which is Bad */
    printk("Waiting for GDB to attach...\n");

    gdb_arch_enter(regs);
    gdb_ctx->signum = gdb_arch_signal_num(regs, cookie);

    /* If gdb is already attached, tell it we've stopped again. */
    if ( gdb_ctx->currently_attached )
    {
        gdb_start_packet(gdb_ctx);
        gdb_cmd_signum(gdb_ctx);
    }

    do {
        if ( receive_command(gdb_ctx) < 0 )
        {
            dbg_printk("Error in GDB session...\n");
            rc = -EIO;
            break;
        }
    } while ( process_command(regs, gdb_ctx) == 0 );

    gdb_smp_resume();

    gdb_arch_exit(regs);
    console_end_sync();
    watchdog_enable();
    atomic_inc(&gdb_ctx->running);

    local_irq_restore(flags);

    return rc;
}
Пример #8
0
bool process_char(char c) {
    bool isDigit = (('0'<=c) && (c<='9'));
    bool isWhite = ((' ' == c)||('\t'==c));
    uint8_t b = 0;

    // ignore '\r'
    if (('\r' == c))
        return TRUE;
    // at end-of-line, command is complete => call process_command
    if (('\n' == c)) {
#ifdef DEBUG
        uint8_t i;
        for(i=0;i<31;i++) {
            if (codes_seen & ((uint32_t)1 << i)) {
                if (numbers_got & ((uint32_t)1 << i)) {
                    LOG_STRING("P: TOKEN ");LOG_CHAR('A'+i);LOG_S32(numbers[i]);LOG_NEWLINE;
                } else {
                    LOG_STRING("P: TOKEN ");LOG_CHAR('A'+i);LOG_NEWLINE;
                }
            }
        }
#endif
        if (base64_len) {
            LOG_STRING("P: TOKEN $ (");LOG_U8(base64_len);LOG_STRING("Bytes)\n");
            // if Stepper queue is empty, transfer modulation data now, else later
            if (STEPPER_QUEUE_is_empty()) {
                for(b=0;b<base64_len;b++)
                    LASER_RASTERDATA_put(base64_bytes[b]);
                base64_len=b=0;
            }
        }
        if (state != ERROR_STATE) {
            LOG_STRING("P: PROCESS COMMAND\n");
            process_command();
            // if stepper queue was not empty before, transfer modulation now
            if(base64_len) {
                for(b=0;b<base64_len;b++)
                    LASER_RASTERDATA_put(base64_bytes[b]);
                base64_len=0;
            }
        } else
            LOG_STRING("P: ERROR-STATE: IGNORE COMMAND!\n");
        // re-init parser
        codes_seen = 0;
        numbers_got = 0;
        state = EXPECT_FIRST_LETTER;
        return state != ERROR_STATE;
    }
    // XXX update checksum

    // state dependent interpretation of characters
    switch(state) {
        case EXPECT_FIRST_LETTER:
            codes_seen = 0;
            numbers_got = 0;
            memset(numbers, 0, sizeof(numbers));
            memset(integers, 0, sizeof(integers));
            memset(base64_bytes, 0, sizeof(base64_bytes));
            memset(filename, 0, sizeof(filename));
            filename_len = 0;
            base64_len = 0;
            state = EXPECT_LETTER;
            // intentionally no break !
        case EXPECT_LETTER:
            if ((('A'<=c) && (c<='Z'))) {
                last_letter = c-'A';
                codes_seen |= ((uint32_t)1) << last_letter;
                state = EXPECT_NUMBER_OR_SIGN;
                return TRUE;
            } else if (isWhite) { // ignore whitespace
                return TRUE;
            } else if ('*' == c) {
                state = PARSE_CHECKSUM;
                return TRUE;
            } else if (';' == c) {
                state = IGNORE_REST;
                return TRUE;
            } else if ('(' == c) {
                state = COMMENT_MODE;
                return TRUE;
            } else if ('$' == c) {
                state = EXPECT_BASE64_1;
                return TRUE;
            } else if ('\'' == c) {
                state = PARSE_FILENAME_TICKS;
                return TRUE;
            } else if ('"' == c) {
                state = PARSE_FILENAME_DOUBLETICKS;
                return TRUE;
            } else if (!filename_len) {
                state = PARSE_FILENAME;
                filename[filename_len++] = c;
                filename[filename_len] = 0;
                return TRUE;
            }
            LOG_PARSE_ERROR("unexpected character and filename already set!");
            break;
        case EXPECT_NUMBER_OR_SIGN:
            if (isWhite) {
                state = EXPECT_LETTER;
                return TRUE;
            } else if (!(isDigit || (c == '+') || (c=='-'))) {
                if (filename_len) {
                    LOG_PARSE_ERROR("filename already set: unexpected character found");
                }
                state = PARSE_FILENAME;
                filename[filename_len++] = last_letter + 'A';
                filename[filename_len++] = c;
                filename[filename_len] = 0;
                return TRUE;
            }
            state = EXPECT_FIRST_DIGIT;
            current_int = 0;
            digits = 0;
            subdigits = 0;
            if (c == '-') {
                isNegative = TRUE;
                return TRUE;
            }
            isNegative = FALSE;
            if (c == '+')    // needless, but valid
                return TRUE;
            // intentionally no break!
        case EXPECT_FIRST_DIGIT:    // first digit of a number
            if (isWhite) {
                state = EXPECT_LETTER;
                return TRUE;
            } else if (!isDigit)
                LOG_PARSE_ERROR("Expected [0-9\\w]");
            current_int = (uint8_t) c - '0';
            digits++;
            state = EXPECT_ANOTHERDIGIT;
            // fall through to number storage
            break;
        case EXPECT_ANOTHERDIGIT: // digits of a number before '.' or 'eE'
            if (isDigit) {
                if (digits>9)
                    LOG_PARSE_ERROR("Too many leading digits!");
                times_ten(current_int);
                current_int += (uint8_t) (c - '0');
                digits++;
                // fall through to number storage
                break;
            } else if ('.' == c) {
                state = EXPECT_SUBDIGITS;
                break;
            } else if (isWhite) {
                state = EXPECT_LETTER;
                break;
            } else if ('*' == c) {
                state = PARSE_CHECKSUM;
                break;
            } else if (';' == c) {
                state = IGNORE_REST;
                break;
            } else if ('(' == c) {
                state = COMMENT_MODE;
                break;
            } else if ('$' == c) {
                state = EXPECT_BASE64_1;
                break;
            } else if ('\'' == c) {
                state = PARSE_FILENAME_TICKS;
                break;
            } else if ('"' == c) {
                state = PARSE_FILENAME_DOUBLETICKS;
                break;
            } else
                LOG_PARSE_ERROR("Expected [0-9.\\w]");

        case EXPECT_SUBDIGITS:    // digits of a number after '.'
            if (isDigit) {
                if (subdigits >= SCALE_DIGITS) // ignore further digits
                    return TRUE;
                if (digits+subdigits > 9) //capacity exceeded!
                    //~ LOG_PARSE_ERROR("Too many total digits!");
                    return TRUE; // ignore further digits
                times_ten(current_int);
                current_int += (uint8_t) (c - '0');
                subdigits++;
                // fall through to number storage
                break;
            } else if (isWhite) {
                state = EXPECT_LETTER;
                return TRUE;
            } else
                LOG_PARSE_ERROR("Expected [0-9\\w]");
        case EXPECT_BASE64_1:    // expect first char of a base64-string
            if (isWhite) {
                state = EXPECT_LETTER;
                return TRUE;
            }
            b = base64_value(c);
            if (b > 63) {
                state = IGNORE_REST;
                LOG_PARSE_ERROR("Expected a BASE64 character");
            }
            base64_bytes[base64_len] = b<<2;
            state = EXPECT_BASE64_2;
            return TRUE;
        case EXPECT_BASE64_2:    // expect second char of a base64-string
            b = base64_value(c);
            if (b > 63) {
                state = IGNORE_REST;
                LOG_PARSE_ERROR("Expected a BASE64 character");
            }
            base64_bytes[base64_len++] |= (b >> 4);
            if (base64_len >= sizeof(base64_bytes)) {
                state = IGNORE_REST;
                LOG_PARSE_ERROR("Too many Base64 Bytes (Buffer full)");
            }
            base64_bytes[base64_len] = (b << 4);
            state = EXPECT_BASE64_3;
            return TRUE;
        case EXPECT_BASE64_3:    // expect third char of a base64-string (may be '=')
            if ('=' != c) {
                b = base64_value(c);
                if (b > 63) {
                    state = IGNORE_REST;
                    LOG_PARSE_ERROR("Expected a BASE64 character");
                }
                base64_bytes[base64_len++] |= (b >> 2);
                if (base64_len >= sizeof(base64_bytes)) {
                    state = IGNORE_REST;
                    LOG_PARSE_ERROR("Too many Base64 Bytes (Buffer full)");
                }
                base64_bytes[base64_len] = (b << 6);
            }
            state = EXPECT_BASE64_4;
            return TRUE;
        case EXPECT_BASE64_4:    // expect fourth char of a base64-string (may be '=')
            if ('=' != c) {
                b = base64_value(c);
                if (b > 63) {
                    state = IGNORE_REST;
                    LOG_PARSE_ERROR("Expected a BASE64 character");
                }
                base64_bytes[base64_len++] |= b;
                if (base64_len >= sizeof(base64_bytes)) {
                    state = IGNORE_REST;
                    LOG_PARSE_ERROR("Too many Base64 Bytes (Buffer full)");
                }
            }
            state = EXPECT_BASE64_1;
            return TRUE;
        case COMMENT_MODE:    // inside comment mode ()
            // just eat everything between '(' and ')'
            if (c == ')') {
                state = EXPECT_LETTER;
            }
            return TRUE;
        case ERROR_STATE: // after an error, ignore until end of line and do not process_command at eol!
            return FALSE;
        case PARSE_CHECKSUM: // after a '*': parse digits of the checksum (untile end of line)
            // ignored.
        case IGNORE_REST:    // after a ; (comment until end of line)
            // just eat everything after a ';'
            return TRUE;
        case PARSE_FILENAME_DOUBLETICKS: // parse filename inside double ticks ""
            if ('"' == c) {
                state = EXPECT_LETTER;
                return TRUE;
            }
            b = filename_len;
            filename[b++] = c;
            filename[b] = 0;
            filename_len = b;
            return (filename_len < sizeof(filename));
        case PARSE_FILENAME_TICKS: // parse filename inside single ticks ''
            if ('\'' == c) {
                state = EXPECT_LETTER;
                return TRUE;
            }
            b = filename_len;
            filename[b++] = c;
            filename[b] = 0;
            filename_len = b;
            return (filename_len < sizeof(filename));
        case PARSE_FILENAME: // Characters which must be a filename
            if (isWhite) {
                state = EXPECT_LETTER;
                return TRUE;
            }
            b = filename_len;
            filename[b++] = c;
            filename[b] = 0;
            filename_len = b;
            return (filename_len < sizeof(filename));

        default:
            LOG_PARSE_ERROR("Unknown or undefined State");
    }
Пример #9
0
void
process_requests (tmfd_t* asock, size_t *alen, fd_set* rset, struct server_ctx* srv)
{
    size_t nmax = *alen, i = 0, nserved = 0;
    int rc = 0, served = 0;
    char param[ 128 ] = "\0";
    time_t now = time (NULL);

    /* uncomment to DEBUG */
    TRACE( print_fds (g_flog, "pre-process sockets", asock, nmax) );

    for (; i < nmax; ++i, served = 0) {
        assert (asock[i].fd >= 0);
        assert (asock[i].atime > 0);

        do {
            /* not selected - yet try to time it out */
            if (!FD_ISSET(asock[i].fd, rset)) {
                if ((asock[i].atime + g_uopt.ssel_tmout) < now) {
                    TRACE( (void)tmfprintf (g_flog,
                        "%s: accepted socket [%ld] timed out\n",
                        __func__, (long)asock[i].fd) );
                    ++served;  /* timed out - must close */
                }
                break;
            }

            /* selected */
            TRACE( (void)tmfprintf (g_flog, "acting on accepted socket "
                "[%d] (%d/%d)\n", asock[i].fd, i+1, nmax) );

            ++served;  /* selected - must close regardless */
            rc = read_command( asock[i].fd, srv->cmd, sizeof(srv->cmd),
                    param, sizeof(param) );
            if( 0 != rc ) break;

            rc = process_command (asock[i].fd, srv, param, sizeof(param) );
        } while (0);

        if (0 != rc) {
            TRACE( (void)tmfprintf (g_flog, "error [%d] processing "
                "client socket [%d]\n", rc, asock[i]));
        }

        TRACE( (void)tmfprintf (g_flog, "%s: %s accepted "
            "socket [%d]\n", __func__, (served ? "closing" : "skipping"),
            asock[i].fd) );

        if (served) {
            (void) close (asock[i].fd);
            asock[i].fd = -1;
            ++nserved;
        }
    } /* for */

    TRACE( (void)tmfprintf (g_flog, "Processed [%ld/%ld] accepted sockets\n",
        (long)nserved, (long)nmax) );
    TRACE( print_fds (g_flog, "newly-accepted sockets", asock, nmax) );

    if (nserved >= nmax) {
        *alen = 0;
        TRACE( (void)tmfputs ("All accepted sockets processed\n", g_flog) );
    }
    else {
        shrink_asock (asock, alen, nserved);
    }

    return;
}
Пример #10
0
void hfp_parse(hfp_connection_t * context, uint8_t byte){
    int value;
    
    // TODO: handle space inside word        
    if (byte == ' ' && context->parser_state > HFP_PARSER_CMD_HEADER) return;

    if (!hfp_parser_found_separator(context, byte)){
        hfp_parser_store_byte(context, byte);
        return;
    }
    if (hfp_parser_is_end_of_line(byte)) {
        if (hfp_parser_is_buffer_empty(context)){
            context->parser_state = HFP_PARSER_CMD_HEADER;
        }
    }
    if (hfp_parser_is_buffer_empty(context)) return;


    switch (context->parser_state){
        case HFP_PARSER_CMD_HEADER: // header
            // printf(" parse header 1 \n");
            if (byte == '='){
                context->keep_separator = 1;
                hfp_parser_store_byte(context, byte);
                return;
            }
            
            if (byte == '?'){
                context->keep_separator = 0;
                hfp_parser_store_byte(context, byte);
                return;
            }
            // printf(" parse header 2 %s, keep separator $ %d\n", context->line_buffer, context->keep_separator);
            if (hfp_parser_is_end_of_header(byte) || context->keep_separator == 1){
                // printf(" parse header 3 %s, keep separator $ %d\n", context->line_buffer, context->keep_separator);
                process_command(context);
            }
            break;

        case HFP_PARSER_CMD_SEQUENCE: // parse comma separated sequence, ignore breacktes
            switch (context->command){
                case HFP_CMD_CONFIRM_COMMON_CODEC:
                    context->remote_codec_received = atoi((char*)context->line_buffer);
                    break;
                case HFP_CMD_SUPPORTED_FEATURES:
                    context->remote_supported_features = atoi((char*)context->line_buffer);
                    printf("Parsed supported feature %d\n", context->remote_supported_features);
                    break;
                case HFP_CMD_AVAILABLE_CODECS:
                    printf("Parsed codec %s\n", context->line_buffer);
                    context->remote_codecs[context->parser_item_index] = (uint16_t)atoi((char*)context->line_buffer);
                    context->parser_item_index++;
                    context->remote_codecs_nr = context->parser_item_index;
                    break;
                case HFP_CMD_INDICATOR:
                    if (context->retrieve_ag_indicators == 1){
                        strcpy((char *)context->ag_indicators[context->parser_item_index].name,  (char *)context->line_buffer);
                        context->ag_indicators[context->parser_item_index].index = context->parser_item_index+1;
                        printf("Indicator %d: %s (", context->ag_indicators_nr+1, context->line_buffer);
                    }

                    if (context->retrieve_ag_indicators_status == 1){ 
                        printf("Parsed Indicator %d with status: %s\n", context->parser_item_index+1, context->line_buffer);
                        context->ag_indicators[context->parser_item_index].status = atoi((char *) context->line_buffer);
                        context->parser_item_index++;
                        break;
                    }
                    break;
                case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
                    context->parser_item_index++;
                    if (context->parser_item_index != 4) break;
                    printf("Parsed Enable indicators: %s\n", context->line_buffer);
                    value = atoi((char *)&context->line_buffer[0]);
                    context->enable_status_update_for_ag_indicators = (uint8_t) value;
                    break;
                case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
                    printf("Parsed Support call hold: %s\n", context->line_buffer);
                    if (context->line_size > 2 ) break;
                    strcpy((char *)context->remote_call_services[context->remote_call_services_nr].name,  (char *)context->line_buffer);
                    context->remote_call_services_nr++;
                    break;
                case HFP_CMD_GENERIC_STATUS_INDICATOR:
                    printf("parser HFP_CMD_GENERIC_STATUS_INDICATOR 1 (%d, %d, %d)\n", 
                            context->list_generic_status_indicators, 
                            context->retrieve_generic_status_indicators,
                            context->retrieve_generic_status_indicators_state);
                    if (context->retrieve_generic_status_indicators == 1 || context->list_generic_status_indicators == 1){
                        printf("Parsed Generic status indicator: %s\n", context->line_buffer);
                        context->generic_status_indicators[context->parser_item_index].uuid = (uint16_t)atoi((char*)context->line_buffer);
                        context->parser_item_index++;
                        context->generic_status_indicators_nr = context->parser_item_index;
                        break;    
                    }
                    printf("parser HFP_CMD_GENERIC_STATUS_INDICATOR 2\n");
                    if (context->retrieve_generic_status_indicators_state == 1){
                        // HF parses inital AG gen. ind. state
                        printf("Parsed List generic status indicator %s state: ", context->line_buffer);
                        context->parser_item_index = (uint8_t)atoi((char*)context->line_buffer);
                        break;
                    }
                    break;
    
                case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
                    // AG parses new gen. ind. state
                    printf("Parsed Enable ag indicator state: %s\n", context->line_buffer);
                    value = atoi((char *)&context->line_buffer[0]);
                    if (!context->ag_indicators[context->parser_item_index].mandatory){
                        context->ag_indicators[context->parser_item_index].enabled = value;
                    }
                    context->parser_item_index++;
                    break;
                case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
                    // indicators are indexed starting with 1
                    context->parser_item_index = atoi((char *)&context->line_buffer[0]) - 1;
                    printf("Parsed status of the AG indicator %d, status ", context->parser_item_index);
                    break;
                case HFP_CMD_QUERY_OPERATOR_SELECTION:
                    if (context->operator_name_format == 1){
                        if (context->line_buffer[0] == '3'){
                            printf("Parsed Set network operator format : %s, ", context->line_buffer);
                            break;
                        }
                        // TODO emit ERROR, wrong format
                        printf("ERROR Set network operator format: index %s not supported\n", context->line_buffer);
                        break;
                    }

                    if (context->operator_name == 1) {
                        context->network_operator.mode = atoi((char *)&context->line_buffer[0]);
                        printf("Parsed network operator mode: %d, ", context->network_operator.mode);
                        break;
                    }
                    break;
                case HFP_CMD_ERROR:
                    break;
                case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
                    context->extended_audio_gateway_error = (uint8_t)atoi((char*)context->line_buffer);
                    break;
                case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
                    context->enable_extended_audio_gateway_error_report = (uint8_t)atoi((char*)context->line_buffer);
                    context->send_ok = 1;
                    context->extended_audio_gateway_error = 0;
                    break;
                default:
                    break;
            }
            break;

        case HFP_PARSER_SECOND_ITEM:
            switch (context->command){
                case HFP_CMD_QUERY_OPERATOR_SELECTION:
                    if (context->operator_name_format == 1) {
                        printf("format %s \n", context->line_buffer);
                        context->network_operator.format =  atoi((char *)&context->line_buffer[0]);
                        break;
                    }
                    if (context->operator_name == 1){
                        printf("format %s, ", context->line_buffer);
                        context->network_operator.format =  atoi((char *)&context->line_buffer[0]);
                    }
                    break;
                case HFP_CMD_GENERIC_STATUS_INDICATOR:
                    context->generic_status_indicators[context->parser_item_index].state = (uint8_t)atoi((char*)context->line_buffer);
                    break;
                case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
                    context->ag_indicators[context->parser_item_index].status = (uint8_t)atoi((char*)context->line_buffer);
                    context->ag_indicators[context->parser_item_index].status_changed = 1;
                    break;
                case HFP_CMD_INDICATOR:
                    if (context->retrieve_ag_indicators == 1){
                        context->ag_indicators[context->parser_item_index].min_range = atoi((char *)context->line_buffer);
                        printf("%s, ", context->line_buffer);
                    }
                    break;
                default:
                    break;
            }
            break;

        case HFP_PARSER_THIRD_ITEM:
             switch (context->command){
                case HFP_CMD_QUERY_OPERATOR_SELECTION:
                    if (context->operator_name == 1){
                        strcpy(context->network_operator.name, (char *)context->line_buffer);
                        printf("name %s\n", context->line_buffer);
                    }
                    break;
                case HFP_CMD_INDICATOR:
                    if (context->retrieve_ag_indicators == 1){
                        context->ag_indicators[context->parser_item_index].max_range = atoi((char *)context->line_buffer);
                        context->parser_item_index++;
                        context->ag_indicators_nr = context->parser_item_index;
                        printf("%s)\n", context->line_buffer);
                    }
                    break;
                default:
                    break;
            }
            break;
    }
    hfp_parser_next_state(context, byte);
}
int main( int argc, char *argv[])
{
   char cmdstr[80];
	int status, i;
	xbee_serial_t XBEE_SERPORT;
	target_t *target = NULL;

	memset( target_list, 0, sizeof target_list);

	parse_serial_arguments( argc, argv, &XBEE_SERPORT);

	// initialize the serial and device layer for this XBee device
	if (xbee_dev_init( &my_xbee, &XBEE_SERPORT, NULL, NULL))
	{
		printf( "Failed to initialize device.\n");
		return 0;
	}

	// replace ZDO cluster table with one that intercepts Device Annce messages
	sample_endpoints.zdo.cluster_table = zdo_clusters;

	// Initialize the WPAN layer of the XBee device driver.  This layer enables
	// endpoints and clusters, and is required for all ZigBee layers.
	xbee_wpan_init( &my_xbee, &sample_endpoints.zdo);

	// Initialize the AT Command layer for this XBee device and have the
	// driver query it for basic information (hardware version, firmware version,
	// serial number, IEEE address, etc.)
	xbee_cmd_init_device( &my_xbee);
	printf( "Waiting for driver to query the XBee device...\n");
	do {
		xbee_dev_tick( &my_xbee);
		status = xbee_cmd_query_status( &my_xbee);
	} while (status == -EBUSY);
	if (status)
	{
		printf( "Error %d waiting for query to complete.\n", status);
	}

	// report on the settings
	xbee_dev_dump_settings( &my_xbee, XBEE_DEV_DUMP_FLAG_DEFAULT);

	// set Profile ID for our Basic Client Cluster endpoint
	sample_endpoints.zcl.profile_id = profile_id;

   print_help();

   puts( "searching for Commissioning Servers");
	find_devices();

	while (1)
   {
      while (xbee_readline( cmdstr, sizeof cmdstr) == -EAGAIN)
      {
      	wpan_tick( &my_xbee.wpan_dev);
      }

		if (! strcmpi( cmdstr, "quit"))
      {
			return 0;
		}
		else if (! strcmpi( cmdstr, "help") || ! strcmp( cmdstr, "?"))
		{
			print_help();
		}
		else if (! strncmpi( cmdstr, "profile ", 8))
		{
			profile_id = strtoul( &cmdstr[8], NULL, 16);
			printf( "Profile ID set to 0x%04x\n", profile_id);
			sample_endpoints.zcl.profile_id = profile_id;
		}
		else if (! strcmpi( cmdstr, "find"))
		{
			find_devices();
		}
		else if (! strcmpi( cmdstr, "target"))
		{
			puts( " #: --IEEE Address--- Ver. --------Application Name--------"
				" ---Date Code----");
			for (i = 0; i < target_index; ++i)
			{
				print_target( i);
			}
			puts( "End of List");
		}
		else if (! strncmpi( cmdstr, "target ", 7))
		{
			i = (int) strtoul( &cmdstr[7], NULL, 10);
			if (target_index == 0)
			{
				printf( "error, no targets in list, starting search now...\n");
				find_devices();
			}
			else if (i < 0 || i >= target_index)
			{
				printf( "error, index %d is invalid (must be 0 to %u)\n", i,
					target_index - 1);
			}
			else
			{
				target = &target_list[i];
				puts( "set target to:");
				print_target( i);
			}
		}
		else if (! strcmpi( cmdstr, "save"))
		{
			restart_target( target, TRUE);
		}
		else if (! strcmpi( cmdstr, "cancel"))
		{
			restart_target( target, FALSE);
		}
		else if (! strcmpi( cmdstr, "default"))
		{
			default_target( target);
		}
		else if (! strcmpi( cmdstr, "deploy"))
		{
			set_pan( target, &network_deploy);
		}
		else if (! strncmpi( cmdstr, "deploy ", 7))
		{
			if (cmdstr[7] == 'r')
			{
				puts( "deploy as router");
				network_deploy.startup_control = ZCL_COMM_STARTUP_JOINED;
			}
			else if (cmdstr[7] == 'c')
			{
				puts( "deploy as coordinator");
				network_deploy.startup_control = ZCL_COMM_STARTUP_COORDINATOR;
			}
			set_pan( target, &network_deploy);
		}
		else if (! strcmpi( cmdstr, "comm"))
		{
			set_pan( target, &network_comm);
		}
		else if (! strncmpi( cmdstr, "AT", 2))
		{
			process_command( &my_xbee, &cmdstr[2]);
		}
	   else
	   {
	   	printf( "unknown command: '%s'\n", cmdstr);
	   }
   }
}
Пример #12
0
void
prim_force(PRIM_PROTOTYPE)
{
    int nFrameIndex = -1; /* -1 means it hasn't been set */
    int nCurFr = 0; /* Loop iterator */
    int wclen = -2;
    int len;
    /* d s -- */
    CHECKOP(2);
    oper1 = POP();              /* string to @force */
    oper2 = POP();              /* player dbref */
    if (mlev < LARCH)
        abort_interp("Arch prim");
    if (fr->level > 8)
        abort_interp("Interp call loops not allowed");
    if (oper1->type != PROG_STRING)
        abort_interp("Non-string argument (2)");
    if (oper2->type != PROG_OBJECT)
        abort_interp("Non-object argument (1)");
    ref = oper2->data.objref;
    if (ref < 0 || ref >= db_top)
        abort_interp("Invalid object to force (1)");
    if (Typeof(ref) != TYPE_PLAYER && Typeof(ref) != TYPE_THING)
        abort_interp("Object to force not a thing or player (1)");
    if (!oper1->data.string)
        abort_interp("Null string argument (2)");
    if (index(oper1->data.string->data, '\r'))
        abort_interp("Carriage returns not allowed in command string (2)");
    if (Man(oper2->data.objref) && !(Man(OWNER(program)) && Boy(program)))
        abort_interp("Cannot force the man (1)");

    strcpy(buf, oper1->data.string->data);
    len = oper1->data.string->length;
#ifdef UTF8_SUPPORT
    wclen = oper1->data.string->wclength;
#endif
    CLEAR(oper1);
    CLEAR(oper2);
    nargs -= 2;

    force_level++;
    /* Okay, we need to store a pointer to the fr in the global stack of
     * frame pointers we need to enable ispid? and getpidinfo to be able
     * to search. */
    for ( ; nCurFr < 9; ++nCurFr )
    {
        if ( !aForceFrameStack[nCurFr] )
        {
            aForceFrameStack[nCurFr] = fr;
            nFrameIndex = nCurFr;
            break;
        }
    }
    
    if ( nFrameIndex == -1 )
    {
        abort_interp( "Internal error trying to cache frame pointer." );
    }

    fr->level++;
    interp_set_depth(fr);
    process_command(dbref_first_descr(ref), ref, buf, len, wclen);
    fr->level--;
    interp_set_depth(fr);
    force_level--;

    /* Now remove our pointer from the end of the array */
    aForceFrameStack[nFrameIndex] = NULL; 
}
Пример #13
0
int main(int argc, char **argv)
{
	struct cmdline_args args = {0};
	int ret = 0;

	setvbuf(stderr, NULL, _IOFBF, 0);
	setvbuf(stdout, NULL, _IOFBF, 0);

	opdb_reset();
	ctrlc_init();

	args.devarg.vcc_mv = 3000;
	args.devarg.requested_serial = NULL;
	if (parse_cmdline_args(argc, argv, &args) < 0)
		goto fail_parse;

	if (args.flags & OPT_EMBEDDED)
		input_module = &input_async;
	if (input_module->init() < 0)
		goto fail_input;

	output_set_embedded(args.flags & OPT_EMBEDDED);

	if (sockets_init() < 0) {
		ret = -1;
		goto fail_sockets;
	}

	printc_dbg("%s", version_text);
	printc_dbg("%s\n", chipinfo_copyright());
	if (setup_driver(&args) < 0) {
		ret = -1;
		goto fail_driver;
	}

	if (device_probe_id(device_default, args.devarg.forced_chip_id) < 0)
		printc_err("warning: device ID probe failed\n");

	simio_init();

	if (!(args.flags & OPT_NO_RC))
		process_rc_file(args.alt_config);

	/* Process commands */
	if (optind < argc) {
		while (optind < argc) {
			if (process_command(argv[optind++]) < 0) {
				ret = -1;
				break;
			}
		}
	} else {
		reader_loop();
	}

	simio_exit();
	device_destroy();
	stab_exit();
fail_driver:
	sockets_exit();
fail_sockets:
	input_module->exit();
fail_input:
fail_parse:

	/* We need to do this on Windows, because in embedded mode we
	 * may still have a running background thread for input. If so,
	 * returning from main() won't cause the process to terminate.
	 */
#if defined(__CYGWIN__)
	cygwin_internal(CW_EXIT_PROCESS,
		(ret == 0) ? EXIT_SUCCESS : EXIT_FAILURE, 1);
#elif defined(__Windows__)
	ExitProcess(ret);
#endif
	return ret;
}
dependency_graph_t build_graph (command_stream_t s)
{
    dependency_graph_t ret_d;
    ret_d = NULL;
    size_t num;
    num = 0;
    size_t iter = 0;
    command_t comm;
    ret_d =checked_malloc(sizeof(struct dependency_graph));
    init_graph(ret_d);
    
    char**args;
    size_t a_size;
    size_t a_mem;
    a_mem = (sizeof(char*));
    args=checked_malloc(a_mem);
    int size= countNodes(s->item);
    
    char** read;
    size_t r_mem;
    size_t r_size;
    
    char** write;
    size_t w_mem;
    size_t w_size;
    
    size_t position=0;
    size_t innerpos = 0;
    
    for(num = 0; num < size;num++)
    {
        comm = s->cArray[num]; //each command in the array
        dependency_node_t n;
        n = checked_malloc (sizeof (struct dependency_node));
        init_node(n, comm); //make a node to add to the graph
        while(iter < ret_d->no_dep_size || iter < ret_d->dep_size)
        {
            //if (debugmode) { printf ("I AM THERE!"); }
            r_size = 0;
            r_mem = (sizeof(char*));
            read = checked_malloc(r_mem);
            w_mem = (sizeof(char*) * 3);
            w_size = 0;
            write = checked_malloc(w_mem);
            a_size = 0;
            size_t aMem = sizeof (char*);
            args = checked_malloc(aMem);
            //find all the arguments passed on the command line
            process_command(comm, args, &a_size, &aMem);
            process_command(comm, read, &r_size, &r_mem);
            process_command(comm, write, &w_size, &w_mem);
            //set all the node properties
            n->read = read;
            n->read_size = r_size;
            n->read_mem = r_mem;
            n->write = write;
            n->write_size = w_size;
            n->write_mem = w_mem;
            n->args = args;
            //printf("iter: %zu\n", iter);
            //error(1,0,"kid");
            //if(comm->input!= NULL)
            //	printf("%s\n", comm->input);
            //printf ("1");
            
            //if there is a value in the output array and there is a node in the executable array
            //of the graph, then add a dependency to the current node and then push it to the dependancy graph
            if(write != NULL && iter < ret_d->no_dep_size){//printf("O\n");
                while(position < w_size){
                    while(innerpos < ret_d->no_dep[iter]->read_size){
                        if(strcmp(ret_d->no_dep[iter]->read[innerpos], write[position])==0)
                        {
                            if (mem_need_grow (n->b4, &n->b4_size, sizeof(dependency_node_t) , n->b4_mem))
                            { n->b4 = checked_grow_alloc (n->b4, &(n->b4_mem)); }
                            
                            n->b4[n->b4_size] = ret_d->no_dep[iter];
                            n->b4_size +=1;
                        }
                        innerpos+=1;
                    }
                    position +=1;
                }
            }
         
            
            //if there is a value in the output array and there is a node in the dependancy array
            //of the graph, then add a dependency to the current node and then push it to the dependancy graph, because all commands
            //are parsed sequentially, if a dependancy occurs in the dependancy graph, then it must be added to the
            //dependancy graph
            if(write != NULL && iter < ret_d->dep_size){//printf("O\n");
                while(write[position]!=NULL){//printf("O2\n");
                    while(ret_d->dep[iter]->read[innerpos]!=NULL){
                        if(strcmp(ret_d->dep[iter]->read[innerpos], write[position])==0)
                        {
                            n->b4[n->b4_size] = ret_d->dep[iter];
                            n->b4_size +=1;
                        }
                        innerpos+=1;
                    }
                    position +=1;
                }
            }
            //printf ("3");
            
            //if there is a input depencdancy and there is a matching value in the dependancy graph
            //push the dependancy for this node
            if(read != NULL && iter < ret_d->dep_size){
                while(read[position]!=NULL){
                    while(ret_d->dep[iter]->write[innerpos]!=NULL){
                        if(strcmp(ret_d->dep[iter]->write[innerpos], read[position])==0)
                        {
                            n->b4[n->b4_size] = ret_d->dep[iter];
                            n->b4_size +=1;
                        }
                        innerpos+=1;
                    }
                    position +=1;
                }
            }
            //printf ("4");
            
            //same thing as above, but check the executable array for a dependancy
            if(read != NULL && iter < ret_d->no_dep_size){
                while(read[position]!=NULL){
                    while(ret_d->no_dep[iter]->write[innerpos]!=NULL){
                        if(strcmp(ret_d->no_dep[iter]->write[innerpos], read[position])==0)
                        {
                            n->b4[n->b4_size] = ret_d->no_dep[iter];
                            n->b4_size +=1;
                        }
                        innerpos+=1;
                    }
                    position +=1;
                }
            }
            //printf ("5");
            
            //this should do the same for the arguments parsed as command line and not strict
            //I/O redirection. This function checks the dependancy array of the graph
            if(args != NULL && iter < ret_d->dep_size){
                while(args[position]!=NULL){
                    while(ret_d->dep[iter]->write[innerpos]!=NULL){
                        if(strcmp(ret_d->dep[iter]->write[innerpos], args[position])==0)
                        {
                            n->b4[n->b4_size] = ret_d->dep[iter];
                            n->b4_size +=1;
                        }
                        innerpos+=1;
                    }
                    position +=1;
                }
            }
            //printf ("6");
            
            //same as above, but it checks the executable array for the graph
            if(args != NULL && iter < ret_d->no_dep_size){
                while(args[position]!=NULL){
                    while(ret_d->no_dep[iter]->write[innerpos]!=NULL){
                        if(strcmp(ret_d->no_dep[iter]->write[innerpos], args[position])==0)
                        {
                            n->b4[n->b4_size] = ret_d->no_dep[iter];
                            n->b4_size +=1;
                        }
                        innerpos+=1;
                    }
                    position +=1;
                }
            }
            //printf ("6.5");
            /*if(comm->input != NULL && iter < ret_d->depSize){
             if(ret_d->dep[iter]->c->output == comm->input)
             {
             n->before[n->bef_size] = ret_d->dep[iter];
             n->bef_size+=1;
             //ret_d->dep[iter]->after[ret_d->dep[iter]->aft_size] = n;
             //ret_d->dep[iter]->aft_size++;
             }
             }*/
            //reset all the values that you used before in the loop 
            position = 0;
            innerpos = 0;
            iter +=1;
        }
        //printf ("7");
        //if at any point the bef_size of the current node has been altered so it is greater than 0, add this
        //node to the dependancy array for the graph
        if(n->b4_size > 0){//if (debugmode) printf("befsize = %zu\n", n->bef_size);
            add_dep_to_graph(ret_d, n, 1);}
        //if the node has no dependancies, then push it to the executable array of the dependancy graph
        else{// if (debugmode) printf("befsize = %zu\n", n->bef_size);
            add_dep_to_graph(ret_d, n, 0);}
        //reset iter for the next command that needs to be added
        iter = 0;
        
        //TODO:
        // Determine which nodes already seen depend on this one.
        // Look through the independent nodes.
        // If a match is found, add this node as a dependency
        // And move it to the node with dependencies list
        // Look through the nodes with dependencies.
        // If a match is found, add this node as a dependency
        //printf ("9");
        
    }
    
    return ret_d;
}
Пример #15
0
/*
	main

	Initiate communication with the XBee module, then accept AT commands from
	STDIO, pass them to the XBee module and print the result.
*/
int main( int argc, char *argv[])
{
   char cmdstr[80];
   char buffer[ADDR64_STRING_LENGTH];
	int status;
	xbee_serial_t XBEE_SERPORT;
	addr64 return_ieee_be = *ZDO_IEEE_ADDR_PENDING;
	uint16_t return_net_addr = ZDO_NET_ADDR_PENDING;
	int err;

	parse_serial_arguments( argc, argv, &XBEE_SERPORT);

	// initialize the serial and device layer for this XBee device
	if (xbee_dev_init( &my_xbee, &XBEE_SERPORT, NULL, NULL))
	{
		printf( "Failed to initialize device.\n");
		return 0;
	}

	// Initialize the WPAN layer of the XBee device driver.  This layer enables
	// endpoints and clusters, and is required for all ZigBee layers.
	xbee_wpan_init( &my_xbee, &sample_endpoints.zdo);

	// Initialize the AT Command layer for this XBee device and have the
	// driver query it for basic information (hardware version, firmware version,
	// serial number, IEEE address, etc.)
	xbee_cmd_init_device( &my_xbee);
	printf( "Waiting for driver to query the XBee device...\n");
	do {
		xbee_dev_tick( &my_xbee);
		status = xbee_cmd_query_status( &my_xbee);
	} while (status == -EBUSY);
	if (status)
	{
		printf( "Error %d waiting for query to complete.\n", status);
	}

	// report on the settings
	xbee_dev_dump_settings( &my_xbee, XBEE_DEV_DUMP_FLAG_DEFAULT);

	// have XBee handle ZDO responses -- on SE device, need to have it respond
	// to match descriptors looking for the Key Establishment cluster.
	xbee_cmd_simple( &my_xbee, "AO", 1);

   print_help();

   while (1)
   {
      while (xbee_readline( cmdstr, sizeof cmdstr) == -EAGAIN)
      {
      	wpan_tick( &my_xbee.wpan_dev);
      	if (! addr64_equal( &return_ieee_be, ZDO_IEEE_ADDR_PENDING))
      	{
				if (addr64_equal( &return_ieee_be, ZDO_IEEE_ADDR_TIMEOUT))
				{
					puts( "IEEE_addr request timed out");
				}
				else if (addr64_is_zero( &return_ieee_be))
				{
					printf( "Error retrieving IEEE_addr");
				}
				else
				{
					printf( "IEEE address is %" PRIsFAR "\n",
						addr64_format( buffer, &return_ieee_be));
				}
				return_ieee_be = *ZDO_IEEE_ADDR_PENDING;
      	}
      	if (return_net_addr != ZDO_NET_ADDR_PENDING)
      	{
      		if (return_net_addr == ZDO_NET_ADDR_TIMEOUT)
      		{
					puts( "NWK_addr request timed out");
      		}
      		else if (return_net_addr == ZDO_NET_ADDR_ERROR)
      		{
					printf( "Error retrieving NWK_addr");
      		}
      		else
      		{
      			printf( "Network address is 0x%04X\n", return_net_addr);
      		}
      		return_net_addr = ZDO_NET_ADDR_PENDING;
      	}
      }

		if (! strcmpi( cmdstr, "help") || ! strcmp( cmdstr, "?"))
		{
			print_help();
		}
      else if (! strcmpi( cmdstr, "quit"))
      {
			return 0;
		}
		else if (! strncmpi( cmdstr, "ieee ", 5))
		{
			addr64 ieee_be;

			if (addr64_parse( &ieee_be, &cmdstr[5]))
			{
				printf( "couldn't parse '%s'\n", &cmdstr[5]);
			}
			else
			{
				err = zdo_send_nwk_addr_req( &my_xbee.wpan_dev, &ieee_be,
					&return_net_addr);
				printf( "sent NWK_addr request for %" PRIsFAR " (err=%d)\n",
					addr64_format( buffer, &ieee_be), err);
			}
		}
		else if (! strncmpi( cmdstr, "net ", 4))
		{
			uint16_t net_addr;
			char *tail;

			net_addr = strtoul( &cmdstr[4], &tail, 0);
			if (tail == NULL)
			{
				printf( "couldn't parse '%s'\n", &cmdstr[4]);
			}
			else
			{
				err = zdo_send_ieee_addr_req( &my_xbee.wpan_dev, net_addr,
					&return_ieee_be);
				printf( "sent IEEE_addr request for 0x%04X (err=%d)\n", net_addr,
					err);
			}
		}
      else if (! strncmpi( cmdstr, "AT", 2))
      {
			process_command( &my_xbee, cmdstr);
	   }
   }
}
Пример #16
0
const char *
mfn_force(MFUNARGS)
{
    char *nxt, *ptr;
    dbref obj = mesg_dbref_raw(player, what, perms, argv[0]);
    if (obj == AMBIGUOUS || obj == UNKNOWN || obj == NOTHING || obj == HOME)
	ABORT_MPI("FORCE","Failed match. (1)");
    if (obj == PERMDENIED)
	ABORT_MPI("FORCE","Permission denied. (1)");
    if (Typeof(obj) != TYPE_THING && Typeof(obj) != TYPE_PLAYER)
	ABORT_MPI("FORCE","Bad object reference. (1)");
    if (!*argv[1])
	ABORT_MPI("FORCE","Null command string. (2)");
    if (!tp_zombies && !Archperms(perms))
	ABORT_MPI("FORCE",NOPERM_MESG);
    if (!Archperms(perms)) {
	const char *ptr = RNAME(obj);
	char objname[BUFFER_LEN], *ptr2;
	dbref loc = getloc(obj);

	if (Typeof(obj) == TYPE_THING) {
	    if (FLAGS(obj) & DARK)
		ABORT_MPI("FORCE","Cannot force a dark puppet");
	    if ((FLAGS(OWNER(obj)) & ZOMBIE))
		ABORT_MPI("FORCE",NOPERM_MESG);
	    if (loc != NOTHING && (FLAGS(loc) & ZOMBIE) &&
		    Typeof(loc) == TYPE_ROOM)
		ABORT_MPI("FORCE","Cannot force a Puppet in a no-puppets room");
	    for (ptr2 = objname; *ptr && !isspace(*ptr);)
		*(ptr2++) = *(ptr++);
	    *ptr2 = '\0';
	    if (lookup_player(objname) != NOTHING)
		ABORT_MPI("FORCE","Cannot force a thing named after a player");
	}
	if (!(FLAGS(obj) & XFORCIBLE)) {
	    ABORT_MPI("FORCE",NOPERM_MESG);
	}
	if (!test_lock_false_default(perms, obj, "@/flk")) {
	    ABORT_MPI("FORCE",NOPERM_MESG);
	}
    }
    if (Man(obj) && !TMan(perms))
	ABORT_MPI("FORCE","You can't force " NAMEMAN);
    if (!controls(OWNER(perms),obj))
	ABORT_MPI("FORCE",NOPERM_MESG);
    if ((WLevel(OWNER(perms)) < WLevel(obj)) ||
	(WLevel(perms) < WLevel(obj))
    )	ABORT_MPI("FORCE",NOPERM_MESG);
    if (force_level)
	ABORT_MPI("FORCE","You can't force recursively");
    strcpy(buf, argv[1]);
    ptr = buf;
    do {
	nxt = index(ptr, '\r');
	if (nxt) *nxt++ = '\0';
	force_level++;
	if (*ptr) process_command(obj, ptr, 0);
	force_level--;
	ptr = nxt;
    } while (ptr);
    *buf = '\0';
    return "";
}
Пример #17
0
void main(int argc, char * argv[])
{
	FILE * fp;
	char  buffer[100],*command,*com2,*com1,*result=NULL,**coms,*dummy=NULL;
	int j;
	struct stack *s=(struct stack*)malloc(sizeof(struct stack));
	s->top=0;
	coms=(char**)malloc(sizeof(char*)*2);
	fp=fopen(argv[1],"r");
	while(1)
	{
		if(fgetc(fp)==EOF)break;
		else fseek(fp,-1,1);		
		fgets(buffer,sizeof(buffer),fp);				
		command = strtok( buffer," ");
		if(strcmp(command,"create\n")==0)
		{
			printf("%s\n",ERR_CDS_CREATE_DATASTORE_00 );
			
		}
		else if(strcmp(command,"load\n")==0)
		{
			printf("%s\n",ERR_CDS_LOAD_DATASTORE_00 );
		}
		else if(strcmp(command,"load")==0)
		{
			j=0;			
			while(j!=2)
			{
				result=strtok(NULL," ");
				if(result==NULL)
				{
					printf("%s\n",ERR_CDS_LOAD_DATASTORE_00);
					break;
				}
				else
				{
					
					
					coms[j]=(char*)malloc(sizeof(char)*strlen(result));
					strcpy(coms[j],result);
					j++;
					
				}
			}
			process_command(command,coms[0],coms[1],s);					
					
		}			
		else if(strcmp(command,"insert\n")==0)
		{
			printf("%s\n",ERR_CDS_INSERT_DATASTORE_00 );
			
		}
		else if(strcmp(command,"insert")==0)
		{
			
			coms[0]=strtok(NULL," ");
			coms[1]=NULL;
			process_command(command,coms[0],coms[1],s);
		}
		else if(strcmp(command,"retrieve\n")==0)
		{
			printf("%s\n",ERR_CDS_RETRIEVE_DATASTORE_00 );
			
		}
		else if(strcmp(command,"update\n")==0)
		{
			printf("%s\n",ERR_CDS_CREATE_DATASTORE_00 );
			
		}
		else if(strcmp(command,"delete\n")==0)
		{
			printf("%s\n",ERR_CDS_CREATE_DATASTORE_00 );
			
		}
		else if(strcmp(command,"delete")==0)
		{
			result=strtok(NULL," ");
			coms[0]=(char*)malloc(sizeof(char)*strlen(result));
			strcpy(coms[0],result);
			coms[1]=NULL;
			process_command(command,coms[0],coms[1],s);
		}
		else if(strcmp(command,"update")==0)
		{
			j=0;			
			while(j!=2)
			{
								
				coms[j]=strtok(NULL," ");
				if(coms[j]==NULL)
				{
					printf("%s\n",ERR_CDS_UPDATE_DATASTORE_00);
					break;
				}
				else
				{
					if(strcmp(coms[j],"where")==0);
					else
					{
						
						j++;
						
					}
				}
						
			}	
			process_command(command,coms[0],coms[1],s);			
			
		}
		else if(strcmp(command,"retrieve")==0)
		{
			j=0;			
			while(j!=2)
			{
				coms[j]=strtok(NULL," ");
				if(coms[j]==NULL)
				{
					printf("%s\n",ERR_CDS_RETRIEVE_DATASTORE_00);
					break;
				}
				else
				{
					if(strcmp(coms[j],"where")==0);
					else
					{
						
						
						j++;
					}
				}
						
			}
			process_command(command,coms[0],coms[1],s);		
		}		
		else if(strcmp(command,"create")==0)

		{
			j=0;			
			while(j!=2)
			{
				result=strtok(NULL," ");
				if(result==NULL)
				{
					printf("%s\n",ERR_CDS_RETRIEVE_DATASTORE_00);
					break;
				}
				else
				{
					
					
					coms[j]=(char*)malloc(sizeof(char)*strlen(result));
					strcpy(coms[j],result);
					j++;
					
				}
						
			}
			process_command(command,coms[0],coms[1],s);					
			
		}
		
			
		

	}	
}
Пример #18
0
DWORD WINAPI server_thread(LPVOID parameter)
{
	while (1)
	{
	HANDLE hPipe = CreateNamedPipeW( 
		(wchar_t*)parameter,             // pipe name 
		PIPE_ACCESS_DUPLEX,      // read/write access 
		PIPE_TYPE_MESSAGE |		  // message type pipe 
		PIPE_READMODE_MESSAGE |   // message-read mode 
		PIPE_WAIT,                // blocking mode 
		PIPE_UNLIMITED_INSTANCES, // max. instances  
		500, // output buffer size 
		500, // input buffer size 
		0,                        // client time-out 
		NULL);                    // default security attribute 

	if (hPipe == INVALID_HANDLE_VALUE)
		break; // wtf ... create pipe fail?

	printf("pipe created, waitting for connection.....");
	fflush(stdout);
	if (!ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED))
		ExitProcess(-2);

	printf("connected\n");



	// read command and execute
	char *data = NULL;
	while (1)
	{
		// free
		if (data) {delete data; data = NULL;}

		// read command header
		thumbnail_cmd cmd;
		DWORD cbBytesRead = 0;
		BOOL fSuccess = ReadFile( hPipe, &cmd, sizeof(thumbnail_cmd), &cbBytesRead, NULL);
		if (!fSuccess || cbBytesRead == 0)
			break;

		// read command data if there is
		if (cmd.data_size>0)
		{
			data = new char[cmd.data_size];
			fSuccess = ReadFile( hPipe, data, cmd.data_size, &cbBytesRead, NULL);
			if (!fSuccess || cbBytesRead == 0)
				break;
		}

		// process command
		void * odata = NULL;
		thumbnail_cmd ocmd;
		if (process_command(cmd, data, &ocmd, &odata)<0)
			continue;

		// send result back
		fSuccess = WriteFile(hPipe, &ocmd, sizeof(thumbnail_cmd), &cbBytesRead, NULL);
		if (!fSuccess || cbBytesRead == 0)
			break;

		if (ocmd.data_size>0 && odata)
		{
			fSuccess = WriteFile( hPipe, odata, ocmd.data_size, &cbBytesRead, NULL);
			delete odata;
			if (!fSuccess || cbBytesRead == 0)
				break;
		}
	}

	printf("shutting down...");
	DisconnectNamedPipe(hPipe); 
	CloseHandle(hPipe);
	printf("OK\n");
	}
	return 0;
}
Пример #19
0
void *listen_neighbor(void *arg){
		sockfd = socket(AF_INET, SOCK_STREAM, 0);
    		if (sockfd<0){
        		perror("Cannot open socket for connection\n");
    		}

    		bzero((char *) &serv_addr, sizeof(serv_addr));
    		portno = PORT;
    		serv_addr.sin_family = AF_INET;
	    	serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    		serv_addr.sin_port = htons(portno);

    		if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))<0){
         		perror("Error - Cannot bind server on given port.\n");
         		exit(1);
    		}
 		printf("Accepting connections..\n");
		listen(sockfd,10);
		int clients = sizeof(clnt_addr);
	
		bzero(buffer,1024);
		//printf("Before accepting\n");
        	newsockfd = accept(sockfd, (struct sockaddr *) NULL, NULL);
		//printf("After accepting\n");
        	if (newsockfd<0)
        	{
            		perror("Error in accepting connection from clients..\n");
        	}
		strcpy(buffer,"ACK");
		int n = send(newsockfd, buffer, strlen(buffer), 0);
		bzero(buffer,1024);
        	while(1){
			if(!NO_LEADER) break;
			printf("\nWaiting for receive..\n");
			int n = recv(newsockfd, buffer, 1024, 0);
        		if(n<0){
                		printf("Cannot read from socket. Possibly the node has disconnected..\n");
                		close(newsockfd);
        			break;
        		}
			printf("Buffer - %s\n", buffer);
			if(strcmp(buffer,"")==0){
				printf("Client disconnected..\n");
				break;
			}
        		rcvd_strings[0][0]='\0';rcvd_strings[1][0]='\0';rcvd_strings[2][0]='\0';
        		process_command(buffer);	//Decode the message.
        		argument *arg = (argument *) malloc (sizeof(argument));
        		arg->sock = newsockfd;
        		strcpy(arg->str1, rcvd_strings[0]);
        		strcpy(arg->str2, rcvd_strings[1]);
        		strcpy(arg->str3, rcvd_strings[2]);
        		pthread_t th;
        		if(pthread_create(&th, NULL, process_msg, arg)){
                		printf("Error in creating a new thread..\n");
				break;
			}
			bzero(buffer,1024);
			/*int p = fork();
			if(p==0) process_msg(arg);*/
		}
	close(newsockfd);
	printf("neighbor listener exited..\n");
	pthread_exit(NULL);		
}
Пример #20
0
int braitenberg( int argc , string * argv)
{
  int Connections_B[9] = { 2, -2, -4, -12,  5,  2,  2, 2, 4}; // weight of every 9 sensor for the left motor 
  int Connections_A[9] = { 2,  2,  2, 5, -12, -4, -2, 2, 4}; // weight of every 9 sensor for the right motor 
  int i, buflen, sensval;
  char buffer[MAXBUFFERSIZE];
  char * scan;
  long int lspeed16, rspeed16;
  int tabsens[9];
  int left_speed, right_speed;
  unsigned int immobility = 0;
  unsigned int prevpos_left, pos_left, prevpos_right,  pos_right;
  u_int8_t valueLL,valueLH,valueHL,valueHH;
  
  int readable_size=0;
	int out=0;
	char Buffer[MAXBUFFERSIZE];

	
	if (argc != 1)
	{
		sprintf(buf,"%c\r\n",ERROR_CMD_CHAR);
		com_send(buf, strlen(buf));
		return -1;
	}
	
	if (atoi(argv[0]) == 2 )
	{
		sprintf(buf,"a\r\n");
		com_send(buf, strlen(buf));
		return 1;
	} else
	{
		if ((atoi(argv[0]) == 0) || (atoi(argv[0]) == 1) )
		{
			// continue with below
		}
		else
		{
			sprintf(buf,"%c\r\n",ERROR_CMD_CHAR);
			com_send(buf, strlen(buf));
			return -1;
		}
	}
	
	sprintf(buf,"a\r\n");
	com_send(buf, strlen(buf));
	
  /* Get the current position values */
  prevpos_left = kmot_GetMeasure( mot1 , kMotRegPos );
  prevpos_right = kmot_GetMeasure( mot2 , kMotRegPos );


	printf("\nBraitenberg mode; enter any serial command to stop\n");

	fcntl(porthandle, F_SETFL, FNDELAY); // read will return immediately if no data

  do
  {
    lspeed16 = 0; rspeed16 = 0;

#if 0
    kh3_sendcommand( dsPic, cmd );
    while(!kb_gpio_get(KNET_INT0));

    buflen = knet_llread( dsPic, buffer, 30);
#endif

    kh3_proximity_ir((char *)buffer, dsPic);
    
    
    scan   = buffer+3; // why not 1???

    /* limit the sensor values to 0-max */
    for (i = 0; i < 9; i++)	
    {
			sensval = *(scan) | (*(scan+1))<<8;
			if(sensval > 1000)
				tabsens[i] = 450;
			else if (sensval < 100)
				tabsens[i] = 0;
			else
				tabsens[i] = (sensval - 100) >> 1;
			scan = scan + 2;
    }

    for (i = 0; i < 9; i++)
    {
      lspeed16 += Connections_A[i] * tabsens[i];
      rspeed16 += Connections_B[i] * tabsens[i];				
    }

    left_speed = ((lspeed16 / BR_IRGAIN) + fwSpeed);
    right_speed = ((rspeed16 / BR_IRGAIN) + fwSpeed);

    if(left_speed > 0 && left_speed < MIN_SPEED)
      left_speed = MIN_SPEED;
    if(left_speed < 0 && left_speed > -MIN_SPEED)
      left_speed = -MIN_SPEED;
    if(right_speed > 0 && right_speed < MIN_SPEED)
      right_speed = MIN_SPEED;
    if(right_speed < 0 && right_speed > -MIN_SPEED)
      right_speed = -MIN_SPEED;

/* define Shift_speed for version under 1.4*/
#ifndef  SHIFT_SPEED
     left_speed *= 256;
     right_speed *= 256;
#endif


    kmot_SetPoint( mot1, kMotRegSpeed, left_speed);
    kmot_SetPoint( mot2, kMotRegSpeed, right_speed);

    //printf("lens = %d, rsens = %d lspd = %d rspd = %d\r\n", (int)lspeed16, (int)rspeed16, left_speed, right_speed);	

    left_speed = kmot_GetMeasure( mot1 , kMotMesSpeed );
    right_speed = kmot_GetMeasure( mot2 , kMotMesSpeed );

    /* Get the new position of the wheel to compare with previous values */
    pos_left = kmot_GetMeasure( mot1 , kMotRegPos );
    pos_right = kmot_GetMeasure( mot2 , kMotRegPos );


    if((pos_left < (prevpos_left + 700)) && (pos_left > (prevpos_left -700)) && (pos_right < (prevpos_right + 700)) && (pos_right > (prevpos_right -700)))
    {
    	
    	//printf("==> Immobility\n");
    	
      if(++immobility > 5)
      {
         left_speed = RotSpeedL;
         right_speed = RotSpeedR;
#ifndef  SHIFT_SPEED
         left_speed *= 256;
         right_speed *= 256;
#endif
         kmot_SetPoint( mot1, kMotRegSpeed, left_speed);
         kmot_SetPoint( mot2, kMotRegSpeed, right_speed);

				 do{
						usleep(10);
						kh3_proximity_ir((char *)buffer, dsPic);
				 }while (((buffer[7] | (buffer[8]<<8) ) >250) || ((buffer[9] | (buffer[10]<<8)) >250));

         immobility = 0;
         prevpos_left = pos_left;
         prevpos_right = pos_right;
      }
    }
    else
    {
       immobility = 0;
       prevpos_left = pos_left;
       prevpos_right = pos_right;
    }

    usleep(20000); 
  
  	
  	ioctl(porthandle, FIONREAD, &readable_size); // get number of bytes available to be read
  	
  	if (readable_size>0)
		{	
    	out=process_command(); // warning: if braitenberg 0 or 1, nested loop
   	} // if (readable_size>0)
  
  } while(!out);
  
  
  kmot_SetMode( mot1 , kMotModeStopMotor );
	kmot_SetMode( mot2 , kMotModeStopMotor );
  
  tcflush (porthandle, TCIFLUSH); // clear the read buffer
  fcntl(porthandle, F_SETFL, 0); // blocking input
  
  printf("Braitenberg mode exit\n");
  
  return 0;
}
Пример #21
0
// This Task assumes that pEntry is already unlinked from any lists it may
// have been related to.
//
static void Task_RunQueueEntry(void *pEntry, int iUnused)
{
    UNUSED_PARAMETER(iUnused);

    BQUE *point = (BQUE *)pEntry;
    dbref executor = point->executor;

    if (  Good_obj(executor)
       && !Going(executor))
    {
        giveto(executor, mudconf.waitcost);
        mudstate.curr_enactor = point->enactor;
        mudstate.curr_executor = executor;
        a_Queue(Owner(executor), -1);
        point->executor = NOTHING;
        if (!Halted(executor))
        {
            // Load scratch args.
            //
            for (int i = 0; i < MAX_GLOBAL_REGS; i++)
            {
                if (mudstate.global_regs[i])
                {
                    RegRelease(mudstate.global_regs[i]);
                    mudstate.global_regs[i] = NULL;
                }
                mudstate.global_regs[i] = point->scr[i];
                point->scr[i] = NULL;
            }

            char *command = point->comm;

            mux_assert(!mudstate.inpipe);
            mux_assert(mudstate.pipe_nest_lev == 0);
            mux_assert(mudstate.poutobj == NOTHING);
            mux_assert(!mudstate.pout);

            break_called = false;
            while (  command
                  && !break_called)
            {
                mux_assert(!mudstate.poutnew);
                mux_assert(!mudstate.poutbufc);

                char *cp = parse_to(&command, ';', 0);

                if (  cp
                   && *cp)
                {
                    // Will command be piped?
                    //
                    if (  command
                       && *command == '|'
                       && mudstate.pipe_nest_lev < mudconf.ntfy_nest_lim)
                    {
                        command++;
                        mudstate.pipe_nest_lev++;
                        mudstate.inpipe = true;

                        mudstate.poutnew  = alloc_lbuf("process_command.pipe");
                        mudstate.poutbufc = mudstate.poutnew;
                        mudstate.poutobj  = executor;
                    }
                    else
                    {
                        mudstate.inpipe = false;
                        mudstate.poutobj = NOTHING;
                    }

                    CLinearTimeAbsolute ltaBegin;
                    ltaBegin.GetUTC();
                    MuxAlarm.Set(mudconf.max_cmdsecs);
                    CLinearTimeDelta ltdUsageBegin = GetProcessorUsage();

                    char *log_cmdbuf = process_command(executor, point->caller,
                        point->enactor, point->eval, false, cp, point->env,
                        point->nargs);

                    CLinearTimeAbsolute ltaEnd;
                    ltaEnd.GetUTC();
                    if (MuxAlarm.bAlarmed)
                    {
                        notify(executor, "GAME: Expensive activity abbreviated.");
                        s_Flags(point->enactor, FLAG_WORD1, Flags(point->enactor) | HALT);
                        s_Flags(point->executor, FLAG_WORD1, Flags(point->executor) | HALT);
                        halt_que(point->enactor, NOTHING);
                        halt_que(executor, NOTHING);
                    }
                    MuxAlarm.Clear();

                    CLinearTimeDelta ltdUsageEnd = GetProcessorUsage();
                    CLinearTimeDelta ltd = ltdUsageEnd - ltdUsageBegin;
                    db[executor].cpu_time_used += ltd;

                    ltd = ltaEnd - ltaBegin;
                    if (ltd > mudconf.rpt_cmdsecs)
                    {
                        STARTLOG(LOG_PROBLEMS, "CMD", "CPU");
                        log_name_and_loc(executor);
                        char *logbuf = alloc_lbuf("do_top.LOG.cpu");
                        mux_sprintf(logbuf, LBUF_SIZE, " queued command taking %s secs (enactor #%d): ",
                            ltd.ReturnSecondsString(4), point->enactor);
                        log_text(logbuf);
                        free_lbuf(logbuf);
                        log_text(log_cmdbuf);
                        ENDLOG;
                    }
                }

                // Transition %| value.
                //
                if (mudstate.pout)
                {
                    free_lbuf(mudstate.pout);
                    mudstate.pout = NULL;
                }
                if (mudstate.poutnew)
                {
                    *mudstate.poutbufc = '\0';
                    mudstate.pout = mudstate.poutnew;
                    mudstate.poutnew  = NULL;
                    mudstate.poutbufc = NULL;
                }
            }

            // Clean up %| value.
            //
            if (mudstate.pout)
            {
                free_lbuf(mudstate.pout);
                mudstate.pout = NULL;
            }
            mudstate.pipe_nest_lev = 0;
            mudstate.inpipe = false;
            mudstate.poutobj = NOTHING;
        }
    }

    for (int i = 0; i < MAX_GLOBAL_REGS; i++)
    {
        if (point->scr[i])
        {
            RegRelease(point->scr[i]);
            point->scr[i] = NULL;
        }

        if (mudstate.global_regs[i])
        {
            RegRelease(mudstate.global_regs[i]);
            mudstate.global_regs[i] = NULL;
        }
    }

    MEMFREE(point->text);
    point->text = NULL;
    free_qentry(point);
}
Пример #22
0
/**** Main program ***********************************************************/
int main( int argc, char *argv[])
{
  char Buffer[MAXBUFFERSIZE];
 
 	
	
  printf("Khepera3 server program (C) K-Team S.A\r\n");

	


  if(!initKH3())
  {
    printf("Init ok...\r\n");

   kh3_revision((char *)Buffer, dsPic);
   printf("\r\n%c,%4.4u,%4.4u => Version = %u, Revision = %u\r\n",
           Buffer[0], (Buffer[1] | Buffer[2]<<8), (Buffer[3] | Buffer[4]<<8),
           (Buffer[1] | Buffer[2]<<8), (Buffer[3] | Buffer[4]<<8));


		if (argc == 2)
		{
			strcpy(Buffer,argv[1]); // use serial port given by parameter
		}
		else
		{
			strcpy(Buffer,SERIAL_PORT); // copy default
		}

		// open serial port
		if ((porthandle=com_connect(Buffer,BAUDRATE))<0)
		{
			printf("\nError: Serial port %s could not be open!\n",Buffer);
			return -1;
		}

		printf("\nParsing commands from serial port %s, baudrate %ld.\nPush CTRL-C for quitting!\n",Buffer,VAL_BAUDRATE);

		// loop
 		while (!quitReq) 
    {


			#ifdef DEBUG
      	printf("\n> ");
      #endif
			process_command();  

			
    }

    printf("Exiting...\r\n");
	}
	else
	  printf("Fatal error, unable to initialize\r\n");
	
	// close serial port	
	if (porthandle>=0)
		close(porthandle);
		  
	return 0;  
}
Пример #23
0
int main(int argc, char **argv)
{
    char *buf = NULL;
    int rc = 0;
    (void)argc;
#if (defined __MWERKS__)
    extern tSIOUXSettings SIOUXSettings;
    SIOUXSettings.asktosaveonclose = 0;
    SIOUXSettings.autocloseonquit = 1;
    SIOUXSettings.rows = 40;
    SIOUXSettings.columns = 120;
#endif

    printf("\n");

    if (!PHYSFS_init(argv[0]))
    {
        printf("PHYSFS_init() failed!\n  reason: %s.\n", PHYSFS_getLastError());
        return(1);
    } /* if */

    output_versions();
    output_archivers();

    open_history_file();

    printf("Enter commands. Enter \"help\" for instructions.\n");

    do
    {
#if (defined PHYSFS_HAVE_READLINE)
        buf = readline("> ");
#else
        int i;
        buf = (char *) malloc(512);
        memset(buf, '\0', 512);
        printf("> ");
        for (i = 0; i < 511; i++)
        {
            int ch = fgetc(stdin);
            if (ch == EOF)
            {
                strcpy(buf, "quit");
                break;
            } /* if */
            else if ((ch == '\n') || (ch == '\r'))
            {
                buf[i] = '\0';
                break;
            } /* else if */
            else if (ch == '\b')
            {
                if (i > 0)
                    i--;
            } /* else if */
            else
            {
                buf[i] = (char) ch;
            } /* else */
        } /* for */
#endif

        rc = process_command(buf);
        if (buf != NULL)
            free(buf);
    } while (rc);

    if (!PHYSFS_deinit())
        printf("PHYSFS_deinit() failed!\n  reason: %s.\n", PHYSFS_getLastError());

    if (history_file)
        fclose(history_file);

/*
    printf("\n\ntest_physfs written by ryan c. gordon.\n");
    printf(" it makes you shoot teh railgun bettar.\n");
*/

    return(0);
} /* main */
/*
	main

	Initiate communication with the XBee module, then accept AT commands from
	STDIO, pass them to the XBee module and print the result.
*/
int main( void)
{
    char cmdstr[80];
    int status;
    uint16_t t;


    if (xbee_dev_init( &my_xbee, &XBEE_SERPORT, xbee_awake_pin, xbee_reset_pin))
    {
        printf( "Failed to initialize device.\n");
        return 0;
    }

    //xbee_dev_reset( &my_xbee);
    // give the XBee 500ms to wake up after resetting it (or exit if it
    // receives a packet)
    t = XBEE_SET_TIMEOUT_MS(500);
    while (! XBEE_CHECK_TIMEOUT_MS(t) && xbee_dev_tick( &my_xbee) <= 0);

    // Initialize the AT Command layer for this XBee device and have the
    // driver query it for basic information (hardware version, firmware version,
    // serial number, IEEE address, etc.)
    xbee_cmd_init_device( &my_xbee);
    printf( "Waiting for driver to query the XBee device...\n");
    do {
        xbee_dev_tick( &my_xbee);
        status = xbee_cmd_query_status( &my_xbee);
    } while (status == -EBUSY);
    if (status)
    {
        printf( "Error %d waiting for query to complete.\n", status);
    }

    // report on the settings
    xbee_dev_dump_settings( &my_xbee, XBEE_DEV_DUMP_FLAG_DEFAULT);

    printATCmds( &my_xbee);
    printf("Target setting for remote commands:\n");
    printf(" > addr   (addr is hex ieee addr, high bytes assumed 0013a200)\n");
    printf(" >        (reset to local device)\n");
    printf(" <        (reinstate previous remote target)\n");

    while (1)
    {
        while (xbee_readline( cmdstr, sizeof cmdstr) == -EAGAIN)
        {
            xbee_dev_tick( &my_xbee);
        }

        if (! strncmpi( cmdstr, "menu", 4))
        {
            printATCmds( &my_xbee);
        }
        else if (! strcmpi( cmdstr, "quit"))
        {
            return 0;
        }
        else if ( cmdstr[0] == '>')
        {
            have_target = set_target( cmdstr+1, &target_ieee);
        }
        else if ( cmdstr[0] == '<')
        {
            if (ever_had_target)
            {
                have_target = 1;
                printf("Reinstating %" PRIsFAR "\n",
                       addr64_format(cmdstr, &target_ieee));
            }
            else
            {
                printf("Nothing to reinstate\n");
            }
        }
        else
        {
            have_target ?
            process_command_remote( &my_xbee, cmdstr, &target_ieee) :
            process_command( &my_xbee, cmdstr);
        }
    }
}
Пример #25
0
int
main(int argc, char *argv[])
{
  int opt;

  setlocale(LC_CTYPE, "");

  while ((opt = getopt(argc, argv, "d")) != -1) {
	switch (opt) {
	case 'd':
	  debug_level ++;
	  break;
	}
  }

  if (debug_level == 0) fclose(stderr);

  if (uim_init() < 0) {
	debug_printf(DEBUG_ERROR, "uim_init failed\n");
	return -1;
  }

  atexit(cleanup);


  a_printf("OK\n");

  while (1) {
	int cid, serial;
	char *p1, *p2, *c;
	char buf[2048], keyname[32];
	uim_key ukey;

	fflush(stdout);

	if (fgets(buf, sizeof (buf), stdin) == NULL) {
	  if (feof(stdin))
	    debug_printf(DEBUG_NOTE, "unexpected EOF\n");
	  else
	    debug_printf(DEBUG_ERROR, "failed to read command: %s\n",
			 strerror (errno));
	  goto QUIT;
	}

	p1 = buf;
	serial = -1;

	/*
	  command format 
	    serial CID COMMAND OPTION

	  key format
	    serial CID [keyvector]
	*/

	if ((p2 = strchr(p1, ' ')) == NULL) {
	  debug_printf(DEBUG_WARNING, "input error: space after 1st string\n");
	  goto ERROR;
	}

	/* 1st string must be digit */
	*p2 = '\0';
	serial = strtol(p1, &c, 10);
	if (c != p2) {
	  debug_printf(DEBUG_WARNING, "input error: invalid serial %d\n", serial);
	  goto ERROR;
	}

	p1 = p2 + 1;
	if ((p2 = strchr(p1, ' ')) == NULL) {
	  debug_printf(DEBUG_WARNING, "input error: no space after 2nd string\n");
	  goto ERROR;
	}

	/* 2nd string must be digit */
	*p2 = '\0';
	cid = strtol(p1, &c, 10);
	if (c != p2) {
	  debug_printf(DEBUG_WARNING, "invalid cid %d\n", cid);
	  goto ERROR;
	}

	/* 3rd string */
	p1 = p2 + 1;

	if (*p1 == '[') {
	  /* keyvector if 3rd string starts with [  */

	  if ((p2 = strchr(p1, ']')) == NULL) {
		/* no corresponding ]  */
		debug_printf(DEBUG_WARNING, "']' not found\n");
		goto ERROR;
	  }

	  p2 ++; 
	  if (*p2 == ']') p2 ++; /* for [X-]] */
	  *p2 = '\0';   /* replace character after ] with \0  */

	  ukey.mod = 0;
	  ukey.key = -1;
	  keyname[0] = '\0';


	  if (analyze_keyvector(p1, &ukey, keyname, sizeof(keyname)) > 0) {

	  	a_printf("( %d %d ", serial, cid);
		if (process_keyvector(serial, cid, ukey, keyname) < 0)
		  a_printf(" ( f ) ");
		else
		  a_printf(" ( a ) ");

		a_printf(" )\n");
		fflush(stdout);

		continue;
	  }

	  goto ERROR;


	} else if (*p1 >= 'A' && *p1 <= 'Z') {
	  /* command */

	  if (strncmp(p1, "QUIT", 4) == 0) goto QUIT;

	  a_printf("( %d %d ", serial, cid);
	  if (process_command(serial, cid, p1) < 0) {
		debug_printf(DEBUG_WARNING, "command error\n");
		a_printf(" ( f ) ");   /* command error */
	  } else {
		a_printf(" ( a ) ");   /* command ok */
	  }

	  a_printf(" )\n");
	  fflush(stdout);

	  continue;
	}
  
	debug_printf(DEBUG_WARNING, "invalid input\n");
	
  ERROR:
	a_printf("( %d 0 ( x ) )\n", serial);
	fflush(stdout);
  }

 QUIT:

  uim_quit();
  return 0;
}
Пример #26
0
void
do_force(int descr, dbref player, const char *what, char *command)
{
	dbref victim, loc;
	struct match_data md;

	assert(what != NULL);
	assert(command != NULL);
	assert(player > 0);

	if (force_level > (tp_max_force_level - 1)) {
		notify(player, "Can't force recursively.");
		return;
	}

	if (!tp_zombies && (!Wizard(player) || Typeof(player) != TYPE_PLAYER)) {
		notify(player, "Zombies are not enabled here.");
		return;
#ifdef DEBUG	
	} else {
		notify(player, "[debug] Zombies are not enabled for nonwizards -- force succeeded.");
#endif
	}

	/* get victim */
	init_match(descr, player, what, NOTYPE, &md);
	match_neighbor(&md);
	match_possession(&md);
	match_me(&md);
	match_here(&md);
	match_absolute(&md);
	match_registered(&md);
	match_player(&md);

	if ((victim = noisy_match_result(&md)) == NOTHING) {
#ifdef DEBUG
		notify(player, "[debug] do_force: unable to find your target!");
#endif /* DEBUG */
		return;
	}

	if (Typeof(victim) != TYPE_PLAYER && Typeof(victim) != TYPE_THING) {
		notify(player, "Permission Denied -- Target not a player or thing.");
		return;
	}
#ifdef GOD_PRIV
	if (God(victim)) {
		notify(player, "You cannot force God to do anything.");
		return;
	}
#endif							/* GOD_PRIV */

/*    if (!controls(player, victim)) {
 *	notify(player, "Permission denied. (you're not a wizard!)");
 *	return;
 *    }
 */

	if (!Wizard(player) && !(FLAGS(victim) & XFORCIBLE)) {
		notify(player, "Permission denied: forced object not @set Xforcible.");
		return;
	}
	if (!Wizard(player) && !test_lock_false_default(descr, player, victim, MESGPROP_FLOCK)) {
		notify(player, "Permission denied: Object not force-locked to you.");
		return;
	}

	loc = getloc(victim);
	if (!Wizard(player) && Typeof(victim) == TYPE_THING && loc != NOTHING &&
		(FLAGS(loc) & ZOMBIE) && Typeof(loc) == TYPE_ROOM) {
		notify(player, "Sorry, but that's in a no-puppet zone.");
		return;
	}

	if (!Wizard(OWNER(player)) && Typeof(victim) == TYPE_THING) {
		const char *ptr = NAME(victim);
		char objname[BUFFER_LEN], *ptr2;

		if ((FLAGS(player) & ZOMBIE)) {
			notify(player, "Permission denied -- you cannot use zombies.");
			return;
		}
		if (FLAGS(victim) & DARK) {
			notify(player, "Permission denied -- you cannot force dark zombies.");
			return;
		}
		for (ptr2 = objname; *ptr && !isspace(*ptr);)
			*(ptr2++) = *(ptr++);
		*ptr2 = '\0';
		if (lookup_player(objname) != NOTHING) {
			notify(player, "Puppet cannot share the name of a player.");
			return;
		}
	}

	log_status("FORCED: %s(%d) by %s(%d): %s", NAME(victim),
			   victim, NAME(player), player, command);
	/* force victim to do command */
	force_prog=NOTHING;
	force_level++;
	process_command(dbref_first_descr(victim), victim, command);
	force_level--;
	force_prog=NOTHING;
}
Пример #27
0
static ssize_t
spd_proc_write(
        struct file *file,
        const char __user *data,
        size_t data_len,
        loff_t *pos)
{
    size_t bytes_read = 0;

    DEBUG_LOW(proc, "Write of %d bytes.", (int) data_len);
    while (bytes_read < data_len)
    {
        struct KernelSpdCommand command;
        int status;

        if (data_len < sizeof command)
        {
            DEBUG_FAIL(
                    proc,
                    "Data length %d less than sizeof command %d bytes.",
                    (int) data_len,
                    (int) sizeof command);

            bytes_read = -EFAULT;
            break;
        }

        status = copy_from_user(&command, data, sizeof command);
        if (status != 0)
        {
            DEBUG_FAIL(proc, "Copy from user failed.");
            bytes_read = -EFAULT;
            break;
        }

        if (command.bytecount < sizeof command)
        {
            DEBUG_FAIL(
                    proc,
                    "Command bytecount %d less than command size %d.",
                    (int) command.bytecount,
                    (int) sizeof command);

            bytes_read = -EINVAL;
            break;
        }

        if (command.bytecount > KERNELSPD_PROCFS_COMMAND_BYTECOUNT_MAX)
        {
            DEBUG_FAIL(
                    proc,
                    "Command bytecount %d bigger than max command size %d.",
                    (int) command.bytecount,
                    (int) KERNELSPD_PROCFS_COMMAND_BYTECOUNT_MAX);

            bytes_read = -EINVAL;
            break;
        }

        if (command.bytecount > data_len - bytes_read)
        {
            DEBUG_FAIL(
                    proc,
                    "Command bytecount %d bigger than data_len %d.",
                    (int) command.bytecount,
                    (int) data_len);

            bytes_read = -EINVAL;
            break;
        }

        bytes_read += sizeof command;

        status =
            process_command(
                    &command,
                    data + bytes_read,
                    command.bytecount - sizeof command);

        if (status < 0)
        {
            bytes_read = status;
            break;
        }

        bytes_read += command.bytecount;
    }

    return bytes_read;
}
Пример #28
0
/*
 * source filename
 */
static int 
do_source(char *inputfilename, int lineno, int argc, char **argv)
{
    char *script;
    char buf[BUFSIZ];
    FILE *fp;
    Bool used_stdin = False;
    int len;
    int errors = 0, status;
    int sublineno = 0;
    char **subargv;
    int subargc;
    Bool prompt = False;		/* only true if reading from tty */

    if (argc != 2 || !argv[1]) {
	prefix (inputfilename, lineno);
	badcommandline (argv[0]);
	return 1;
    }

    script = argv[1];

    fp = open_file (&script, "r", &used_stdin, inputfilename, lineno, argv[0]);
    if (!fp) {
	return 1;
    }

    if (verbose && used_stdin && isatty (fileno (fp))) prompt = True;

    while (!alldone) {
	buf[0] = '\0';
	if (prompt) {
	    printf ("xauth> ");
	    fflush (stdout);
	}
	if (fgets (buf, sizeof buf, fp) == NULL) break;
	sublineno++;
	len = strlen (buf);
	if (len == 0 || buf[0] == '#') continue;
	if (buf[len-1] != '\n') {
	    prefix (script, sublineno);
	    fprintf (stderr, "line too long\n");
	    errors++;
	    break;
	}
	buf[--len] = '\0';		/* remove new line */
	subargv = split_into_words (buf, &subargc);
	if (subargv) {
	    status = process_command (script, sublineno, subargc, subargv);
	    free ((char *) subargv);
	    errors += status;
	} else {
	    prefix (script, sublineno);
	    fprintf (stderr, "unable to break line into words\n");
	    errors++;
	}
    }

    if (!used_stdin) {
	(void) fclose (fp);
    }
    return errors;
}
Пример #29
0
/* Forward a simple one-liner command downstream.
 * For example, get, incr/decr, delete, etc.
 * The response, though, might be a simple line or
 * multiple VALUE+END lines.
 */
bool cproxy_forward_a2a_simple_downstream(downstream *d,
                                          char *command, conn *uc) {
    assert(d != NULL);
    assert(d->ptd != NULL);
    assert(d->ptd->proxy != NULL);
    assert(d->downstream_conns != NULL);
    assert(command != NULL);
    assert(uc != NULL);
    assert(uc->item == NULL);
    assert(uc->cmd_curr != -1);
    assert(d->multiget == NULL);
    assert(d->merger == NULL);

    // Handles get and gets.
    //
    if (uc->cmd_curr == PROTOCOL_BINARY_CMD_GET) {
        // Only use front_cache for 'get', not for 'gets'.
        //
        mcache *front_cache =
            (command[3] == ' ') ? &d->ptd->proxy->front_cache : NULL;

        return multiget_ascii_downstream(d, uc,
                                         a2a_multiget_start,
                                         a2a_multiget_skey,
                                         a2a_multiget_end,
                                         front_cache);
    }

    assert(uc->next == NULL);

    if (uc->cmd_curr == PROTOCOL_BINARY_CMD_FLUSH)
        return cproxy_broadcast_a2a_downstream(d, command, uc,
                                               "OK\r\n");

    if (uc->cmd_curr == PROTOCOL_BINARY_CMD_STAT) {
        if (strncmp(command + 5, " reset", 6) == 0)
            return cproxy_broadcast_a2a_downstream(d, command, uc,
                                                   "RESET\r\n");

        if (cproxy_broadcast_a2a_downstream(d, command, uc,
                                            "END\r\n")) {
            d->merger = genhash_init(512, skeyhash_ops);
            return true;
        } else {
            return false;
        }
    }

    // TODO: Inefficient repeated scan_tokens.
    //
    int      cmd_len = 0;
    token_t  tokens[MAX_TOKENS];
    size_t   ntokens = scan_tokens(command, tokens, MAX_TOKENS, &cmd_len);
    char    *key     = tokens[KEY_TOKEN].value;
    int      key_len = tokens[KEY_TOKEN].length;

    if (ntokens <= 1) { // This was checked long ago, while parsing
        assert(false);  // the upstream conn.
        return false;
    }

    // Assuming we're already connected to downstream.
    //
    bool self = false;

    conn *c = cproxy_find_downstream_conn(d, key, key_len,
                                          &self);
    if (c != NULL) {
        if (self) {
            // TODO: This optimization could be done much earlier,
            // even before the upstream conn was assigned
            // to a downstream.
            //
            cproxy_optimize_to_self(d, uc, command);
            process_command(uc, command);
            return true;
        }

        if (cproxy_prep_conn_for_write(c)) {
            assert(c->state == conn_pause);

            out_string(c, command);

            if (settings.verbose > 1)
                fprintf(stderr, "forwarding to %d, noreply %d\n",
                        c->sfd, uc->noreply);

            if (update_event(c, EV_WRITE | EV_PERSIST)) {
                d->downstream_used_start = 1;
                d->downstream_used       = 1;

                if (cproxy_dettach_if_noreply(d, uc) == false) {
                    cproxy_start_downstream_timeout(d, c);
                } else {
                    c->write_and_go = conn_pause;

                    // Do mcache_delete() here only during a noreply,
                    // otherwise for with-reply requests, we could
                    // be in a race with other clients repopulating
                    // the front_cache.  For with-reply requests, we
                    // clear the front_cache when we get a success reply.
                    //
                    mcache_delete(&d->ptd->proxy->front_cache, key, key_len);
                }

                return true;
            }

            if (settings.verbose > 1)
                fprintf(stderr, "Couldn't update cproxy write event\n");

            d->ptd->stats.stats.err_oom++;
            cproxy_close_conn(c);
        } else {
            d->ptd->stats.stats.err_downstream_write_prep++;
            cproxy_close_conn(c);
        }
    }

    return false;
}
Пример #30
0
int main(int argc, char *argv[])
{
	esl_handle_t handle = {{0}};
	int count = 0;
	const char *line = NULL;
	char cmd_str[1024] = "";
	esl_config_t cfg;
	cli_profile_t *profile = NULL;
	int rv = 0;

#ifndef WIN32
	char hfile[512] = "/etc/fs_cli_history";
	char cfile[512] = "/etc/fs_cli.conf";
	char dft_cfile[512] = "/etc/fs_cli.conf";
#else
	char hfile[512] = "fs_cli_history";
	char cfile[512] = "fs_cli.conf";
	char dft_cfile[512] = "fs_cli.conf";
#endif
	char *home = getenv("HOME");
	/* Vars for optargs */
	int opt;
	static struct option options[] = {
		{"help", 0, 0, 'h'},
		{"host", 1, 0, 'H'},
		{"port", 1, 0, 'P'},
		{"user", 1, 0, 'u'},
		{"password", 1, 0, 'p'},
		{"debug", 1, 0, 'd'},
		{"execute", 1, 0, 'x'},
		{"loglevel", 1, 0, 'l'},
		{"quiet", 0, 0, 'q'},
		{0, 0, 0, 0}
	};

	char temp_host[128];
	int argv_host = 0;
	char temp_user[256];
	char temp_pass[128];
	int argv_pass = 0 ;
	int argv_user = 0 ;
	int temp_port = 0;
	int argv_port = 0;
	int temp_log = -1;
	int argv_error = 0;
	int argv_exec = 0;
	char argv_command[256] = "";
	char argv_loglevel[128] = "";
	int argv_quiet = 0;
	

	strncpy(internal_profile.host, "127.0.0.1", sizeof(internal_profile.host));
	strncpy(internal_profile.pass, "ClueCon", sizeof(internal_profile.pass));
	strncpy(internal_profile.name, "internal", sizeof(internal_profile.name));
	internal_profile.port = 8021;
	set_fn_keys(&internal_profile);


	if (home) {
		snprintf(hfile, sizeof(hfile), "%s/.fs_cli_history", home);
		snprintf(cfile, sizeof(cfile), "%s/.fs_cli_conf", home);
	}
	
	signal(SIGINT, handle_SIGINT);
#ifdef SIGQUIT
	signal(SIGQUIT, handle_SIGQUIT);
#endif
	esl_global_set_default_logger(6); /* default debug level to 6 (info) */
	
	for(;;) {
		int option_index = 0;
		opt = getopt_long(argc, argv, "H:U:P:S:u:p:d:x:l:qh?", options, &option_index);
		if (opt == -1) break;
		switch (opt)
		{
			case 'H':
				esl_set_string(temp_host, optarg);
				argv_host = 1;
				break;
			case 'P':
				temp_port= atoi(optarg);
				if (temp_port > 0 && temp_port < 65536){
					argv_port = 1;
				} else {
					printf("ERROR: Port must be in range 1 - 65535\n");
					argv_error = 1;
				}
				break;
			case 'u':
				esl_set_string(temp_user, optarg);
				argv_user = 1;
				break;
			case 'p':
				esl_set_string(temp_pass, optarg);
				argv_pass = 1;
				break;
			case 'd':
				temp_log=atoi(optarg);
				if (temp_log < 0 || temp_log > 7){
					printf("ERROR: Debug level should be 0 - 7.\n");
					argv_error = 1;
				} else {
					esl_global_set_default_logger(temp_log);
				}
				break;
			case 'x':
				argv_exec = 1;
				esl_set_string(argv_command, optarg);
				break;
			case 'l':
				esl_set_string(argv_loglevel, optarg);
				break;
			case 'q':
				argv_quiet = 1;
				break;
				
			case 'h':
			case '?':
				print_banner(stdout);
				usage(argv[0]);
				return 0;
			default:
				opt = 0;
		}
	}
	
	if (argv_error){
		printf("\n");
		return usage(argv[0]);
	}

	if (!(rv = esl_config_open_file(&cfg, cfile))) {
		rv = esl_config_open_file(&cfg, dft_cfile);
	}

	if (rv) {
		char *var, *val;
		char cur_cat[128] = "";

		while (esl_config_next_pair(&cfg, &var, &val)) {
			if (strcmp(cur_cat, cfg.category)) {
				esl_set_string(cur_cat, cfg.category);
				esl_set_string(profiles[pcount].name, cur_cat);
				esl_set_string(profiles[pcount].host, "localhost");
				esl_set_string(profiles[pcount].pass, "ClueCon");
				profiles[pcount].port = 8021;
				set_fn_keys(&profiles[pcount]);
				esl_log(ESL_LOG_DEBUG, "Found Profile [%s]\n", profiles[pcount].name);
				pcount++;
			}
			
			if (!strcasecmp(var, "host")) {
				esl_set_string(profiles[pcount-1].host, val);
			} else if (!strcasecmp(var, "user")) {
				esl_set_string(profiles[pcount-1].user, val);
			} else if (!strcasecmp(var, "password")) {
				esl_set_string(profiles[pcount-1].pass, val);
			} else if (!strcasecmp(var, "port")) {
				int pt = atoi(val);
				if (pt > 0) {
					profiles[pcount-1].port = (esl_port_t)pt;
				}
			} else if (!strcasecmp(var, "debug")) {
				int dt = atoi(val);
				if (dt > -1 && dt < 8){
					 profiles[pcount-1].debug = dt;
				}	
 			} else if(!strcasecmp(var, "loglevel")) {
 				esl_set_string(profiles[pcount-1].loglevel, val);
 			} else if(!strcasecmp(var, "quiet")) {
 				profiles[pcount-1].quiet = esl_true(val);
			} else if (!strncasecmp(var, "key_F", 5)) {
				char *key = var + 5;

				if (key) {
					int i = atoi(key);
				
					if (i > 0 && i < 13) {
						profiles[pcount-1].console_fnkeys[i - 1] = strdup(val);
					}
				}
			} 
		}
		esl_config_close_file(&cfg);
	}
	
	if (optind < argc) {
		get_profile(argv[optind], &profile);
	}
	
	if (!profile) {
		if (get_profile("default", &profile)) {
			esl_log(ESL_LOG_DEBUG, "profile default does not exist using builtin profile\n");
			profile = &internal_profile;
		}
	}

	if (temp_log < 0 ) {
		esl_global_set_default_logger(profile->debug);
	}	

	if (argv_host) {
		esl_set_string(profile->host, temp_host);
	}
	if (argv_port) {
		profile->port = (esl_port_t)temp_port;
	}

	if (argv_user) {
		esl_set_string(profile->user, temp_user);
	}

	if (argv_pass) {
		esl_set_string(profile->pass, temp_pass);
	}
	
	if (*argv_loglevel) {
		esl_set_string(profile->loglevel, argv_loglevel);
		profile->quiet = 0;
	}

	esl_log(ESL_LOG_DEBUG, "Using profile %s [%s]\n", profile->name, profile->host);
	
	if (argv_host) {
		if (argv_port && profile->port != 8021) {
			snprintf(prompt_str, sizeof(prompt_str), "freeswitch@%s:%u@%s> ", profile->host, profile->port, profile->name);
		} else {
			snprintf(prompt_str, sizeof(prompt_str), "freeswitch@%s@%s> ", profile->host, profile->name);
		}
	} else {
		snprintf(prompt_str, sizeof(prompt_str), "freeswitch@%s> ", profile->name);
	}

	if (esl_connect(&handle, profile->host, profile->port, profile->user, profile->pass)) {
		esl_global_set_default_logger(7);
		esl_log(ESL_LOG_ERROR, "Error Connecting [%s]\n", handle.err);
		if (!argv_exec) usage(argv[0]);
		return -1;
	}


	if (argv_exec){
		const char *err = NULL;

		snprintf(cmd_str, sizeof(cmd_str), "api %s\n\n", argv_command);
		esl_send_recv(&handle, cmd_str);
		if (handle.last_sr_event) {
			if (handle.last_sr_event->body) {
				printf("%s\n", handle.last_sr_event->body);
			} else if ((err = esl_event_get_header(handle.last_sr_event, "reply-text")) && !strncasecmp(err, "-err", 3)) {
				printf("Error: %s!\n", err + 4);
			}
		}

		esl_disconnect(&handle);
		return 0;
	} 

	global_handle = &handle;
	global_profile = profile;

	esl_thread_create_detached(msg_thread_run, &handle);

#ifdef HAVE_EDITLINE
	el = el_init(__FILE__, stdout, stdout, stdout);
	el_set(el, EL_PROMPT, &prompt);
	el_set(el, EL_EDITOR, "emacs");

	myhistory = history_init();

	el_set(el, EL_ADDFN, "f1-key", "F1 KEY PRESS", console_f1key);
	el_set(el, EL_ADDFN, "f2-key", "F2 KEY PRESS", console_f2key);
	el_set(el, EL_ADDFN, "f3-key", "F3 KEY PRESS", console_f3key);
	el_set(el, EL_ADDFN, "f4-key", "F4 KEY PRESS", console_f4key);
	el_set(el, EL_ADDFN, "f5-key", "F5 KEY PRESS", console_f5key);
	el_set(el, EL_ADDFN, "f6-key", "F6 KEY PRESS", console_f6key);
	el_set(el, EL_ADDFN, "f7-key", "F7 KEY PRESS", console_f7key);
	el_set(el, EL_ADDFN, "f8-key", "F8 KEY PRESS", console_f8key);
	el_set(el, EL_ADDFN, "f9-key", "F9 KEY PRESS", console_f9key);
	el_set(el, EL_ADDFN, "f10-key", "F10 KEY PRESS", console_f10key);
	el_set(el, EL_ADDFN, "f11-key", "F11 KEY PRESS", console_f11key);
	el_set(el, EL_ADDFN, "f12-key", "F12 KEY PRESS", console_f12key);

	el_set(el, EL_ADDFN, "EOF-key", "EOF (^D) KEY PRESS", console_eofkey);

	el_set(el, EL_BIND, "\033OP", "f1-key", NULL);
	el_set(el, EL_BIND, "\033OQ", "f2-key", NULL);
	el_set(el, EL_BIND, "\033OR", "f3-key", NULL);
	el_set(el, EL_BIND, "\033OS", "f4-key", NULL);


	el_set(el, EL_BIND, "\033[11~", "f1-key", NULL);
	el_set(el, EL_BIND, "\033[12~", "f2-key", NULL);
	el_set(el, EL_BIND, "\033[13~", "f3-key", NULL);
	el_set(el, EL_BIND, "\033[14~", "f4-key", NULL);
	el_set(el, EL_BIND, "\033[15~", "f5-key", NULL);
	el_set(el, EL_BIND, "\033[17~", "f6-key", NULL);
	el_set(el, EL_BIND, "\033[18~", "f7-key", NULL);
	el_set(el, EL_BIND, "\033[19~", "f8-key", NULL);
	el_set(el, EL_BIND, "\033[20~", "f9-key", NULL);
	el_set(el, EL_BIND, "\033[21~", "f10-key", NULL);
	el_set(el, EL_BIND, "\033[23~", "f11-key", NULL);
	el_set(el, EL_BIND, "\033[24~", "f12-key", NULL);

	el_set(el, EL_BIND, "\004", "EOF-key", NULL);

	el_set(el, EL_ADDFN, "ed-complete", "Complete argument", complete);
	el_set(el, EL_BIND, "^I", "ed-complete", NULL);

	if (myhistory == 0) {
		esl_log(ESL_LOG_ERROR, "history could not be initialized\n");
		goto done;
	}

	history(myhistory, &ev, H_SETSIZE, 800);
	el_set(el, EL_HIST, history, myhistory);
	history(myhistory, &ev, H_LOAD, hfile);

	el_source(el, NULL);

#endif
#ifdef WIN32
	hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
	if (hStdout != INVALID_HANDLE_VALUE && GetConsoleScreenBufferInfo(hStdout, &csbiInfo)) {
		wOldColorAttrs = csbiInfo.wAttributes;
	}
#endif

	if (!argv_quiet && !profile->quiet) {
		snprintf(cmd_str, sizeof(cmd_str), "log %s\n\n", profile->loglevel);	
		esl_send_recv(&handle, cmd_str);
	}

	print_banner(stdout);

	esl_log(ESL_LOG_INFO, "FS CLI Ready.\nenter /help for a list of commands.\n");
	printf("%s\n", handle.last_sr_reply);

	while (running) {

#ifdef HAVE_EDITLINE
		line = el_gets(el, &count);
#else
		line = basic_gets(&count);
#endif

		if (count > 1) {
			if (!esl_strlen_zero(line)) {
				char *cmd = strdup(line);
				char *p;

#ifdef HAVE_EDITLINE
				const LineInfo *lf = el_line(el);
				char *foo = (char *) lf->buffer;
#endif

				if ((p = strrchr(cmd, '\r')) || (p = strrchr(cmd, '\n'))) {
					*p = '\0';
				}
				assert(cmd != NULL);

#ifdef HAVE_EDITLINE
				history(myhistory, &ev, H_ENTER, line);
#endif
				
				if (process_command(&handle, cmd)) {
					running = 0;
				}

#ifdef HAVE_EDITLINE
				el_deletestr(el, strlen(foo) + 1);
				memset(foo, 0, strlen(foo));
#endif
				free(cmd);
			}
		}

		usleep(1000);

	}

#ifdef HAVE_EDITLINE
 done:
	history(myhistory, &ev, H_SAVE, hfile);

	/* Clean up our memory */
	history_end(myhistory);
	el_end(el);
#endif

	esl_disconnect(&handle);
	
	thread_running = 0;

	return 0;
}