Пример #1
0
bool write4 (int fd, enum DATA_ZONE zone, uint8_t addr, uint32_t buf)
{

  bool status = false;
  uint8_t recv = 0;
  uint8_t param2[2] = {0};
  uint8_t param1 = set_zone_bits (zone);

  param2[0] = addr;

  struct Command_ATSHA204 c = make_command ();

  set_opcode (&c, COMMAND_WRITE);
  set_param1 (&c, param1);
  set_param2 (&c, param2);
  set_data (&c, (uint8_t *)&buf, sizeof (buf));
  set_execution_time (&c, 0, 4000000);

  if (RSP_SUCCESS == process_command (fd, &c, &recv, sizeof (recv)));
  {
    if (0 == (int) recv)
      status = true;
  }

  return status;



}
Пример #2
0
struct octet_buffer read32 (int fd, enum DATA_ZONE zone, uint8_t addr)
{


  uint8_t param2[2] = {0};
  uint8_t param1 = set_zone_bits (zone);

  uint8_t READ_32_MASK = 0b10000000;

  param1 |= READ_32_MASK;

  param2[0] = addr;

  struct Command_ATSHA204 c = make_command ();

  set_opcode (&c, COMMAND_READ);
  set_param1 (&c, param1);
  set_param2 (&c, param2);
  set_data (&c, NULL, 0);
  set_execution_time (&c, 0, READ_AVG_EXEC);

  const unsigned int LENGTH_OF_RESPONSE = 32;
  struct octet_buffer buf = make_buffer (LENGTH_OF_RESPONSE);

  if (RSP_SUCCESS != process_command (fd, &c, buf.ptr, LENGTH_OF_RESPONSE))
    {
      free_wipe (buf.ptr, LENGTH_OF_RESPONSE);
      buf.ptr = NULL;
      buf.len = 0;
    }

  return buf;
}
Пример #3
0
bool read4 (int fd, enum DATA_ZONE zone, uint8_t addr, uint32_t *buf)
{

  bool result = false;
  uint8_t param2[2] = {0};
  uint8_t param1 = set_zone_bits (zone);

  assert (NULL != buf);

  param2[0] = addr;

  struct Command_ATSHA204 c = make_command ();

  set_opcode (&c, COMMAND_READ);
  set_param1 (&c, param1);
  set_param2 (&c, param2);
  set_data (&c, NULL, 0);
  set_execution_time (&c, 0, 1000000);


  if (RSP_SUCCESS == process_command (fd, &c, (uint8_t *)buf, sizeof (uint32_t)))
    {
      result = true;
    }

  return result;
}
Пример #4
0
struct octet_buffer get_random (int fd, bool update_seed)
{
  uint8_t *random = NULL;
  uint8_t param2[2] = {0};
  uint8_t param1 = update_seed ? 0 : 1;
  struct octet_buffer buf = {};

  random = malloc_wipe (RANDOM_RSP_LENGTH);

  struct Command_ATSHA204 c = make_command ();

  set_opcode (&c, COMMAND_RANDOM);
  set_param1 (&c, param1);
  set_param2 (&c, param2);
  set_data (&c, NULL, 0);
  set_execution_time (&c, 0, RANDOM_AVG_EXEC);

  if (RSP_SUCCESS == process_command (fd, &c, random, RANDOM_RSP_LENGTH))
    {
      buf.ptr = random;
      buf.len = RANDOM_RSP_LENGTH;
    }
  else
    CTX_LOG (DEBUG, "Random command failed");

  return buf;



}
Пример #5
0
static int call_bashfunction (lua_State *L)
{
  int no_args=lua_gettop(L);
  int retval=0;
  int i;

  WORD_LIST* list=0;
  WORD_LIST* start=0;

  for (i=0; i<no_args; i++) {
    const char* string=luaL_checkstring(L, i+1);
    if (list) {
      list->next=(WORD_LIST*) malloc(sizeof(WORD_LIST));
      list=list -> next;
    } else {
      list=(WORD_LIST*) malloc(sizeof(WORD_LIST));
      start=list;
    }
    list->word=make_word(string);
    list->next=0;
  }

  if (!list)
    retval=127;
  else {
    SIMPLE_COM* cmd=newSimpleCom(start);
    retval=execute_command(make_command(cm_simple, cmd));
  }
  lua_pushinteger(L,retval);
  return 1;
}
Пример #6
0
static int register_function (lua_State *L)
{
  const char* fnname = luaL_checkstring(L, 1);

  // old code using aliases
  //const char* fmt="luabash call %s ";
  //char* fullname=(char*) malloc(strlen(fmt)+strlen(fnname));
  //sprintf(fullname, fmt, fnname);
  //add_alias(fnname, fullname);

  WORD_LIST* wluabash=(WORD_LIST*) malloc(sizeof(WORD_LIST));
  WORD_LIST* wcall=(WORD_LIST*) malloc(sizeof(WORD_LIST));
  WORD_LIST* wfnname=(WORD_LIST*) malloc(sizeof(WORD_LIST));
  WORD_LIST* warguments=(WORD_LIST*) malloc(sizeof(WORD_LIST));
  wluabash->next = wcall;
  wcall->next=wfnname;
  wfnname->next=warguments;
  warguments->next=0;
  wluabash->word=make_word("luabash");
  wcall->word=make_word("call");
  wfnname->word=make_word(fnname);
  warguments->word=make_word("$@");

  SIMPLE_COM* call_luabash=newSimpleCom(wluabash);

  COMMAND* function_body=make_command(cm_simple, call_luabash);
  bind_function(fnname,function_body);

  return 0;
}
Пример #7
0
command_node_t
make_node(char* buffer, enum command_type type)
{
  command_node_t node = checked_malloc(sizeof(struct  command_node));
  node->next = NULL;
  node->command = make_command(buffer,type);
  return node;
}
Пример #8
0
void mplayer_gui(char **filenames, size_t num_of_files, size_t total_length, char *filepath) 
{
	// mplayer binary
	char *command = make_command("open -a " PREFS_MPLAYER_GUI_APP_NAME , filenames, num_of_files, total_length, 
								 "", "", filepath, true, false);
	
	// strdup is needed
	system(strdup(command));
}
Пример #9
0
/// \brief Filenames should end with "", total length the length of all the strings
/// filepath, to the directory to call vlc from.	
void vlc(char **filenames, size_t num_of_files, size_t total_length, 
		 char *prefix_args, char *postfix_args, char *filepath)
{
	char *command = make_command(PREFS_VLC_BINARY, filenames, num_of_files, total_length, 
								 prefix_args, postfix_args, filepath, true, false);
	
	// strdup is needed
	system(strdup(command));
}
Пример #10
0
bool check_mac (int fd, struct check_mac_encoding cm,
                unsigned int data_slot,
                struct octet_buffer challenge,
                struct octet_buffer challenge_response,
                struct octet_buffer other_data)

{
  uint8_t response = 0;
  bool result = false;
  uint8_t param1 = serialize_check_mac_mode (cm);
  uint8_t param2[2] = {0};
  const unsigned int CHALLENGE_SIZE = 32;
  const unsigned int OTHER_DATA_SIZE = 13;

  assert (NULL != challenge.ptr);
  assert (NULL != challenge_response.ptr);
  assert (NULL != other_data.ptr);
  assert (CHALLENGE_SIZE == challenge.len);
  assert (CHALLENGE_SIZE == challenge_response.len);
  assert (OTHER_DATA_SIZE == other_data.len);
  assert (data_slot <= MAX_NUM_DATA_SLOTS);

  const unsigned int DATA_LEN = CHALLENGE_SIZE * 2 + OTHER_DATA_SIZE;

  struct octet_buffer data;
  data = make_buffer(DATA_LEN);

  memcpy (data.ptr, challenge.ptr, CHALLENGE_SIZE);
  memcpy (data.ptr + CHALLENGE_SIZE, challenge_response.ptr, CHALLENGE_SIZE);
  memcpy (data.ptr + CHALLENGE_SIZE * 2, other_data.ptr, OTHER_DATA_SIZE);


  /* Param 2 is guaranteed to be less than 15 (check above) */
  param2[0] = data_slot;
  param2[1] = 0;


  struct Command_ATSHA204 c = make_command ();

  set_opcode (&c, COMMAND_CHECK_MAC);
  set_param1 (&c, param1);
  set_param2 (&c, param2);
  set_data (&c, data.ptr, data.len);
  set_execution_time (&c, 0, CHECK_MAC_AVG_EXEC);

  if (RSP_SUCCESS == process_command (fd, &c, &response, sizeof(response)))
    {
      if (0 == response)
        result = true;
    }


  return result;



}
Пример #11
0
command_t
make_subshell_command(char *buffer)
{
  command_t subshell = checked_malloc(sizeof(struct command));
  subshell->type = SUBSHELL_COMMAND; subshell->status = -1;
  enum command_type type = scan(buffer);
  command_t command = make_command(buffer, type);
  eat_whitespace();
  char c;
  if((c = get_byte(get_byte_argument)) == ')')
  {
    subshell->u.subshell_command = command;
    return subshell;
  }
  else
  {
    ungetc(c, get_byte_argument);
    command_t top = checked_malloc(sizeof(struct command)); 
    top->type = SEQUENCE_COMMAND; top->status = -1;
    top->u.command[0] = command; top->u.command[1] = NULL;
    while((c = get_byte(get_byte_argument)) != ')')
    {
      ungetc(c,get_byte_argument);
      enum command_type type = scan(buffer);

      command_t new_sequence = checked_malloc(sizeof(struct command));
      new_sequence->type = SEQUENCE_COMMAND; new_sequence->status = -1;
      new_sequence->u.command[0] = make_command(buffer, type);
      new_sequence->u.command[1] = NULL;
      command_t bottom = top;
      while(bottom->u.command[1] != NULL)
        bottom = bottom->u.command[1];
      bottom->u.command[1] = new_sequence;
    }
    command_t bottom = top;
    while(bottom->u.command[1]->u.command[1] != NULL)
      bottom = bottom->u.command[1];
    bottom->u.command[1] = bottom->u.command[1]->u.command[0];
    subshell->u.subshell_command = top;
    return subshell;
  }
}
Пример #12
0
bool lock (int fd, enum DATA_ZONE zone, uint16_t crc)
{

  uint8_t param1 = 0;
  uint8_t param2[2];
  uint8_t response;
  bool result = false;

  if (is_locked (fd, zone))
    return true;

  memcpy (param2, &crc, sizeof (param2));

  const uint8_t CONFIG_MASK = 0;
  const uint8_t DATA_MASK = 1;

  switch (zone)
    {
    case CONFIG_ZONE:
      param1 |= CONFIG_MASK;
      break;
    case DATA_ZONE:
    case OTP_ZONE:
      param1 |= DATA_MASK;
      break;
    default:
      assert (false);
    }

  struct Command_ATSHA204 c = make_command ();

  set_opcode (&c, COMMAND_LOCK);
  set_param1 (&c, param1);
  set_param2 (&c, param2);
  set_data (&c, NULL, 0);
  set_execution_time (&c, 0, LOCK_AVG_EXEC);

  if (RSP_SUCCESS == process_command (fd, &c, &response, sizeof (response)))
    {
      if (0 == response)
        {
          result = true;
          CTX_LOG (DEBUG, "Lock Successful");
        }
      else
        {
          CTX_LOG (DEBUG, "Lock Failed");
        }
    }


  return result;

}
Пример #13
0
/* Description: This functions sets the servo position given the servo number
                and the angle (note: angle = 0 denotes servo position = 128
                in terms of camera's values)
   Parameters:  number[i] = c;fd: serial port file descriptor
                servo_num: the servo which we are setting the position
                I am using 0:pan  1:tilt
   Returns:     1: If the command was successfully sent to the camera
                0: Otherwise
*/
int set_servo_position(int fd, int servo_num, int angle)
{
	// change the angle into camera's format
	int position = ZERO_POSITION + angle;
	// for servo position. I am using angle 0
	char comm[10];
	// corresponding to the default servo pos. 128
	int value[] = {servo_num, position};
	// generate the command using the values
	make_command("SV ", value, sizeof(value)/sizeof(int), comm);
	printf("servo %d new position: %d\n", servo_num, angle);
	return write_check(fd, comm, 5);      // write the command to the camera
}
Пример #14
0
/* Description: This functions starts to Track a Color. It takes in the minimum
                and maximum RGB values and outputs a type T packet. This packet
                by default returns the middle mass x and y coordinates, the
                bounding box, the number of pixles tracked, and a confidence
                values.
   cc:          the min & max RGB values of the blob to be tracked.
*/
void track_blob( int fd, color_config cc )
{
	char cmd[28];
	int value[] = {cc.rmin, cc.rmax, cc.gmin, cc.gmax, cc.bmin, cc.bmax};
	range = cc;

	make_command("TC ", value, sizeof(value)/sizeof(int), cmd);
	if(!write_check(fd, cmd, 4))
	{
		printf("ERROR; track color failed.\n");
		return;
	}
}
Пример #15
0
/// \brief Filenames should end with "", total length the length of all the strings
/// filepath, to the directory to call mplayer from.
void mplayer(char **filenames, size_t num_of_files, size_t total_length, 
			 char *prefix_args, char *postfix_args, char *filepath, bool background, bool output_file) 
{
	// mplayer binary
	char *command = make_command(PREFS_MPLAYER_BINARY, filenames, num_of_files, total_length, 
								 prefix_args, postfix_args, filepath, background,output_file);
	// printf("%s\n", command);
	// strdup is needed
	system(strdup(command));
	
	// exec
	// chdir(filepath);
	// execvp( PREFS_MPLAYER_BINARY_UN_Q, "mplayer", filenames );
}
Пример #16
0
struct mac_response perform_mac (int fd, struct mac_mode_encoding m,
                                 unsigned int data_slot,
                                 struct octet_buffer challenge)
{
  const unsigned int recv_len = 32;
  struct mac_response rsp = {0};
  rsp.status = false;
  uint8_t param1 = serialize_mac_mode (m);
  uint8_t param2[2] = {0};


  assert (data_slot <= MAX_NUM_DATA_SLOTS);
  if (!m.use_second_32_temp_key)
    assert (NULL != challenge.ptr && recv_len == challenge.len);

  /* Param 2 is guaranteed to be less than 15 (check above) */
  param2[0] = data_slot;
  param2[1] = 0;

  rsp.mac = make_buffer (recv_len);

  struct Command_ATSHA204 c = make_command ();

  set_opcode (&c, COMMAND_MAC);
  set_param1 (&c, param1);
  set_param2 (&c, param2);
  /* TODO Fix for situations not sending the challlenge */
  set_data (&c, challenge.ptr, challenge.len);
  set_execution_time (&c, 0, MAC_AVG_EXEC);

  if (RSP_SUCCESS == process_command (fd, &c, rsp.mac.ptr, recv_len))
    {
      /* Perform a check mac to ensure we have the data correct */
      rsp.meta = get_check_mac_meta_data (fd, m, data_slot);
      struct check_mac_encoding cm = {0};

      rsp.status = check_mac (fd,  cm, data_slot, challenge, rsp.mac, rsp.meta);

    }
  else
    {
      free_octet_buffer (rsp.mac);

    }

  return rsp;



}
Пример #17
0
struct octet_buffer gen_nonce (int fd, int seed_update_flag,
                              struct octet_buffer input)

{

  uint8_t *recv = NULL;
  uint8_t param1 = seed_update_flag;
  uint8_t param2[2] = {0};
  unsigned int recv_len = 0;
  struct octet_buffer response = {NULL, 0};

  assert (1 == seed_update_flag || 0 == seed_update_flag);
  assert (NULL != input.ptr);
  /* If 32, the nonce is considered a pass through and will be used
     directly by the system */
  /* If 20, the nonce will be combined with a random number */
  assert (32 == input.len || 20 == input.len);

  if (32 == input.len)
    {
      recv_len = 1;
    }
  else
    {
      recv_len = 32;
    }

  recv = malloc (recv_len);
  assert (NULL != recv);


  struct Command_ATSHA204 c = make_command ();

  set_opcode (&c, COMMAND_NONCE);
  set_param1 (&c, param1);
  set_param2 (&c, param2);
  set_data (&c, input.ptr, input.len);
  set_execution_time (&c, 0, 22000000); /* avg. 22 msec */

  if (RSP_SUCCESS == process_command (fd, &c, recv, recv_len));
  {
    response.ptr = recv;
    response.len= recv_len;
  }

  return response;



}
Пример #18
0
int main(int argc, char **argv)
{
	FILE *fh;
	int slen, rlen, retval = 0;
	char *next, *sbuf, *rbuf;

	if (argc != 2) {
		fprintf(stderr, "Syntax: %s scriptfile\n", argv[0]);
		exit(1);
	}

	fh = fopen(argv[1], "r");
	if (!fh) {
		perror("fopen");
		exit(1);
	}

	if (init() < 0)
		exit(1);

	if (l3(RFID_PROTOCOL_TCL) < 0)
		exit(1);

	printf("Protocol T=CL\n");
	/* we've established T=CL at this point */

	while (next = nextline(fh)) {
		if (!(strlen(next) >= 2 && strncmp(next, "//", 2) == 0)) {
			if (make_command(next, &sbuf, &slen)) {
				rlen = 1024;
				rbuf = calloc(rlen, 1);
				
				retval = send_command(sbuf, slen, rbuf, rlen);

				free(sbuf);
				free(rbuf);
			}
		}
		free(next);

		if (retval < 0)
			break;
	}

	rfid_reader_close(rh);
	
	exit(0);
}
Пример #19
0
static wchar_t* go_internal(PyObject *args, int captureOutput) {
	int hadError;
	wchar_t **cmd;

	cmd = make_command(args);
	if (!cmd)
		return NULL;

	wchar_t *ret = scripting_executePraatCommand(cmd, captureOutput, &hadError);
	
	if (hadError) {
		char *cret = wc2c(ret, 1);
		PyErr_SetString(g_PrPyExc, cret);
		free(cret);
		return NULL;
	}

	return ret;
}
Пример #20
0
int set_imager_config(int fd, imager_config ic)
{
   int value[8], size = 0;                 // The numbers used in the command:
   char command[26];                       // ex. CR 5 255 19 33
   if(ic.contrast != -1)                   // If ther is a change set the values
   {
	   value[size++] = CONTRAST;
	   value[size++] = ic.contrast;
   }
   if(ic.brightness != -1)
   {
	   value[size++] = BRIGHTNESS;
	   value[size++] = ic.brightness;
   }
   if(ic.colormode != -1)
   {
	   value[size++] = COLORMODE;
	   if(ic.colormode == 0)
		   value[size++] = RGB_AWT_OFF;
	   if(ic.colormode == 1)
		   value[size++] = RGB_AWT_ON;
	   if(ic.colormode == 2)
		   value[size++] = YCRCB_AWT_OFF;
	   if(ic.colormode == 3)
		   value[size++] = YCRCB_AWT_ON;
   }
   if(ic.autogain != -1)
   {
	   value[size++] = AUTOGAIN;
	   if(ic.autogain == 0)
		   value[size++] = AUTOGAIN_OFF;
	   if(ic.autogain == 1)
		   value[size++] = AUTOGAIN_ON;
   }
   // Put the values into camera's command format:
   // ex. CR 6 105 18 44
   make_command("CR ", value, size, command);
   return write_check(fd, command, 5);         // send the command to the camera
}
Пример #21
0
int
ishell() {
	char *buffer;
	char *format = malloc(9);
	struct stat s;
	command_t cmd;
	
	rl_bind_key('x', ctrl_d);

	while (strcmp((buffer=readline("timetrash ~$")), "exit")) {
		if (strlen(buffer) <= 0)
			continue;
		cmd = make_command(get_next_byte, NULL, buffer, strlen(buffer), 0, 0);
		if (cmd) {
		pid_t pid = fork();
		if (!pid) {
			pid = getpid();
			SIGNAL=pid;
			execute_command(cmd, 0, NULL);
		}
		else {
			//printf("child is %d\n", pid);
			waitpid(pid, NULL, 0);
			//sprintf(format, "/proc/%d", pid);
			/*
			while(stat(format, &s)!= 0)	
			{
				if (SIGNAL)
				{
					printf("kill\n");
					kill(pid, 0);
				}
			}*/
		}
		if (buffer)
			free(buffer);
	} }
	return 0;
}
Пример #22
0
bool write32 (int fd, enum DATA_ZONE zone, uint8_t addr,
              struct octet_buffer buf)
{

  assert (NULL != buf.ptr);
  assert (32 == buf.len);

  bool status = false;
  uint8_t recv = 0;
  uint8_t param2[2] = {0};
  uint8_t param1 = set_zone_bits (zone);

  /* If writing 32 bytes, this bit must be set in param1 */
  uint8_t WRITE_32_MASK = 0b10000000;

  param1 |= WRITE_32_MASK;

  param2[0] = addr;

  struct Command_ATSHA204 c = make_command ();

  set_opcode (&c, COMMAND_WRITE);
  set_param1 (&c, param1);
  set_param2 (&c, param2);
  set_data (&c, buf.ptr, buf.len);
  set_execution_time (&c, 0, WRITE_AVG_EXEC);

  if (RSP_SUCCESS == process_command (fd, &c, &recv, sizeof (recv)));
  {
    if (0 == (int) recv)
      status = true;
  }

  return status;



}
Пример #23
0
void
make_commands (FILE* filename, int (*get_next_byte) (void *), command_t* res)
{
  Separation_t m_sp[MAXLINE];
  makeSeparation(filename, m_sp, get_next_byte);
  if (!validate_all(m_sp)) return;
  else
  {
    int i = 0;
    while (m_sp[i]->m_line != -1)
    {
      // command_t cmd = checked_malloc(sizeof(struct command));
      command_t cmd[1];
      token_t *token_array = checked_malloc(sizeof(struct token)*128);
      tokenize(m_sp[i]->m_cmd, token_array, m_sp[i]->m_line);
      make_command(token_array, cmd);
      cmd[0]->line = m_sp[i]->m_line;
      res[i] = cmd[0];
      i++;
    }
    res[i] = NULL;
  }
}
Пример #24
0
command_stream_t make_command_stream(int (*get_next_byte) (void *), void *get_next_byte_argument)
{
  /* FIXME: Replace this with your implementation.  You may need to
     add auxiliary functions and otherwise modify the source code.
     You can also use external functions defined in the GNU C Library.  */
     token_t t = checked_malloc(sizeof(struct token));
     token_t head = t;
     t->prev = NULL;
     t->str = checked_malloc(sizeof(char));
     t->str[0] = '\0';
     t->type = EMPTY;
     char* inputStream = makeInputStream(get_next_byte, get_next_byte_argument); 
     while(1) 
     { 
      token_t temp = get_next_token(inputStream, t); 
  //printf("%s %d\n", temp->prev->str, temp->prev->type); 
  //printf("%s %d\n", temp->str, temp->type); 
      if(temp->str[0] == EOF) 
      { 
        t = temp; break; 
      } 
      t = temp; 
    } 
    t->next = NULL; 
    t = remove_whitespace(head);

  // while (t != NULL)
  // {
  //   //printf("%s %d\n", t->str, t->type);
  //   //if (t -> next != NULL) {
  //     //printf("%s %d\n", t->next->str, t->next->type);
  //   //}
  //   t = t->next;
  // }
    convert_to_simple(head);
    remove_newline(head);
  // t = head;
  // while (t != NULL)
  // {
  //    printf("%s %d\n", t->str, t->type);
  //    //if (t -> next != NULL) {
  //      //printf("%s %d\n", t->next->str, t->next->type);
  //    //}
  //    t = t->next;
  // }
    //remove_newline(head);
   //  t = head;
   //  while (t != NULL)
   //  {
   //   //printf("%s %d\n", t->str, t->type);
   //   //if (t -> next != NULL) {
   //     //printf("%s %d\n", t->next->str, t->next->type);
   //   //}
   //   t = t->next;
   // }
    command_stream_t stream = make_command(head);
    command_stream_t c = checked_malloc(sizeof(struct command_stream));
    c->head = NULL;
    c->tail = NULL;
    while(stream->head != NULL)
    {
      struct command_node *n = stream->head->next;
      stream->head->next = c->head;
      c->head = stream->head;
      stream->head = n;
    }
  // while(c->head != NULL)
  // {
  //   printf("new command\n");
  //   print_command(c->head->command);
  //   c->head = c->head->next;
  // } 
  // t = head;
  // while(t != NULL)
  // {
  //   token_command_t c = get_next_command(t);
  //   //printf("%s\n", t->str);
  //   if(c != NULL)
  //   {
  //     if(c->type == SIMPLE)
  //     {
  //       int i = 0;
  //       while(c->command->u.word[i] != '\0')
  //       {
  //         //printf("%d:%s\n", i, c->command->u.word[i]);
  //         i=i+1;
  //       }
  //     }
  //     else 
  //     {
  //       //printf("%s %d\n", t->str, c->type);
  //     }
  //     //printf("\n");
  //   }
  //   t = t->next;
  // }
    return c;
  }
Пример #25
0
/**
 * execute_fopen()
 *
 * refactor the fopen code for execute into this routine
 */
URL_FILE *
url_execute_fopen(char *url, bool forwrite, extvar_t *ev, CopyState pstate)
{
	URL_EXECUTE_FILE *file;
	int			save_errno;
	struct itimers savetimers;
	pqsigfunc	save_SIGPIPE;
	char	   *cmd;

	/* Execute command */
	Assert(strncmp(url, EXEC_URL_PREFIX, strlen(EXEC_URL_PREFIX)) == 0);
	cmd  = url + strlen(EXEC_URL_PREFIX);

	file = palloc0(sizeof(URL_EXECUTE_FILE));
	file->common.type = CFTYPE_EXEC;	/* marked as a EXEC */
	file->common.url = pstrdup(url);
	file->shexec = make_command(cmd, ev);		/* Execute command */

	/* Clear process interval timers */
	resetTimers(&savetimers);

	if (!execute_resowner_callback_registered)
	{
		RegisterResourceReleaseCallback(execute_abort_callback, NULL);
		execute_resowner_callback_registered = true;
	}

	file->handle = create_execute_handle();

	/*
	 * Preserve the SIGPIPE handler and set to default handling.  This
	 * allows "normal" SIGPIPE handling in the command pipeline.  Normal
	 * for PG is to *ignore* SIGPIPE.
	 */
	save_SIGPIPE = pqsignal(SIGPIPE, SIG_DFL);

	/* execute the user command */
	file->handle->pid = popen_with_stderr(file->handle->pipes,
										  file->shexec,
										  forwrite);
	save_errno = errno;

	/* Restore the SIGPIPE handler */
	pqsignal(SIGPIPE, save_SIGPIPE);

	/* Restore process interval timers */
	restoreTimers(&savetimers);

	if (file->handle->pid == -1)
	{
		errno = save_errno;
		pfree(file->common.url);
		pfree(file);
		ereport(ERROR,
				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
						errmsg("cannot start external table command: %m"),
						errdetail("Command: %s", cmd)));

	}

	return (URL_FILE *) file;
}
Пример #26
0
void
make_command(token_t *token_array, command_t* out_cmd)
{
  int i = 0;
  stack operator_stack= create_stack();
  // printf("%lu\n", operator_stack);
  
  // printf("%lu\n", operator_stack);
  stack command_stack = create_stack();
  // printf("%lu\n", command_stack);
  while (token_array[i]->line_num != -1)
  {
    char *token_origin = token_array[i]->word;
    char *token = eat_tail_white_space(token_origin);
    
    if (!strcmp(token, "&&") || !strcmp(token, "||") || !strcmp(token, "|") 
      || !strcmp(token, ";") || !strcmp(token, "<") || !strcmp(token, ">")
      || !strcmp(token, "(") || !strcmp(token, ")"))
    {
      if (!strcmp(token, "<")) 
      {
        char *word = eat_tail_white_space(token_array[i+1]->word);
        command_t tmp_cmd = (command_t)peer(command_stack);
        tmp_cmd->input = word;
        // free(word);
        i+=2;
        continue;
      } 
      else if (!strcmp(token, ">"))
      {
        char *word = eat_tail_white_space(token_array[i+1]->word);
        command_t tmp_cmd = (command_t)peer(command_stack);
        tmp_cmd->output = word;
        // free(word);
        i+=2;
        continue;
      }

      if (!strcmp(token, ")"))
      {
        char *oper = (char*)pop(operator_stack);
        while (strcmp(oper, "("))
        {
          pop(operator_stack);
        }
        command_t sub_cmd = checked_malloc(sizeof(struct command));
        sub_cmd->line = token_array[0]->line_num;
        command_t subshell = (command_t)pop(command_stack);
        make_subshell_command(subshell, sub_cmd);
        push(sub_cmd, command_stack);
      }
      else if (is_empty(operator_stack)) 
        push(token, operator_stack);
      else
      {
        char *oper = (char*)peer(operator_stack);
        while (strcmp(token, "(") && oper_cmp(token, oper) <= 0 && !is_empty(operator_stack))
        {
          oper = (char*)pop(operator_stack);
          command_t cmd2 = (command_t)pop(command_stack);
          command_t cmd1 = (command_t)pop(command_stack);
          command_t new_cmd = checked_malloc(sizeof(struct command));
          make_compound_command(cmd1, cmd2, oper, new_cmd);
          new_cmd->line = token_array[0]->line_num;
          push(new_cmd, command_stack);
          if (!is_empty(operator_stack))
            oper = (char*)peer(operator_stack);
        }
        
        push(token, operator_stack);
        
      }
      // if (!strcmp(token, "&&"))

    }
    else 
    {
      // command_t cmd = checked_malloc(sizeof(struct command));
      if (i > 0 && !strcmp(token_array[i - 1]->word, "("))
      {
        token_t *sub_token_array = checked_malloc(sizeof(struct token) * 128);
        tokenize(token, sub_token_array, token_array[i]->line_num);
        command_t cmd[1];
        make_command(sub_token_array, cmd);
        cmd[0]->line = token_array[0]->line_num;
        push(cmd[0], command_stack);
      }
      else
      {
        command_t cmd = checked_malloc(sizeof(struct command));
        cmd->line = token_array[0]->line_num;
        make_simple_command(token, cmd);
        push(cmd, command_stack);
      }
      // push(cmd, command_stack);
    }
    i++;
  }

  if (is_empty(operator_stack))
  {
    out_cmd[0] = (command_t)pop(command_stack);
    out_cmd[0]->line = token_array[0]->line_num;
  } 
  else
  {
    while (!is_empty(operator_stack)) 
    {
      char *oper = (char*)pop(operator_stack);
      command_t cmd2 = (command_t)pop(command_stack);
      command_t cmd1 = (command_t)pop(command_stack);
      out_cmd[0] = checked_malloc(sizeof(struct command));
      out_cmd[0]->line = token_array[0]->line_num;
      make_compound_command(cmd1, cmd2, oper, out_cmd[0]);
      push(out_cmd[0], command_stack);
    }
  }



  // free(operator_stack);
  // free(command_stack);
}
Пример #27
0
//returns an entire command stream; points to head of tree
//grabs command struct 1, operator, command struct 2 and makes them a tree
command_t make_single_command_stream (int (*get_next_byte) (void *),
         void *get_next_byte_argument, int *flag)
{
	command_t a;
	command_t b;
	command_t o;
	int position = 0;
	int check_newline = 0;

	char *token_a = read_token(get_next_byte, get_next_byte_argument, &position, check_newline);
	//check for comments, if whiteSpace in front of comment
	int i = 0;
    while(isWhiteSpace(token_a[i])){
        i++;
    }
	while (token_a[0] == '\n' || token_a[0] == '#')
	{
        position = 0;
        token_a = read_token(get_next_byte, get_next_byte_argument, &position, check_newline);	
	}

	if (token_a[position] == EOF){ 
		*flag = 1; 
		return 0;
	}
	//Checking if token_a is an operator
	int k = 0;
	while(isWhiteSpace(token_a[k])){
		k++;
	}
	if(isOperator(token_a[k])){
		fprintf(stderr, "%d: Incorrect Syntax1 \n", line_number);
		exit(1);
	}
	char op;
	char *operator = (char*)checked_malloc(5);
	if (token_a[position] == '(')
	{
		paren_number++;
		a = make_single_command_stream(get_next_byte, get_next_byte_argument, flag);
		a = make_command(NULL, a);
		operator = read_token(get_next_byte, get_next_byte_argument, &position, 0);
	} else {
		operator[0] = token_a[position];
  		token_a[position] = '\0';
		a = make_command(token_a, NULL);	
	}

 	while (*operator != EOF && *operator != ')')
	{
		k = 0;
		while(isWhiteSpace(operator[k])){
			k++;
		}
		operator += k;

		if (paren_number == 0 && *operator == ';')
			break;
		
		if (paren_number == 0 && *operator == '\n')
			break;
	
		position = 0;
		if (operator[0] == '&') {
			operator[1] = get_next_byte(get_next_byte_argument);
 			if(operator[1] == ';'){
				fprintf(stderr, "%d: Incorrect Syntax2 \n", line_number);
				exit(1);
        		}else if(operator[1] != '&')
			{
				fprintf(stderr, "%d: Incorrect Syntax3 \n", line_number);
                                exit(1);
			}
			operator[2] = '\0';
  		} else if (operator[0] == '|') {
			op = get_next_byte(get_next_byte_argument);
			if (op == '|'){
				op == '\0';
				operator[1] = '|';
				operator[2] = '\0';
			} else if( op == ';'){
		 		fprintf(stderr, "%d: Incorrect Syntax4 \n", line_number);
                exit(1);
			} else {
				operator[1] = '\0';
			}
  		} else if(operator[0] == ';' || operator[0] == EOF) {
			operator[1] = '\0';
		}  else if(operator[0] == '\n'){
			operator[0] = ';';
			operator[1] = '\0';
		}
		o = make_command(operator, NULL);

		char *token_b = read_token(get_next_byte, get_next_byte_argument, &position, check_newline);
		//check for #, even ones that start with spaces in front of #

		while (position == 0 && check_newline == 0 && token_b[position] == '\n' && o->type != SEQUENCE_COMMAND)
		{
			token_b = read_token(get_next_byte, get_next_byte_argument, &position, check_newline);
		}			 
 
		if (o->type == PIPE_COMMAND && op != '\n') {
			int i = 0;
			char store = token_b[0];
			token_b[0] = op;
			op = token_b[1];
			i++;
			while (i <= position)
			{
				token_b[i] = store;
				store = op;	
				i++;
				op = token_b[i];
			}
			position++;
			token_b[position] = store;
  		}
		//check token_b for operator or EOF
		int  w =0;
		while(isWhiteSpace(token_b[w])){
			w++;
  		}
		if(isOperator(token_b[w]) || token_b[w] == EOF){
			fprintf(stderr, "%d: Incorrect Syntax6 \n", line_number);
			exit(1);
		}	

		if (token_b[position] == '(') {
			paren_number++;
			b = make_single_command_stream(get_next_byte, get_next_byte_argument, flag);
			b = make_command(NULL, b);
			operator = read_token(get_next_byte, get_next_byte_argument, &position, check_newline);
  		} else {
			if (token_b[position-1] == '\n') {
  				operator[0] = token_b[position-1];
				token_b[position-1] = '\0';
			} else {
				operator[0] = token_b[position];
				token_b[position] = '\0';
			}
			b = make_command(token_b, NULL);	
  		}
  		a = create_command_tree(a, o, b);
	}

	if(*operator == EOF) 
		*flag = 1;
	if(paren_number != 0) 
	{
		fprintf(stderr, "%d: Invalid Syntax7", line_number);
		exit(1);
	}
  	return a;
}
Пример #28
0
int main(int argc, char *argv[])
{
  /* Define the options specific to the DNS protocol. */
  struct option long_options[] =
  {
    /* General options */
    {"help",    no_argument,       0, 0}, /* Help */
    {"h",       no_argument,       0, 0},
    {"version", no_argument,       0, 0}, /* Version */
#if 0
    {"name",    required_argument, 0, 0}, /* Name */
    {"n",       required_argument, 0, 0},
    {"download",required_argument, 0, 0}, /* Download */
    {"n",       required_argument, 0, 0},
    {"chunk",   required_argument, 0, 0}, /* Download chunk */
    {"isn",     required_argument, 0, 0}, /* Initial sequence number */
#endif

    {"delay",              required_argument, 0, 0}, /* Retransmit delay */
    {"steady",             no_argument,       0, 0}, /* Don't transmit immediately after getting a response. */
    {"max-retransmits",    required_argument, 0, 0}, /* Set the max retransmissions */
    {"retransmit-forever", no_argument,       0, 0}, /* Retransmit forever if needed */
#ifndef NO_ENCRYPTION
    {"secret",             required_argument, 0, 0}, /* Pre-shared secret */
    {"no-encryption",      no_argument,       0, 0}, /* Disable encryption */
#endif

    /* i/o options. */
    {"console", no_argument,       0, 0}, /* Enable console */
    {"exec",    required_argument, 0, 0}, /* Enable execute */
    {"e",       required_argument, 0, 0},
    {"command", no_argument,       0, 0}, /* Enable command (default) */
    {"ping",    no_argument,       0, 0}, /* Ping */

    /* Tunnel drivers */
    {"dns",     required_argument, 0, 0}, /* Enable DNS */
#if 0
    {"tcp",     optional_argument, 0, 0}, /* Enable TCP */
#endif

    /* Debug options */
    {"d",            no_argument, 0, 0}, /* More debug */
    {"q",            no_argument, 0, 0}, /* Less debug */
    {"packet-trace", no_argument, 0, 0}, /* Trace packets */

    /* Sentry */
    {0,              0,                 0, 0}  /* End */
  };

  int               c;
  int               option_index;
  const char       *option_name;

  NBBOOL            tunnel_driver_created = FALSE;
  ll_t             *drivers_to_create     = ll_create(NULL);
  uint32_t          drivers_created       = 0;

  log_level_t       min_log_level = LOG_LEVEL_WARNING;

  group = select_group_create();
  system_dns = dns_get_system();

  /* Seed with the current time; not great, but it'll suit our purposes. */
  srand((unsigned int)time(NULL));

  /* This is required for win32 support. */
  winsock_initialize();

#ifndef WIN32  
  /* set the SIGCHLD handler to SIG_IGN causing zombie child processes to be reaped automatically */
  if(signal(SIGCHLD, SIG_IGN) == SIG_ERR) 
  {
    perror("Couldn't set SIGCHLD handler to SIG_IGN");
    exit(1);
  }  
#endif

  /* Set the default log level */
  log_set_min_console_level(min_log_level);

  /* Parse the command line options. */
  opterr = 0;
  while((c = getopt_long_only(argc, argv, "", long_options, &option_index)) != -1)
  {
    switch(c)
    {
      case 0:
        option_name = long_options[option_index].name;

        /* General options */
        if(!strcmp(option_name, "help") || !strcmp(option_name, "h"))
        {
          usage(argv[0], "--help requested");
        }
        if(!strcmp(option_name, "version"))
        {
          printf(NAME" "VERSION" (client)\n");
          exit(0);
        }
        else if(!strcmp(option_name, "isn"))
        {
          uint16_t isn = (uint16_t) (atoi(optarg) & 0xFFFF);
          debug_set_isn(isn);
        }
        else if(!strcmp(option_name, "delay"))
        {
          int delay = (int) atoi(optarg);
          session_set_delay(delay);
          LOG_INFO("Setting delay between packets to %dms", delay);
        }
        else if(!strcmp(option_name, "steady"))
        {
          session_set_transmit_immediately(FALSE);
        }
        else if(!strcmp(option_name, "max-retransmits"))
        {
          controller_set_max_retransmits(atoi(optarg));
        }
        else if(!strcmp(option_name, "retransmit-forever"))
        {
          controller_set_max_retransmits(-1);
        }
#ifndef NO_ENCRYPTION
        else if(!strcmp(option_name, "secret"))
        {
          session_set_preshared_secret(optarg);
        }
        else if(!strcmp(option_name, "no-encryption"))
        {
          session_set_encryption(FALSE);
        }
#endif

        /* i/o drivers */
        else if(!strcmp(option_name, "console"))
        {
          ll_add(drivers_to_create, ll_32(drivers_created++), make_console());

/*          session = session_create_console(group, "console");
          controller_add_session(session); */
        }
        else if(!strcmp(option_name, "exec") || !strcmp(option_name, "e"))
        {
          ll_add(drivers_to_create, ll_32(drivers_created++), make_exec(optarg));

/*          session = session_create_exec(group, optarg, optarg);
          controller_add_session(session); */
        }
        else if(!strcmp(option_name, "command"))
        {
          ll_add(drivers_to_create, ll_32(drivers_created++), make_command());

/*          session = session_create_command(group, "command");
          controller_add_session(session); */
        }
        else if(!strcmp(option_name, "ping"))
        {
          ll_add(drivers_to_create, ll_32(drivers_created++), make_ping());

/*          session = session_create_ping(group, "ping");
          controller_add_session(session); */
        }

        /* Tunnel driver options */
        else if(!strcmp(option_name, "dns"))
        {
          tunnel_driver_created = TRUE;
          tunnel_driver = create_dns_driver(group, optarg);
        }
        else if(!strcmp(option_name, "tcp"))
        {
          tunnel_driver_created = TRUE;
          create_tcp_driver(optarg);
        }

        /* Debug options */
        else if(!strcmp(option_name, "d"))
        {
          if(min_log_level > 0)
          {
            min_log_level--;
            log_set_min_console_level(min_log_level);
          }
        }
        else if(!strcmp(option_name, "q"))
        {
          min_log_level++;
          log_set_min_console_level(min_log_level);
        }
        else if(!strcmp(option_name, "packet-trace"))
        {
          session_enable_packet_trace();
        }
        else
        {
          usage(argv[0], "Unknown option");
        }
        break;

      case '?':
      default:
        usage(argv[0], "Unrecognized argument");
        break;
    }
  }

  create_drivers(drivers_to_create);
  ll_destroy(drivers_to_create);

  if(tunnel_driver_created && argv[optind])
  {
    printf("It looks like you used --dns and also passed a domain on the commandline.\n");
    printf("That's not allowed! Either use '--dns domain=xxx' or don't use a --dns\n");
    printf("argument!\n");
    exit(1);
  }

  /* If no output was set, use the domain, and use the last option as the
   * domain. */
  if(!tunnel_driver_created)
  {
    /* Make sure they gave a domain. */
    if(optind >= argc)
    {
      printf("Starting DNS driver without a domain! This will only work if you\n");
      printf("are directly connecting to the dnscat2 server.\n");
      printf("\n");
      printf("You'll need to use --dns server=<server> if you aren't.\n");
      tunnel_driver = create_dns_driver_internal(group, NULL, "0.0.0.0", 53, DEFAULT_TYPES, NULL);
    }
    else
    {
      tunnel_driver = create_dns_driver_internal(group, argv[optind], "0.0.0.0", 53, DEFAULT_TYPES, NULL);
    }
  }

  /* Be sure we clean up at exit. */
  atexit(cleanup);

  /* Start the driver! */
  driver_dns_go(tunnel_driver);

  return 0;
}