Esempio n. 1
0
u32 get_random_u32(void)
{
	return (get_next_byte() << 24)
			| (get_next_byte() << 16)
			| (get_next_byte() << 8)
			| get_next_byte();
}
Esempio n. 2
0
//Create_buffer simply stores the file into a buffer
char* create_buffer(int(*get_next_byte) (void *), void *get_next_byte_argument)
{
	size_t iter = 0;
	size_t buffer_size = 1024;
	char *buffer = (char *)checked_malloc(buffer_size);
	char current_byte;

	//Iterates through entire file
	while ((current_byte = get_next_byte(get_next_byte_argument)) != EOF)
	{
		//Skips over characters included in a comment
		if (current_byte == '#')
		{
			while ((current_byte = get_next_byte(get_next_byte_argument)) != '\n')
			{
				if (current_byte == EOF)
					break;
				//fprintf(stderr, "%d", current_byte);
				//Continue iterating until the end of the comment is reached.
			}
			continue;
		}

		buffer[iter++] = current_byte;

		if (iter == buffer_size)
			buffer = (char *)checked_grow_alloc(buffer, &buffer_size);
	}
	buffer[iter] = '\0';

	fprintf(stderr, "%s", buffer);
	return buffer;
}
static void scr_notifications_draw_screen() {
		uint32_t read_address = notifications_get_current_data();
    uint8_t notification_type = get_next_byte(&read_address);
	
		switch(notification_type) {
				case NOTIFICATIONS_CATEGORY_MESSAGE:
				case NOTIFICATIONS_CATEGORY_EMAIL:
				case NOTIFICATIONS_CATEGORY_SOCIAL:
				case NOTIFICATIONS_CATEGORY_ALARM:
				case NOTIFICATIONS_CATEGORY_INCOMING_CALL:
				case NOTIFICATIONS_CATEGORY_OTHER:
				{
						uint16_t notification_id = get_next_short(&read_address);
						uint8_t page = get_next_byte(&read_address);
						uint8_t font = get_next_byte(&read_address);
						bool has_more = get_next_byte(&read_address);
					
						char* data_ptr = (char*)(0x80000000 + read_address);
						mlcd_draw_text(data_ptr, 3, 3,  MLCD_XRES - 6, MLCD_YRES - 6, font, HORIZONTAL_ALIGN_LEFT | MULTILINE);
				}
						break;
				case NOTIFICATIONS_CATEGORY_SUMMARY:
				{
						uint8_t notification_count = get_next_byte(&read_address);
				
						if (notification_count>9) {
								notification_count = 9;
						}
						mlcd_draw_digit(notification_count, 20, 20, MLCD_XRES-40, MLCD_YRES-40, 11);
				}
						break;
		}
}
Esempio n. 4
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.
  */

  char c = get_next_byte(get_next_byte_argument);
  //printf("%c",c); 

  // read into big buffer
  // iterate through buffer, capturing 2 characters (pair) at a time
  // if pair is an operator, then do stuff
  // else add pair[0] to word

  char buffer[1024] = "";
  int len = 0;
  while (c != EOF)
  {
    buffer[len]=c;
    len++;
    c = get_next_byte(get_next_byte_argument);
  }
  buffer[len++] = EOF;
  // printf("==== buffer ====\n%s\n==== end buffer ====\n", buffer);
  command_stream* command_list = malloc(sizeof(struct command_stream));
  build_command_stream_from_buffer(command_list, buffer, len);

  return command_list;
}
Esempio n. 5
0
char* read_into_buffer(int (*get_next_byte) (void *), void *get_next_byte_argument) {
    size_t n, buf_size;
    char next_byte;
    char *buf;

    buf_size = 1024;
    n = 0;
    
    buf = (char *) checked_malloc(sizeof(char)*buf_size);
    
    while ((next_byte = get_next_byte(get_next_byte_argument)) != EOF) {
        
        if (next_byte == '#') {
            next_byte = get_next_byte(get_next_byte_argument);
            while (next_byte != '\n' && next_byte != EOF)
                next_byte = get_next_byte(get_next_byte_argument);
        }
        if (next_byte != EOF) {
            buf[n] = next_byte;
            n++;
            if (n == buf_size)
                buf = checked_grow_alloc(buf, &buf_size);
        }
    }
    
    if (n < buf_size - 1) {
        buf[n] = '\0';
    } else {
        buf = (char *) checked_grow_alloc(buf, &buf_size);
        buf[n] = '\0';
    }

    return buf;
}
Esempio n. 6
0
command_stream_t make_command_stream (int (*get_next_byte) (void *), void *get_next_byte_arg)
{
  size_t count = 0;
  size_t buffer_size = 1000;
  char* buffer = checked_malloc(buffer_size);
  //create a buffer of charactors to store the readin chars
  // create buffer of input with comments stripped out
  char ch;
  do
  {
    ch = get_next_byte(get_next_byte_arg);

    if (ch == '#') // for comments: ignore everything until '\n' or EOF
    {
      ch = get_next_byte(get_next_byte_arg);
      while(ch != EOF && ch!='\n')
        ch = get_next_byte(get_next_byte_arg);
    }
    //skip all the words until \n
    if (ch!= -1)
    {
      // load into buffer
      buffer[count] = ch;
      count++;

      // expand buffer if necessary
      //if (count == INT_MAX)
      //{
      //  error(1, 0, "Line -1: Input size over INT_MAX.");
      //}
      if (count == buffer_size)
      {
        buffer_size = buffer_size * 2;
        buffer = checked_grow_alloc (buffer, &buffer_size);
      }
    }
  } while(ch != -1);
  token_stream_t return_point = convert_buffer_to_token_stream(buffer,count);
  //build command_tree
  //nuild the first command_tree
  //command_stream_t command_stream_first = init_command_stream ();
  command_t new_command_t = make_command_tree (return_point);
  add_command_to_stream(new_command_t );
  //build the rest command_tree
  while (return_point->next != NULL)
  {
    //make return_point point to next token stream
    token_stream_t temp = return_point->next;
    //free(return_point);
    return_point = temp;
    new_command_t = make_command_tree (return_point);
    add_command_to_stream(new_command_t);
  }
  return command_stream_head;
}
Esempio n. 7
0
int valid_operator(char c, char* word, enum command_type *cmd, struct linked_list *cmd_stack,
	int(*get_next_byte) (void *), void *get_next_byte_argument)
{
	char next;
	//char *tmp;
	int retval = 0;
	if (c == ';') {
		*cmd = SEQUENCE_COMMAND;
		retval = 1;
	}
	else if (c == '(' || c == ')') {
		*cmd = SUBSHELL_COMMAND;
		retval = 1;
	}
	else if (c == '|') {
		next = (char)get_next_byte(get_next_byte_argument);
		if (next == '|') {
			*cmd = OR_COMMAND;
		}
		else {
			*cmd = PIPE_COMMAND;
			char *temp = (char*)malloc(sizeof(char)*(strlen(word) - 1));
		}
		retval = 1;
	}
	else if (c == '&') {
		next = get_next_byte(get_next_byte_argument);
		if (next == '&') {
			*cmd = AND_COMMAND;
		}
		retval = 1;
	}
	if (retval) {
		//gotta push nontokenized string onto the command stack
		//FIXME:  Need to clean up this nontoken string and check for invalid syntax - as of now newlines and
		//whitespace are a-ok and we gotta check for that - suggest creating another function
		struct command simple_cmd;
		simple_cmd.u.word = (char**)malloc(sizeof(char*));
		*(simple_cmd.u.word) = (char*)malloc(sizeof(char)*strlen(word));
		**(simple_cmd.u.word) = *word;
		InsertAtHead(&simple_cmd, cmd_stack);
		//now clean up the reference variable used in the parser
		free(word);
		word = "";
		if (*cmd == PIPE_COMMAND) {
			//tmp = (char *)malloc(sizeof(char) * strlen(&next))
			//*tmp = next;
			strcat(word, &next);
		}
	}
	return retval;
}
Esempio n. 8
0
// get several bytes as specified, the bytes may cross buffer boundary
// if succeed, the location info will be updated.
int get_bytes(buf_chain_t **curr_buf_node, int *next_byte_idx, char *buf, int size)
{
    buf_chain_t *tmp_node = *curr_buf_node; 
    int tmp_nxt_idx = *next_byte_idx;
    char c;

    int i;
    for(i = 0; i < size; i++)
    {
        if(0 == get_next_byte(&tmp_node, &tmp_nxt_idx, &c))
            buf[i] = c;
        else
            break;
    }

    if(i == size)
    {
        *curr_buf_node = tmp_node;
        *next_byte_idx = tmp_nxt_idx;

        return 0;
    }
    else
    {
        return GET_BYTES_FAILED;
    }
}
Esempio n. 9
0
// get nexst field deliminated by ' '(a space)
// filling the output buffer. This may cross the buffer boundary.
// If the fucntion succeed, the location info will be updated
int get_next_field(buf_chain_t **curr_buf_node, int *next_byte_idx, char *buf, int buf_size)
{
    assert(*curr_buf_node);
    buf_chain_t *tmp_node = *curr_buf_node; 
    int tmp_nxt_idx = *next_byte_idx;
    int cnt = 0; 
    int sp_found = 0;
    char c;

    while(0 == get_next_byte(&tmp_node, &tmp_nxt_idx, &c))
    {
        if(c != ' ')
            break;
    }

    buf[0] = c;
    cnt++;


    while(0 == get_next_byte(&tmp_node, &tmp_nxt_idx, &c))
    {
        cnt++;
        if(cnt > buf_size) //space will be replaced by '\0'
            return NXT_FIELD_FAILED;

        buf[cnt - 1] = c;

        if(c == ' ')
        {
            sp_found = 1;
            break;
        }
     }

    if(sp_found == 1)
    {
        buf[cnt - 1] = '\0'; //repalce the space
        dbg_print(1, "Function:%s:%.*s\n", __FUNCTION__, cnt, buf);
        *curr_buf_node = tmp_node;
        *next_byte_idx = tmp_nxt_idx;
        return cnt;
    }
    else
    {
        return NXT_FIELD_NOMORE;
    }
}
Esempio n. 10
0
/* See comment to read_qword function, except return value. */
static inline void read_qword_only(reader_state * rs, uint_fast64_t * res)
{
    *res = (((uint_fast64_t) get_next_byte(rs))) |
        (((uint_fast64_t) get_next_byte(rs)) << 8u) |
        (((uint_fast64_t) get_next_byte(rs)) << 16u) |
        (((uint_fast64_t) get_next_byte(rs)) << 24u) |
        (((uint_fast64_t) get_next_byte(rs)) << 32u) |
        (((uint_fast64_t) get_next_byte(rs)) << 40u) |
        (((uint_fast64_t) get_next_byte(rs)) << 48u) |
        (((uint_fast64_t) get_next_byte(rs)) << 56u);
}
Esempio n. 11
0
static uint8_t get_next_literal(decompression_state *state)
{
	uint8_t c = get_next_byte(state);
	/* if (isprint(c)) {
		OC_DEBUG(3, "literal %c", c));
	} else {
		OC_DEBUG(3, "literal 0x%02x", c));
		} */
	return c;
}
	/*
static void draw_incmonig_call_notification() {
	  uint32_t read_address = m_address + 1;
    uint16_t param_1_offset = get_next_short(&read_address);
    uint16_t param_2_offset = get_next_short(&read_address);
	
	  mlcd_draw_text(I18N_TRANSLATE(MESSAGE_INCOMING_CALL), 0, 5, MLCD_XRES, 20, FONT_OPTION_NORMAL, ALIGN_CENTER);
	
	  uint8_t data[32];
		read_address = m_address + param_1_offset;
	  ext_ram_read_data(read_address, data, 32);
	  mlcd_draw_text((char*)data, 0, 60, MLCD_XRES, 20, FONT_OPTION_NORMAL, ALIGN_CENTER);
	
		read_address = m_address + param_2_offset;
	  ext_ram_read_data(read_address, data, 32);
	  mlcd_draw_text((char*)data, 0, 90, MLCD_XRES, 20, FONT_OPTION_NORMAL, ALIGN_CENTER);
}
*/
static void draw_default_notification() {
	  uint32_t read_address = m_address + 1;
    uint16_t text_offset = get_next_short(&read_address);
    uint8_t font = get_next_byte(&read_address);
    uint8_t operationsNo = get_next_byte(&read_address);
		uint16_t op1_name_offset = operationsNo>0?get_next_short(&read_address):0;
	  uint16_t op2_name_offset = operationsNo>1?get_next_short(&read_address):0;
	
		char* data_ptr = (char*)(0x80000000 + m_address + text_offset);
	  mlcd_draw_text(data_ptr, 3, 30, MLCD_XRES - 6, MLCD_YRES-60, font, HORIZONTAL_ALIGN_CENTER | MULTILINE | VERTICAL_ALIGN_CENTER);

		if (op1_name_offset != 0) {
				data_ptr = (char*)(0x80000000 + m_address + op1_name_offset);
				mlcd_draw_text(data_ptr, 3, 0, MLCD_XRES-6, 30, font, HORIZONTAL_ALIGN_RIGHT | VERTICAL_ALIGN_CENTER);
		}
		
		if (op2_name_offset != 0) {
				data_ptr = (char*)(0x80000000 + m_address + op2_name_offset);
				mlcd_draw_text(data_ptr, 3, MLCD_YRES-30, MLCD_XRES-6, 30, font, HORIZONTAL_ALIGN_RIGHT | VERTICAL_ALIGN_CENTER);
		}
}
static bool scr_notifications_handle_button_pressed(uint32_t button_id) {
	  switch (button_id) {
			  case SCR_EVENT_PARAM_BUTTON_BACK:
						scr_mngr_close_notifications();
				    return true;
			  case SCR_EVENT_PARAM_BUTTON_UP:
				{
						uint32_t read_address = notifications_get_current_data();
						uint8_t notification_type = get_next_byte(&read_address);
	
						if (notification_type != NOTIFICATIONS_CATEGORY_SUMMARY) {
								uint16_t notification_id = get_next_short(&read_address);
								uint8_t page = get_next_byte(&read_address);
								if (page > 0) {
										notifications_prev_part(notification_id, page);
								}
						}
				}
				    return true;
			  case SCR_EVENT_PARAM_BUTTON_DOWN:
				{
					
						uint32_t read_address = notifications_get_current_data();
						uint8_t notification_type = get_next_byte(&read_address);
	
						if (notification_type == NOTIFICATIONS_CATEGORY_SUMMARY) {
								//show first
								notifications_invoke_function(NOTIFICATIONS_SHOW_FIRST);
						} else {
								uint16_t notification_id = get_next_short(&read_address);
								uint8_t page = get_next_byte(&read_address);
								uint8_t font = get_next_byte(&read_address);
								bool has_more = get_next_byte(&read_address);
								if (has_more) {
										notifications_next_part(notification_id, page);
								} else {
										notifications_next(notification_id);
								}
						}
				}
				    return true;
			  case SCR_EVENT_PARAM_BUTTON_SELECT:
				{
						uint32_t read_address = notifications_get_current_data();
						uint8_t notification_type = get_next_byte(&read_address);
	
						if (notification_type != NOTIFICATIONS_CATEGORY_SUMMARY) {
								uint16_t notification_id = get_next_short(&read_address);
								notifications_open(notification_id);
						}
				}
				    return true;
		}
		return false;
}
Esempio n. 14
0
void ignoreWhiteSpace(int (*get_next_byte) (void *),
		      void *get_next_byte_argument)
{
  char c;

  while ((c = get_next_byte(get_next_byte_argument)) != EOF &&
	 (c == ' ' || c == '\n')) {
    ;
  }
  if (c != EOF) {
    _rewind(get_next_byte_argument, -1);
  }
}
Esempio n. 15
0
int gz_engine_run(void)
{
    struct color color_reg = { 0x00, 0x00, 0x00 };

    uint8_t n_leds = 0;
    uint8_t i;

    while (1)
    {
        enum op code = get_next_byte();

        switch (code)
        {
        case OP_HALT:
            return 0;
            break;

        case OP_DESCRIPTOR:
            n_leds = get_next_byte();
            break;

        case OP_COLOR:
            color_reg.r = get_next_byte();
            color_reg.g = get_next_byte();
            color_reg.b = get_next_byte();
            break;

        case OP_ALL_ON:
            for (i = 0; i < n_leds; i++)
            {
                set_led(i, color_reg.r, color_reg.g, color_reg.b);
            }
            latch_leds();
            break;

        case OP_DELAY:
        {
            uint8_t lowMs;
            uint8_t highMs;

            lowMs = get_next_byte();
            highMs = get_next_byte();
            delay((uint16_t)(highMs << 8) | lowMs);
        }
        break;

        default:
            break;
        }
    }

    return 0;
}
static bool scr_notifications_handle_button_long_pressed(uint32_t button_id) {
	  switch (button_id) {
			  case SCR_EVENT_PARAM_BUTTON_DOWN:
				{
						uint32_t read_address = notifications_get_current_data();
						uint8_t notification_type = get_next_byte(&read_address);
						if (notification_type != NOTIFICATIONS_CATEGORY_SUMMARY) {
								uint16_t notification_id = get_next_short(&read_address);
								notifications_next(notification_id);
						}				
				}
				    return true;
		}
		return false;
}
Esempio n. 17
0
file *rl_decode(const char *data, long size) {
    int i;
    byte_buffer *buff = new_buffer(size);
    memcpy(buff->buffer, data, size);

    // 1. Get size of each run.
    uchar bytes[2];
    for (i = 0; i < 2; ++i) {
        bytes[i] = get_next_byte(buff);
    }
    const ushort NUM_BITS = *((ushort *)bytes);

    // 2. Decode data
    int zeros = 1;
    int remaining = 8 * size;
    int max_len = (4 * size)/3;

    byte_buffer *output = new_buffer(max_len);
    i = 0;

    while (remaining > NUM_BITS) {
        int bits = read_length(buff, NUM_BITS);
        for (i = 0; i < bits; ++i) {
            if (zeros) {
                append_bit_to_buffer(output, 0);
            } else {
                append_bit_to_buffer(output, 1);
            }
        }
        zeros = (zeros == 0)? 1 : 0;
        remaining -= NUM_BITS;
    }

    // 3. Convert output buffer to file
    file *f = (file *)malloc(sizeof(file));
    f->size = (long)output->current_byte;
    f->data = (char *)malloc(f->size);
    memcpy(f->data, output->buffer, f->size);

    // 4. Free resources
    free_buffer(output);
    free_buffer(buff);

    return f;
}
Esempio n. 18
0
int
fillRedirectionOperands(char **input, char **output,
			int (*get_next_byte) (void *),
			void *get_next_byte_argument)
{
  int len = 0;
  TOKENTYPE type = 0;

  while (1) {
    len = 0;
    type = getTokenType(get_next_byte(get_next_byte_argument));
    switch (type) {
    case REDIRECTION1:
      type = readNextToken(input, &len, get_next_byte,
			   get_next_byte_argument);
      if (!(*input) || !strlen(*input)) {
	goto err;
      }
      break;
    case REDIRECTION2:
      type = readNextToken(output, &len, get_next_byte,
			   get_next_byte_argument);
      if (!(*output) || !strlen(*output)) {
	goto err;
      }
      break;
    default:
      _rewind(get_next_byte_argument, -1);
      goto out;
    }
    if (type == REDIRECTION2 || type == REDIRECTION1) {
      continue;
    } else {
      break;
    }
  }
 out:
  return type;
 err:
  printErr();
  return -1;
}
Esempio n. 19
0
  char* makeInputStream(int (*get_next_byte) (void *), void *get_next_byte_argument)
  {
    int inputStreamSize = 100;
    int byteCount = 0;
    int c;
    char *inputStream = (char*)checked_malloc(inputStreamSize*sizeof(char));

    while ((c = get_next_byte(get_next_byte_argument)) != EOF) {
      inputStream[byteCount] = c;
      byteCount++;

      if (byteCount == inputStreamSize) {
        inputStreamSize += 100;
        inputStream = checked_realloc(inputStream, inputStreamSize*sizeof(char));
      }
    }
    inputStream[byteCount] = EOF;
    byteCount++;

    return inputStream;
  }
Esempio n. 20
0
int
checkRedirection(int (*get_next_byte) (void *),
		 void *get_next_byte_argument)
{
  char c;
  int flag = 0;

  while ((c = get_next_byte(get_next_byte_argument)) != EOF && c == ' ') {
    ;
  }
  switch (getTokenType(c)) {
  case REDIRECTION1:
  case REDIRECTION2:
    flag = 1;
    break;
  default:
    flag = 0;
    break;
  }
  _rewind(get_next_byte_argument, -1);

  return flag;
}
Esempio n. 21
0
File: aprs.c Progetto: thasti/utrak
/*
 * get_next_bit
 *
 * fetches the next bit for the data stream.
 *
 * returns: the next bit to be transmitted, already NRZI coded and bit stuffed
 */
uint8_t get_next_bit(void) {
	static uint8_t byte = 0;
	static uint8_t bit = 1;
	static uint8_t bit_d = 0;
	if (bitcnt >= 8) {
		byte = get_next_byte();
		bitcnt = 0;
	}
	/* all bytes LSB first */
	bit = byte & 0x01;
	if (bit) {
		/* bit stuffing */
		onecnt++;
		if ((stuffing == 1) && (onecnt >= 5)) {
			/* next time the same bit will be a zero -> stuffed bit */
			byte &= ~0x01;
			onecnt = 0;
		} else {
			byte >>= 1;
			bitcnt = bitcnt + 1;
		}

	} else {
Esempio n. 22
0
/* FIXME: Define the type 'struct command_stream' here. This should
complete the incomplete type declaration in command.h. */
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. */
	if (DEBUG) printf("291 Begin make_command_stream\n");
	initStream();
	size_t sizeofBuffer = 1024;
	char* buffer = (char*)checked_malloc(sizeofBuffer);
	char curr;
	size_t filled = 0;
	while ((curr = get_next_byte(get_next_byte_argument)) != EOF) {
		buffer[filled] = curr;
		filled++;
		if (filled == sizeofBuffer) {
			sizeofBuffer *= 2;
			buffer = (char*)checked_grow_alloc(buffer, &sizeofBuffer);
		}
	}
	//***For the parser:
	//Word
	int bufferWordSize = 10;
	int currWord = 0;
	//char ** wordElement;
	char** wordElement = checked_malloc(sizeof(char*));
	wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
	int usedWord = 0;
	//Input
	int bufferInputSize = 10;
	char* inputElement = (char*)checked_malloc(bufferInputSize);
	int usedInput = 0;
	//Output
	int bufferOutputSize = 10;
	char* outputElement = (char*)checked_malloc(bufferOutputSize);
	int usedOutput = 0;
	//***Initialize operator and command stacks
	initStacks();
	if (DEBUG) printf("333 Buffer created, initStacks()\n");
	
	int i = 0;
	while (i < (int)filled)
	{
		if (DEBUG) printf("on buffer %d\n", i);
		//***When you want to add a character*************************//
		int op = -1;
		int openCount = 0;
		int closedCount = 0;

		if (buffer[i] == '`')
			error(1, 0, "Line %d: %c", __LINE__, buffer[i]);

		if (buffer[i] == '(')
		{
			openCount = 1;
			closedCount = 0;
			int x = i;
			while (x < (int) filled)
			{
				x++;
				if (buffer[x] == '(')
					openCount++;
				if (buffer[x] == ')')
					closedCount++;
				if (closedCount == openCount)
					break;
			}
			if (closedCount != openCount)
				error(1, 0, "Line %d: Expected ')' for end of subshell", __LINE__);
		}
		if(buffer[i] == ')')
		{
			if(openCount == 0)
				error(1, 0, "Line %d: Expected '(' before ')'", __LINE__);
		}

		if(buffer[i] = '(') 
		{
			op = numberOfOper(&buffer[i]);
			processOperator(op);
		}

		//Case of ' '
		while (buffer[i] == ' ' && usedWord == 0)
			i++;

		if (buffer[i] == ' ' && usedWord != 0)
		{
			if (usedWord >= bufferWordSize)
			{
				bufferWordSize += 10;
				wordElement[currWord] = (char*)checked_realloc(wordElement[currWord], bufferWordSize);
			}
			//i++;
			wordElement[currWord][usedWord] = '\0';
			while (buffer[i + 1] == ' ')
				i++;
			usedWord = 0;
			bufferWordSize = 10;
			currWord++;
			wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
			//wordElement[currWord][usedWord] = buffer[i];
			//usedWord++;
		}
		//Case of carrots
		//WHAT IF a<b>c>d<a....?! You're making a simple command out of a<b>c which then
		// must also be the word of >d<a
		//Case of '<' first
		else
			if (buffer[i] == '<')
			{
				int k = i;
				while (buffer[k-1] == ' ')
				{
					k--;
					if(buffer[k-1] == '\n')
						error(1, 0, "Line %d: Operator and word on diff lines", __LINE__);
				}
				if (wordElement[0][0] == '\0')
					error(1, 0, "Line %d: No command given to '<'", __LINE__);
				i++;
				while (buffer[i] != '<' && buffer[i] != '>' && buffer[i] != '&' && buffer[i] != '|' && buffer[i] != '(' && buffer[i] != ')' && buffer[i] != ';' && buffer[i] != '\n')
				{
					if (i == filled)
					{
						if (DEBUG) printf("378 Complete command, free buffer bc EOF\n");
						currWord++;
						wordElement[currWord] = '\0';
						if (usedInput == 0)
							inputElement = NULL;
						if (usedOutput == 0)
							outputElement = NULL;
						makeSimpleCommand(wordElement, inputElement, outputElement);
						completeCommand();
						//free(buffer);
						return headStream;
					}
					if (buffer[i] == ' ')
						i++;
					else
					{
						if (usedInput >= bufferInputSize)
						{
							bufferInputSize += 10;
							inputElement = (char*)checked_realloc(inputElement, bufferInputSize);
						}
						inputElement[usedInput] = buffer[i];
						usedInput++;
						i++;
					}
				}
				if (usedInput >= bufferInputSize)
				{
					bufferInputSize += 10;
					inputElement = (char*)checked_realloc(inputElement, bufferInputSize);
				}
				if (usedInput == 0)
					error(1, 0, "Line %d: No input after '<'", __LINE__);
				inputElement[usedInput] = '\0';
				usedInput++;
				if (buffer[i] == '>')
				{
					i++;
					while (buffer[i] != '<' && buffer[i] != '>' && buffer[i] != '&' && buffer[i] != '|' && buffer[i] != '(' && buffer[i] != ')' && buffer[i] != ';' && buffer[i] != '\n')
					{
						if (i == filled)
						{
							if (DEBUG) printf("413 Complete command, free buffer at EOF\n");
							currWord++;
							wordElement[currWord] = '\0';
							if (usedInput == 0)
								inputElement = NULL;
							if (usedOutput == 0)
								outputElement = NULL;
							makeSimpleCommand(wordElement, inputElement, outputElement);
							completeCommand();
							//free(buffer);
							return headStream;
						}
						if (buffer[i] == ' ')
							i++;
						else
						{
							if (usedOutput >= bufferOutputSize)
							{
								bufferOutputSize += 10;
								outputElement = (char*)checked_realloc(outputElement, bufferOutputSize);
							}
							outputElement[usedOutput] = buffer[i];
							usedOutput++;
							i++;
						}
					}
					if (usedOutput >= bufferOutputSize)
					{
						bufferOutputSize += 10;
						outputElement = (char*)checked_realloc(outputElement, bufferOutputSize);
					}
					if (usedOutput == 0)
						error(1, 0, "Line %d: No input after '<'", __LINE__);
					outputElement[usedOutput] = '\0';
					usedOutput++;
					//i--; //Check logic
				}
				i--;
			}
		/////CHECK FOR EXTRA i++!!!!!
		//Case of '>' first
			else
				if (buffer[i] == '>')
				{
					int k = i;
					while (buffer[k-1] == ' ')
					{
						k--;
						if(buffer[k-1] == '\n')
							error(1, 0, "Line %d: Operator and word on diff lines", __LINE__);
					}
					if (wordElement[0][0] == '\0')
					error(1, 0, "Line %d: No command given to '<'", __LINE__);
					i++;
					while (buffer[i] != '<' && buffer[i] != '>' && buffer[i] != '&' && buffer[i] != '|' && buffer[i] != '(' && buffer[i] != ')' && buffer[i] != ';' && buffer[i] != '\n')
					{
						if (i == filled)
						{
							if (DEBUG) printf("471 Complete Command, free buffer at EOF");
							currWord++;
							wordElement[currWord] = '\0';
							if (usedInput == 0)
								inputElement = NULL;
							if (usedOutput == 0)
								outputElement = NULL;
							makeSimpleCommand(wordElement, inputElement, outputElement);
							completeCommand();
							//free(buffer);
							return headStream;
						}
						if (buffer[i] == ' ')
							i++;
						else
						{
							if (usedOutput >= bufferOutputSize)
							{
								bufferOutputSize += 10;
								outputElement = (char*)checked_realloc(outputElement, bufferOutputSize);
							}
							outputElement[usedOutput] = buffer[i];
							usedOutput++;
							i++;
						}
					}
					if (usedOutput >= bufferOutputSize)
					{
						bufferOutputSize += 10;
						outputElement = (char*)checked_realloc(outputElement, bufferOutputSize);
					}
					if (usedOutput == 0)
						error(1, 0, "Line %d: No input after '<'", __LINE__);
					outputElement[usedOutput] = '\0';
					usedOutput++;
					if (buffer[i] == '<')
					{
						i++;
						while (buffer[i] != '<' && buffer[i] != '>' && buffer[i] != '&' && buffer[i] != '|' && buffer[i] != '(' && buffer[i] != ')' && buffer[i] != ';' && buffer[i] != '\n')
						{
							if (i == filled)
							{
								if (DEBUG) printf("505 Complete Command, free buffer at EOF");
								currWord++;
								wordElement[currWord] = '\0';
								if (usedInput == 0)
									inputElement = NULL;
								if (usedOutput == 0)
									outputElement = NULL;
								makeSimpleCommand(wordElement, inputElement, outputElement);
								completeCommand();
								//free(buffer);
								return headStream;
							}
							if (buffer[i] == ' ')
								i++;
							else
							{
								if (usedInput >= bufferInputSize)
								{
									bufferInputSize += 10;
									inputElement = (char*)checked_realloc(inputElement, bufferInputSize);
								}
								inputElement[usedInput] = buffer[i];
								usedInput++;
								i++;
							}
						}
						if (usedInput >= bufferInputSize)
						{
							bufferInputSize += 10;
							inputElement = (char*)checked_realloc(inputElement, bufferInputSize);
						}
						if (usedInput == 0)
							error(1, 0, "Line %d: No input after '<'", __LINE__);
						inputElement[usedInput] = '\0';
						usedInput++;
					}
					wordElement[currWord + 1] = '\0';
					/*if (usedInput == 0)
					inputElement = NULL;
					if (usedOutput == 0)
					outputElement = NULL;
					if(DEBUG) printf("makeSimpleCommand %s\n", wordElement[0]);
					makeSimpleCommand(wordElement, inputElement, outputElement);
					bufferWordSize = 10;
					currWord = 0;
					usedWord = 0;
					usedInput = 0;
					usedOutput = 0;
					wordElement = (char**)checked_malloc(sizeof(char*));
					wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
					inputElement = (char*)checked_malloc(bufferInputSize);
					outputElement = (char*)checked_malloc(bufferOutputSize);*/
					i--;
				}
		//Operators
		//After every operator is encountered, use makeSimpleCommand to push the command on the stack
		//Case of '|'
				else
					if (buffer[i] == '|')
					{
						int k = i;
						while (buffer[k-1] == ' ')
						{
							k--;
							if(buffer[k-1] == '\n')
								error(1, 0, "Line %d: Operator and word on diff lines", __LINE__);
						}
						
						if (buffer[i+1] == '|' && operatorStack == NULL)
							error(1, 0, "Line %d: Missing pipe for '||'", __LINE__);
						if (wordElement[0][0] == '\0')
							error(1, 0, "Line %d: Nothing for '|'", __LINE__);
						//if (commandStack == NULL)
						//	error(1, 0, "Line %d: Nothing to run '|' on");
						if (buffer[i + 1] == '|' && buffer[i+2] == '|')
							error(1, 0, "Line %d: Invalid Command, too many '|'", i);
						op = numberOfOper(&buffer[i]);
						//error(1, 0, "Line %d: Nothing to pipe", __LINE__);
						if (buffer[i-1] != ' ')
							currWord++;
						wordElement[currWord] = '\0';
						if (usedInput == 0)
							inputElement = NULL;
						if (usedOutput == 0)
							outputElement = NULL;
						if (DEBUG) printf(" 566 makeSimpleCommand %s\n", wordElement[0]);
						makeSimpleCommand(wordElement, inputElement, outputElement);
						bufferWordSize = 10;
						currWord = 0;
						usedWord = 0;
						usedInput = 0;
						usedOutput = 0;
						wordElement = (char**)checked_malloc(sizeof(char*));
						wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
						inputElement = (char*)checked_malloc(bufferInputSize);
						outputElement = (char*)checked_malloc(bufferOutputSize);
						if (DEBUG) printf("577 Process operator %d\n", op);
						processOperator(op);
						if (op == 3) 
							i++;
						if (buffer[i + 1] == ' ')
							i++;
						//i++;
					}
		//Case of '&'
					else
						if (buffer[i] == '&')
						{
							int k = i;
							while (buffer[k-1] == ' ')
							{
								k--;
								if(buffer[k-1] == '\n')
									error(1, 0, "Line %d: Operator and word on diff lines", __LINE__);
							}
							//if (buffer[i] == '&' && operatorStack == NULL)
							//	error(1, 0, "Line %d: Missing pipe for '&&'", __LINE__);
							if (wordElement[0][0] == '\0')
								error(1, 0, "Line %d: Nothing for '|'", __LINE__);
							if (buffer[i + 1] == '&' && buffer[i+2] == '&')
								error(1, 0, "Line %d: Invalid Command, too many '&'", i);
							op = numberOfOper(&buffer[i]);
							if (buffer[i-1] != ' ')
								currWord++;
							wordElement[currWord] = '\0';
							if (usedInput == 0)
								inputElement = NULL;
							if (usedOutput == 0)
								outputElement = NULL;
							if (DEBUG) printf("592 makeSimpleCommand %s\n", wordElement[0]);
							makeSimpleCommand(wordElement, inputElement, outputElement);
							bufferWordSize = 10;
							usedWord = 0;
							currWord = 0;
							usedInput = 0;
							usedOutput = 0;
							wordElement = (char**)checked_malloc(sizeof(char*));
							wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
							inputElement = (char*)checked_malloc(bufferInputSize);
							outputElement = (char*)checked_malloc(bufferOutputSize);
							processOperator(op);
							i++;
							if (buffer[i + 1] == ' ')
								i++;
						}
		//Case of ';'
						else
							if (buffer[i] == ';')
							{
													int k = i;
						while (buffer[k-1] == ' ')
						{
							k--;
							if(buffer[k-1] == '\n')
								error(1, 0, "Line %d: Operator and word on diff lines", __LINE__);
						}
								if(wordElement[0][0] == '\0')
									error(1, 0, "Line %d: Nothing before sequence", i);
								op = numberOfOper(&buffer[i]);
								currWord++;
								wordElement[currWord] = '\0';
								if (usedInput == 0)
									inputElement = NULL;
								if (usedOutput == 0)
									outputElement = NULL;
								if (DEBUG) printf("617 makeSimpleCommand %s\n", wordElement[0]);
								if ((currWord = 0) || (currWord == 1))
									error(1, 0, "Line %d: Nothing to run ';' on", i);
								makeSimpleCommand(wordElement, inputElement, outputElement);
								bufferWordSize = 10;
								usedWord = 0;
								currWord = 0;
								usedInput = 0;
								usedOutput = 0;
								wordElement = (char**)checked_malloc(sizeof(char*));
								wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
								inputElement = (char*)checked_malloc(bufferInputSize);
								outputElement = (char*)checked_malloc(bufferOutputSize);
								processOperator(op);
								//i++;
							}
		//Case of '\n'
							else
								if (buffer[i] == '\n' && i != 0)
								{
									/*int scChecker = i;
									while (buffer[i + 1] == ' ')
									{
										scChecker++;
										if (buffer[scChecker + 1] == ';')
											error(1, 0, "Line %d: Newline followed by ';'");
									}*/
									if (buffer[i+1] == ';')
										error(1, 0, "Line %d: Newline followed by ';'", i);
									if ((i + 1) == (int)filled)
									{
										currWord++;
										wordElement[currWord] = '\0';
										if (usedInput == 0)
											inputElement = NULL;
										if (usedOutput == 0)
											outputElement = NULL;
										if (DEBUG) printf("654 makeSimpleCommand %s\n", wordElement[0]);
										makeSimpleCommand(wordElement, inputElement, outputElement);
										bufferWordSize = 10;
										currWord = 0;
										usedWord = 0;
										usedInput = 0;
										usedOutput = 0;
										wordElement = (char**)checked_malloc(sizeof(char*));
										wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
										inputElement = (char*)checked_malloc(bufferInputSize);
										outputElement = (char*)checked_malloc(bufferOutputSize);
										completeCommand();
										free(buffer);
										return headStream;
									}
									char lastC;
									int back = 1;
									while (buffer[i - back] == ' ' && i - back >= 0)
									{
										//lastC = buffer[i - back];
										back++;
									}
									lastC = buffer[i - back];
									if (buffer[i + 1] == '\n')
									{
										while (buffer[i + 1] == '\n')
											i++;
										if (lastC != '|' && lastC != '&')
										{
											currWord++;
											wordElement[currWord] = '\0';
											if (usedInput == 0)
												inputElement = NULL;
											if (usedOutput == 0)
												outputElement = NULL;
											if (DEBUG) printf("654 makeSimpleCommand %s\n", wordElement[0]);
											makeSimpleCommand(wordElement, inputElement, outputElement);
											bufferWordSize = 10;
											currWord = 0;
											usedWord = 0;
											usedInput = 0;
											usedOutput = 0;
											wordElement = (char**)checked_malloc(sizeof(char*));
											wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
											inputElement = (char*)checked_malloc(bufferInputSize);
											outputElement = (char*)checked_malloc(bufferOutputSize);
											completeCommand();
										}
									}
									else
									{
										if (lastC == '|' || lastC == '&' || lastC == '<' || lastC || '>')
										{
											while (buffer[i + 1] == '\n')
												i++;//////SPIT ERROR?
										}
										else
										{
											char swap = ';';
											op = numberOfOper(&swap);
											wordElement[currWord + 1] = '\0';
											if (usedInput == 0)
												inputElement = NULL;
											if (usedOutput == 0)
												outputElement = NULL;
											if (DEBUG) printf(" 679 makeSimpleCommand %s\n", wordElement[0]);
											makeSimpleCommand(wordElement, inputElement, outputElement);
											bufferWordSize = 10;
											currWord = 0;
											usedWord = 0;
											usedInput = 0;
											usedOutput = 0;
											wordElement = (char**)checked_malloc(sizeof(char*));
											wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
											inputElement = (char*)checked_malloc(bufferInputSize);
											outputElement = (char*)checked_malloc(bufferOutputSize);
											processOperator(op);
										}
									}
								}
		//Case of # (comment)
								else
									if (buffer[i] == '#')
									{
										if (DEBUG) printf("698 Got a comment!\n");
										while (buffer[i] != '\n')
											i++;
									}
									//Else
									else
									{
										if (buffer[i] == '\'')
										{
											if (buffer[i + 1] == 'E' && buffer[i + 2] == 'O' && buffer[i + 3] == 'F')
												break;
										}
										//if (buffer[i] != ' ')
										wordElement[currWord][usedWord] = buffer[i];
										usedWord++;
										if (i + 1 == filled)
										{
											currWord++;
											wordElement[currWord] = '\0';
											if (usedInput == 0)
												inputElement = NULL;
											if (usedOutput == 0)
												outputElement = NULL;
											makeSimpleCommand(wordElement, inputElement, outputElement);
											completeCommand();
										}
									}
		i++;
	}
	free(buffer);
	return headStream;
}
Esempio n. 23
0
int encrypt_file(const char *file, struct lfsr *l_17, struct lfsr *l_25, const char *outfile, int *dMode, unsigned char initialization_vector)
{
    //File Manipulation
    FILE *inFile = fopen(file, "rb");
    if(inFile == NULL){
        fprintf(stderr, "Error Opening File For Reading <%s>\n", file);
        return -1;
    }
    FILE *oFile = fopen(outfile, "wb+");
    if(oFile == NULL){
        fprintf(stderr, "Error Opening File For Writing <%s>\n", outfile);
        fclose(inFile);
        return -2;
    }

    long lSize;
    unsigned char *buffer = NULL;
    size_t result;

    fseek (inFile , 0 , SEEK_END);
    lSize = ftell (inFile);
    rewind (inFile);

    buffer = (unsigned char*) malloc( sizeof(unsigned char) * lSize);
    if (buffer == NULL) {
        fprintf(stderr, "Memory Error While Reading File <%s>\n", file);
        return -3;
    }

    result = fread (buffer, sizeof(unsigned char), lSize, inFile);
    if (result != lSize) {
        fprintf(stderr, "Error reading File into Memory <%s>\n", file);
        return -4;
    }

    //Encryption
    BIT byte_17[8], byte_25[8];
    BIT carry = ZERO;
    BIT sumArray[8] = {ZERO, ZERO, ZERO, ZERO,ZERO, ZERO, ZERO, ZERO};

    int i;
    unsigned char temp_keystream,
                  temp_plaintext,
                  temp_ciphertext;

    /* MODES OF OPERATION:
        ECB: mode = 0
        CBC: 1
        OFB: 2
        CFB: 3
    */

    MODE _mode = *dMode;

    for(i=0; i<lSize; i++){
        get_next_byte(l_17, byte_17);
        get_next_byte(l_25, byte_25);
        sum_bytes(byte_17, byte_25, carry, sumArray, &carry);
        bit_array_to_unsigned_char(sumArray, &temp_keystream);
        memcpy(&temp_plaintext, buffer+i, sizeof(unsigned char));
        switch (_mode) {
          case ECB:
              temp_ciphertext = temp_keystream ^ temp_plaintext;
              break;
          case CBC:
              temp_plaintext ^= initialization_vector;
              temp_ciphertext = temp_keystream ^ temp_plaintext;
              initialization_vector = temp_ciphertext;
              break;
          case OFB:
              temp_ciphertext = temp_keystream ^ initialization_vector;
              initialization_vector = temp_ciphertext;
              temp_ciphertext ^= temp_plaintext;
              break;
          case CFB:
              temp_ciphertext = temp_keystream ^ initialization_vector;
              temp_ciphertext ^= temp_plaintext;
              initialization_vector = temp_ciphertext;
              break;
        }
        //Output the ciphertext to the File
        if(fwrite (&temp_ciphertext , sizeof(unsigned char), 1, oFile) < 1){
            fprintf(stderr, "Error Writing (%c) at index.(%d) to Output File <%s>, Aborting.\n", temp_ciphertext, i, outfile);
            return -5;
        }
    }
    fclose(inFile);
    fclose(oFile);
    return 0;
}
Esempio n. 24
0
command_stream_t
make_command_stream (int (*get_next_byte) (void *),
                     void *get_next_byte_argument)
{
    
    //current character
    char curr;
    int tree_number = 1;
    char prev_char_stored = '\0';
    int consecutive_newlines = 0;
    
    
    //buffer size = 1KB
    int BUFFER_SIZE = 1024;
    //buffer to read characters into; buffer can hold 1024 chars at once
    char *buffer = (char *) checked_malloc(BUFFER_SIZE * sizeof(char));
    
    //int to count how many chars are in buffer
    int numChars = 0;
    
    //int to count which line we are on
    //int syntax_line_counter = 0;
    int invalid_char_line_counter = 1;
    
    //if this is true, we are searching for the right operand of an operator
    bool found_AND_OR_PIPE_SEQUENCE = false; //looking for operand
    
    
    //declare command stream and allocate space
    //maybe dont need to allocate space because initStream() already does?
    command_stream_t theStream;    // = (command_stream_t) checked_malloc(sizeof(struct command_stream));
    
    //initialize command_stream
    theStream = initStream();
    
    //start reading the chars from the input
    while ((curr = get_next_byte(get_next_byte_argument)) != EOF ) {
        
        if (numChars > 0){
            //only stores previous meaningful character, i.e. not whitespace
            if ((buffer[numChars-1] != ' ' && buffer[numChars-1] != '#')){
                prev_char_stored = buffer[numChars-1];
            }
        }
        
        if (prev_char_stored == '&' || prev_char_stored == '|' || prev_char_stored == ';'){
            found_AND_OR_PIPE_SEQUENCE = true;
        }
        
        
        
        ////////////////////////////////////////////////////////////
        //////////////////      NEWLINE CHAR    ////////////////////
        ////////////////////////////////////////////////////////////
        
        /*
         New variables introduced:
         char prev_char_stored;
         int consecutive_newlines;
         bool command_has_ended; //haven't needed to use yet
         
         */
        if (identify_char_type(curr) == NEWLINE_CHAR || identify_char_type(curr) == HASHTAG_CHAR){
            
            //found a newline, increment counter
            consecutive_newlines++;
            
            //hit second (or more) newline
            if (consecutive_newlines > 1){
                //not looking for an operator and
                if (!found_AND_OR_PIPE_SEQUENCE){
                    if (identify_char_type(curr) == NEWLINE_CHAR) {
                    //add second newline to buffer
                    buffer[numChars] = '\n';
                    numChars++;
                    curr = get_next_byte(get_next_byte_argument);
                    }
                    /*
                     check for newlines, whitespaces, and hashtags after second newline
                     Store newlines on the buffer, ignore white spaces, and for hashtags:
                     put hashtag and newline on the buffer
                     */
                    while (identify_char_type(curr) == NEWLINE_CHAR || identify_char_type(curr) == WHITESPACE_CHAR || identify_char_type(curr) == HASHTAG_CHAR){
                        if (curr == '\n'){
                            buffer[numChars] = '\n';
                            numChars++;
                        } else if (curr == '#'){
                            //add hashtag to buffer
                            consecutive_newlines++;
                            buffer[numChars] = '#';
                            numChars++;
                            
                            //go to end of comment
                            while (identify_char_type(curr) != NEWLINE_CHAR){
                                if ((curr = get_next_byte(get_next_byte_argument)) == EOF) {
                                    break;
                                }
                            }
                            //broke out of loop, curr is now a newline char; add to buffer
                            buffer[numChars] = '\n';
                            numChars++;
                            
                        }
                        
                        if ((curr = get_next_byte(get_next_byte_argument)) == EOF) {
                            break;
                        }
                    }
                    
                    consecutive_newlines = 0;
                    
                    //create temporary array with size of numChars;
                    char* buffer_no_whitespaces = checked_malloc(BUFFER_SIZE * (sizeof(char)));  //the correct syntaxed command
                    memset(buffer_no_whitespaces, '\0', BUFFER_SIZE * sizeof(char));
                    
                    //run validation, then parse if correct
                    
                    eatWhiteSpaces(buffer, numChars, buffer_no_whitespaces);
                    
                    
                    int pos = 0;
                    
                    while (buffer_no_whitespaces[pos] != '\0'){
                        if (identify_char_type(buffer_no_whitespaces[pos]) == NEWLINE_CHAR){
                            invalid_char_line_counter++;
                        }
                        if (identify_char_type(buffer_no_whitespaces[pos]) == INVALID_CHAR){
                            identify_char_type(buffer_no_whitespaces[pos]);
                            fprintf(stderr, "%d: Invalid character: %c <---", invalid_char_line_counter, buffer_no_whitespaces[pos]);
                            exit(1);
                        }
                        pos++;
                    }
                    
                    checkAndSyntax(buffer_no_whitespaces);
                    checkForConsecutiveTokens(buffer_no_whitespaces);
                    checkIfOperatorsHaveOperands(buffer_no_whitespaces);
                    validParentheses(buffer_no_whitespaces);
                    
                    /*
                     int i;
                     for (i= 0; i<numChars; i++){
                     printf("%c", buffer_no_whitespaces[i]);
                     }
                     
                     //this just separates commands
                     printf("\n");
                     */
                    
                    commandNode_t root = createNodeFromCommand(make_command_tree(buffer_no_whitespaces));
                    
                    //printf("adding command node to stream: %s\n", root->cmd->u.word[0]);
                    
                    write_list_t write_list = init_write_list();
                    
                    //printf("adding command node to stream: %s\n", root->cmd->u.word[0]);
                    root->write_list = make_write_list(write_list, root->cmd);
                    read_list_t read_list = init_read_list();
                    root->read_list = make_read_list(read_list, root->cmd);
                    
                    root->tree_number=tree_number;
                    
                    root->dependency_list = (commandNode_t*)(checked_realloc(root->dependency_list, (tree_number) * sizeof(commandNode_t)));
                    memset (root -> dependency_list, '\0', (tree_number) * sizeof(commandNode_t));
                    
                    
                    //printf("adding command node to stream: %s\n", root->cmd->u.word[0]);
                    
                    addNodeToStream(theStream, root);
                    
                    
                    //reset everything with memset
                    memset(buffer, '\0', BUFFER_SIZE * sizeof(char));
                    free(buffer_no_whitespaces);
                    numChars = 0;
                    consecutive_newlines = 0;
                    
                    tree_number++;
                    
                    
                    if (curr == EOF)
                        break;
                    /*
                     We are now at a new command.
                     Add first character to buffer, whether valid or invalid.
                     Will check syntax later.
                     */
                    if (identify_char_type(curr) != HASHTAG_CHAR){
                        buffer[numChars] = curr;
                        numChars++;
                    } else {
                        //add a hashtag and newline to the buffer
                        buffer[numChars] = '#';
                        numChars++;
                        
                        //get to the end of the line
                        while (identify_char_type(curr) != NEWLINE_CHAR){
                            if ((curr = get_next_byte(get_next_byte_argument)) == EOF) {
                                break;
                            }
                        }
                        
                        //now we have a newline; add newline to buffer
                        buffer[numChars]=curr;
                        numChars++;
                        consecutive_newlines++;
                    }
                    continue;
                } else { //if we are looking for operand, don't end the commmand
                    
                    while (identify_char_type(curr) == NEWLINE_CHAR || identify_char_type(curr) == WHITESPACE_CHAR || identify_char_type(curr) == HASHTAG_CHAR){
                        if (curr == '\n'){
                            buffer[numChars] = '\n';
                            numChars++;
                        } else if (curr == '#'){
                            //add hashtag to buffer
                            buffer[numChars] = '#';
                            numChars++;
                            
                            while (identify_char_type(curr) != NEWLINE_CHAR){
                                if ((curr = get_next_byte(get_next_byte_argument)) == EOF) {
                                    break;
                                }
                            }
                            //broke out of loop, curr is now a newline char; add to buffer
                            buffer[numChars] = '\n';
                            numChars++;
                        }
                        
                        if ((curr = get_next_byte(get_next_byte_argument)) == EOF) {
                            break;
                        }
                        
                        
                    }
                    //broken out of while loop, we now have a regular character; add to buffer
                    
                    if (curr == EOF)
                        break;
                    
                    buffer[numChars] = curr;
                    numChars++;
                    found_AND_OR_PIPE_SEQUENCE = false;
                    consecutive_newlines = 0;
                    continue;
                }
            } else {
                //add newline to buffer; this is when number of newlines equals one
                if (identify_char_type(curr) == HASHTAG_CHAR) {
                    buffer[numChars] = '#';
                    numChars++;
                    
                    while (identify_char_type(curr) != NEWLINE_CHAR){
                        if ((curr = get_next_byte(get_next_byte_argument)) == EOF) {
                            break;
                        }
                    }
                    
                }
                buffer[numChars] = '\n';
                numChars++;
                continue;
            }
        } //end newline case
        else {
            
            
            if (!found_AND_OR_PIPE_SEQUENCE && consecutive_newlines == 1) {
                buffer[numChars] = ';';
                numChars++;
            }
            
            buffer[numChars] = curr;
            numChars++;
            consecutive_newlines = 0;
            
            //if we are here we no longer skip lines
            found_AND_OR_PIPE_SEQUENCE = false;
        }
    }
    
    char* buffer_no_whitespaces = checked_malloc(BUFFER_SIZE * (sizeof(char)));  //the correct syntaxed command
    memset(buffer_no_whitespaces, '\0', BUFFER_SIZE * sizeof(char));
    
    //run validation, then parse if correct
    //void eatWhiteSpaces(char *buffer, int bufferSize, char *newArray)
    eatWhiteSpaces(buffer, numChars, buffer_no_whitespaces);
    int pos = 0;
    
    while (buffer_no_whitespaces[pos] != '\0'){
        if (identify_char_type(buffer_no_whitespaces[pos]) == NEWLINE_CHAR){
            invalid_char_line_counter++;
        }
        if (identify_char_type(buffer_no_whitespaces[pos]) == INVALID_CHAR){
            identify_char_type(buffer_no_whitespaces[pos]);
            fprintf(stderr, "%d: Invalid character: %c <---", invalid_char_line_counter, buffer_no_whitespaces[pos]);
            exit(1);
        }
        pos++;
    }
    
    checkAndSyntax(buffer_no_whitespaces);
    checkForConsecutiveTokens(buffer_no_whitespaces);
    checkIfOperatorsHaveOperands(buffer_no_whitespaces);
    validParentheses(buffer_no_whitespaces);
    
    /*
     if (buffer_no_whitespaces[0] != '\0') {
     int i;
     for (i= 0; i<numChars; i++){
     printf("%c", buffer_no_whitespaces[i]);
     }
     printf("\n");
     }*/
    
    
    //make sure buffer_no_whitespace is not empty
    if (buffer_no_whitespaces[0] != '\0') {
        commandNode_t root = createNodeFromCommand(make_command_tree(buffer_no_whitespaces));
        
        write_list_t write_list = init_write_list();
        root->write_list = make_write_list(write_list, root->cmd);
        read_list_t read_list = init_read_list();
        root->read_list = make_read_list(read_list, root->cmd);
        root->tree_number=tree_number;
        
        
        root->dependency_list = (commandNode_t*)(checked_realloc(root->dependency_list, (tree_number) * sizeof(commandNode_t)));
        memset (root -> dependency_list, '\0', (tree_number) * sizeof(commandNode_t));
        
        //printf("adding command node to stream: %s\n", root->cmd->u.word[0]);
        
        addNodeToStream(theStream, root);
    }
    
    free(buffer);
    free(buffer_no_whitespaces);
    
    theStream->blocked_commands = (commandNode_t*)checked_realloc(theStream->blocked_commands, theStream->num_nodes * sizeof(commandNode_t));
    memset(theStream->blocked_commands, '\0', theStream->num_nodes * sizeof(commandNode_t));
    
    return theStream;
}
Esempio n. 25
0
void 
makeSeparation(FILE* fp, Separation_t* m_separation, int (*get_next_byte) (void *))
{
  char* word[MAXLINE];
  int atLine[MAXLINE];
  char* str="";
  char ch = get_next_byte(fp);
  char preCh;
  int countWord=0;
  int countParath=0;
  int countLine=1; //this parameter records the line number that the program is reading
  int newLineFlag=1; //this flag is used to skip white space after '\n'
  int newWordFlag=0;
  int headFlag=1;
  //Separation_t m_separation[MAXLINE];

  //this while is to slit the text by 2 or more '\n' and the split results are stored in array word
  while(ch!=EOF){

    //this if is to skip white space after '\n'
    if((ch==' '||ch=='\t') && newLineFlag) {ch=get_next_byte(fp);continue;}

    //this if is to get rid of comment starting with '#', while the tailing '\n' is preserved 
    if(ch=='#'){
      while(ch!='\n' && ch!=EOF){
        ch=getc(fp);
      }
      countLine++;
      ch=getc(fp);
      continue;
    }
    //this if is to extract the subshell expressed as ()
    if(ch=='('){
      int badLine = countLine;
      // printf("enter subshell: badLine=%d\n",badLine);
      do{
        if(ch=='#'){
          while(ch!='\n' && ch!=EOF){
            ch=getc(fp);
          }
          countLine++;
          ch=getc(fp);
          continue;
        }
        str = str_append(str,ch);
        if(ch=='(') countParath++;
        if(ch==')') countParath--;
        if(ch=='\n') countLine++;
        ch=getc(fp);
      }while(countParath && ch!=EOF);
      if(ch==EOF){
        word[countWord]=checked_malloc(sizeof(str)+1);
        memset(word[countWord],'\0',sizeof(str)+1);
        word[countWord]=str;
        atLine[countWord]=badLine;
        countWord++;
        str="";
        break;
      }
    }

    if(ch!='\n'){
      str = str_append(str,ch);
      newLineFlag=0;
      if(headFlag){
        atLine[0]=countLine;
        headFlag=0;
      }
    }
    else{
      newLineFlag=1;
      countLine++;
      //printf("3:countLine=%d\n",countLine);
      if(preCh=='\n' && strlen(str)>0){
        word[countWord]=checked_malloc(sizeof(str)+1);
        memset(word[countWord],'\0',sizeof(str)+1);
        word[countWord]=str;
        countWord++;
        str="";
        newWordFlag=1;
      }
      else if(strlen(str)>0){
        str = str_append(str,ch);
        if(newWordFlag){
          atLine[countWord]=countLine-1;
          newWordFlag=0;
        }
        if(headFlag){
          atLine[0]=countLine;
          headFlag=0;

        }
      }
        //printf(" (%c at line %d, the str=%s, strlen=%d) ",ch,countLine,str, (int)strlen(str));
    }
    preCh=ch;
    ch = get_next_byte(fp);
  }
  //if the last word doesn't end with "\n\n", also add it in
  if(str!=""){
    word[countWord]=checked_malloc(sizeof(str)+1);
    memset(word[countWord],'\0',sizeof(str)+1);
    word[countWord]=str;
    countWord++;
    newWordFlag=1;
  }
  //if the last word doesn't end with '\n', revise the bug of counting line
  if(atLine[countWord-1]==0)
    atLine[countWord-1]=countLine;
  fclose(fp);
  //==============end of read file====================


  //============================merge word with tailing operator=======================================
  int merge[countWord+1];
  int i=0;
  // for(i=0; i<countWord; i++){
  //  printf("word %d at Line %d is:\n%s",i,atLine[i],word[i]);
  // }
  // for(i=0; i<countWord; i++)
  //  printf("%d\n",atLine[i]);

  //delete tailing '\n'
  for(i=0; i<countWord; i++){
    //get rid of tailing '\n'
    size_t sz=strlen(word[i]);
    if(word[i][sz-1]=='\n'){
      word[i][sz-1]='\0';
      sz--;
    }
    //printf("w%d:\n%s",i,word[i]);
    //if ending with operator: '|' ';' '||' '&&' '<' '>', mark this word in array merge[]
    if(word[i][sz-1]=='|' || word[i][sz-1]==';' || word[i][sz-1]=='<' || word[i][sz-1]=='>' || (word[i][sz-1]=='&' && word[i][sz-2]=='&'))
      merge[i]=strlen(word[i]);
    else
      merge[i]=-strlen(word[i]);
    //printf("merge[%d]=%d\n",i,merge[i]);
  }
  //printf("4:countLine=%d\n",countLine);
  
  //recompute the total word in merged array
  int newCountWord=0;
  for(i=0; i<countWord; i++){
    if(merge[i]<0) newCountWord++;
    else{
      newCountWord++;
      while(merge[i]>0 && i<countWord)  i++;
    }
  }
  //printf("newCountWord=%d\n",newCountWord);

  //merge and copy from old array to new array 
  char* commandStr[newCountWord];
  int newAtLine[newCountWord];
  int ptrOld=0;
  int ptrNew=0;
  while(ptrOld<countWord && ptrNew<newCountWord){
    if(merge[ptrOld]<0) {
      //printf("hi: %d\n",ptrOld);
      commandStr[ptrNew] = checked_malloc(abs(merge[ptrOld])+1);
      strcpy(commandStr[ptrNew],word[ptrOld]);
      newAtLine[ptrNew]=atLine[ptrOld];
    }
    else {
      int startPtr=ptrOld;
      size_t cpyLen=0;
      while(merge[ptrOld]>0 && ptrOld<countWord){
        cpyLen+=merge[ptrOld];
        ptrOld++;
      }
      if(ptrOld==countWord){
        //printf("\n\nhuge bug!!!\n\n");
        //printf("\ncpyLen=%d\n\n",(int)cpyLen);
        commandStr[ptrNew] = checked_malloc(cpyLen+1);
        memset(commandStr[ptrNew],'\0',cpyLen+1);
        newAtLine[ptrNew]=atLine[startPtr];
        while(startPtr<=--ptrOld){
          strcat(commandStr[ptrNew],word[startPtr]);
          startPtr++;
        }
        break;
      }
      cpyLen+=abs(merge[ptrOld]);
      //printf("\ncpyLen=%d\n\n",(int)cpyLen);
      commandStr[ptrNew] = checked_malloc(cpyLen+1);
      memset(commandStr[ptrNew],'\0',cpyLen+1);
      newAtLine[ptrNew]=atLine[startPtr];
      while(startPtr<=ptrOld){
        strcat(commandStr[ptrNew],word[startPtr]);
        startPtr++;
      }
    }
    ptrNew++;
    ptrOld++;
  }
  for(i=0;i<newCountWord;i++){
    //printf("1111: CMD%d at line %d is:\n%s",i,newAtLine[i],commandStr[i]);
    m_separation[i]=checked_malloc(sizeof(Separation));
    m_separation[i]->m_cmd = checked_malloc(strlen(commandStr[i])+1);
    strcpy(m_separation[i]->m_cmd,commandStr[i]);
    m_separation[i]->m_line=newAtLine[i];
    //printf("CMD%d at line %d is:\n%s",i,m_separation[i]->m_line,m_separation[i]->m_cmd);
  } 

  //write an end indicating element
  m_separation[newCountWord]=checked_malloc(sizeof(Separation));
  m_separation[newCountWord]->m_cmd=checked_malloc(strlen("this is the end")+1);
  strcpy(m_separation[newCountWord]->m_cmd, "this is the end");
  m_separation[newCountWord]->m_line=-1;
  //=================================end of merge word======================================================

  //return m_separation;
}
Esempio n. 26
0
command_stream_t main()
{
	char* script_name = "test.sh";
  FILE *script_stream = fopen (script_name, "r");

	int buffer_size=1000;
	char* buffer = (char* )malloc(buffer_size);
	size_t count = 0;
	char ch;

	do
  {
    ch = get_next_byte(script_stream);

    if (ch == '#') // for comments: ignore everything until '\n' or EOF
    {
      ch = get_next_byte(script_stream);
      while(ch != EOF && ch!='\n')
        ch = get_next_byte(script_stream);
    }
    //skip all the words until \n
    if (ch!= -1)
    {
      // load into buffer
      buffer[count] = ch;
      count++;

      // expand buffer if necessary
      //if (count == INT_MAX)
      //{
      //  error(1, 0, "Line -1: Input size over INT_MAX.");
      //}
      if (count == buffer_size)
      {
        buffer_size = buffer_size * 2;
        buffer = (char*)realloc (buffer, buffer_size);
      }
    }
  } while(ch != -1);

	//token_stream_t return_point =convert_buffer_to_token_stream(buffer, count);

	//printf("convert end\n");
  token_stream_t return_token_stream = convert_buffer_to_token_stream(buffer, count);
 /* if(return_token_stream==NULL)
    printf("NULL pointer\n");
  else
    {
      if(return_token_stream->head == NULL)
        printf("NULL head\n");
      else
        { 
          printf("head is not null\n" );
          printf("%d\n",return_token_stream->head->t_type);
          printf("%c\n",return_token_stream->head->next->text[0]);
          if(return_token_stream->head->next->next != NULL)
            {
              printf("linked");
              printf("%d\n",return_token_stream->head->next->next->t_type);
            }
        }
    }
  if(return_token_stream->next==NULL)
    printf("NEXT is NULL pointer\n");
  else
    {
      if(return_token_stream->next->head == NULL)
        printf("NEXT NULL head\n");
      else
        { 
          printf("head is not null\n" );
          printf("%d\n",return_token_stream->next->head->t_type);
          printf("%c\n",return_token_stream->next->head->next->text[0]);
          if(return_token_stream->next->head->next->next->next == NULL)
            printf("YEAH");
        }
    }
  printf("main end");*/
	command_t new_command_t = make_command_tree (return_token_stream);
	printf("make tree end\n");
  add_command_to_stream(new_command_t );
    while (return_token_stream->next != NULL)
  {
    //make return_point point to next token stream
    return_token_stream = return_token_stream->next;
    //free(return_point);
    //return_token_stream = temp;
    new_command_t = make_command_tree (return_token_stream);
    add_command_to_stream(new_command_t);
  }
  return command_stream_head;

}
Esempio n. 27
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.  */

  // initialize memory allocation
  // count of characters
  int pt_count = 0;
  int cmd_count = 0;
  int i = 0;
  char input_byte;
  char prev_byte;
  char *tmp = NULL;
  char *tmp_ch = NULL;
  command_stream t = { 0, 0, NULL };
  command_stream_t result_stream = &t;

  // Initalize memory allocation for stream
  result_stream->command_list = (char**) malloc(sizeof(char**));
  result_stream->command_list[0] = NULL;

  // initialize stream
  input_byte = (char)get_next_byte(get_next_byte_argument);

  // Reallocate memory for stream characters
  // Record stream
  while (input_byte != EOF)
  {    
    if (is_valid_op(input_byte, prev_byte))
    {
      // Add command
      if (tmp_ch != NULL) 
      {
        add_command(&(result_stream->command_list), pt_count++, &tmp_ch, cmd_count);
      }
      // Operator Cases
      if (input_byte == '#') 
      {
        // Append # comment to next command
        tmp_ch = (char*) malloc(sizeof(char));
        tmp_ch[0] = input_byte;
      }
      else if (input_byte == '|' && prev_byte != '|')
      {
        printf("hello");
      }
      else if (input_byte != '|' && prev_byte == '|')
      {
        // Add operator 
        tmp = (char*) malloc(sizeof(char));
        tmp[0] = prev_byte;
        add_command(&(result_stream->command_list), pt_count++, &tmp, 1);
      }
      else if (input_byte == '|' && prev_byte == '|')
      {
        // Add operator 
        tmp = (char*) malloc(2*sizeof(char));
        tmp[0] = input_byte;
        tmp[1] = prev_byte;
        add_command(&(result_stream->command_list), pt_count++, &tmp, 2);
        // prevent from being read again
        input_byte = ' ';
      }
      else if (input_byte == '&' && prev_byte != '&')
      {
      }
      else if (input_byte != '&' && prev_byte == '&')
      {
        // Add operator 
        tmp = (char*) malloc(sizeof(char));
        tmp[0] = input_byte;
        add_command(&(result_stream->command_list), pt_count++, &tmp, 1);
      }
      else if (input_byte == '&' && prev_byte == '&')
      {
        // Add operator 
        tmp = (char*) malloc(2*sizeof(char));
        tmp[0] = input_byte;
        tmp[1] = prev_byte;
        add_command(&(result_stream->command_list), pt_count++, &tmp, 2);
        // prevent from being read again
        input_byte = ' ';
      }
      else
      {
        // Add operator 
        tmp = (char*) malloc(sizeof(char));
        tmp[0] = input_byte;
        add_command(&(result_stream->command_list), pt_count++, &tmp, 1);
      }

      // Reset for next add
      if(input_byte == '#')
      {
        cmd_count = 1;
      }
      else
      {
        cmd_count = 0;
      }
      prev_byte = input_byte;
      input_byte = get_next_byte(get_next_byte_argument);
      continue;
    }
    if (input_byte == '#') 
    {
            // Reset
      prev_byte = input_byte;
      input_byte = get_next_byte(get_next_byte_argument);
      continue;
    }
    // Allocate for command until delimiter found
    tmp_ch = (char*) realloc(tmp_ch, (cmd_count+1)*sizeof(char));
    tmp_ch[cmd_count] = input_byte;
    cmd_count++;

    prev_byte = input_byte;
    input_byte = get_next_byte(get_next_byte_argument);
  }

  result_stream->size = pt_count;

  // Test print
  for (i=0; i < pt_count; i++)
  {
    printf("%d: %s\n", i, result_stream->command_list[i]);
  }
  printf("\npt_count: %d \n", pt_count);
  
  // Returns stream as character array
  return result_stream;
}
Esempio n. 28
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.  */
  size_t buffer_size=1000;
  char* buffer = (char* )checked_malloc(buffer_size);
  size_t count = 0;
  char ch;

  do
  {
    ch = get_next_byte(get_next_byte_argument);

    if (ch == '#') // for comments: ignore everything until '\n' or EOF
    {
      ch = get_next_byte(get_next_byte_argument);
      while(ch != EOF && ch!='\n')
        ch = get_next_byte(get_next_byte_argument);
    }
    //skip all the words until \n
    if (ch!= -1)
    {
      // load into buffer
      buffer[count] = ch;
      count++;

      // expand buffer if necessary
      //if (count == INT_MAX)
      //{
      //  error(1, 0, "Line -1: Input size over INT_MAX.");
      //}
      if (count == buffer_size)
      {
        buffer_size = buffer_size * 2;
        buffer = (char*)checked_realloc (buffer, buffer_size);
      }
    }
  } while(ch != -1);

  token_stream_t return_token_stream = convert_buffer_to_token_stream(buffer, count);
  command_t new_command_t = make_command_tree (return_token_stream);
   // printf("make tree end\n");
  add_command_to_stream(new_command_t );
 // printf("add first command to stream\n");
 // printf("command type : %d\n", new_command_t->type);
  //if(new_command_t == NULL)
   // printf("HAHA");
 // print_command(new_command_t);
    while (return_token_stream->next != NULL)
  {
    //make return_point point to next token stream
    return_token_stream = return_token_stream->next;
    //free(return_point);
    //return_token_stream = temp;
    new_command_t = make_command_tree (return_token_stream);
    add_command_to_stream(new_command_t);
   // printf("add another command to stream\n");
    //print_command(new_command_t);
  }
//  printf("return to main\n");
 // print_command()
  return command_stream_head;

}
Esempio n. 29
0
static uint8_t get_next_control(decompression_state *state)
{
	uint8_t c = get_next_byte(state);
	/* OC_DEBUG(3, "control: 0x%02x", c); */
	return c;
}
Esempio n. 30
0
command_stream_t
make_command_stream (int (*get_next_byte) (void *),
         void *get_next_byte_argument)
{
  
  //*****************************************
  //         CREATE & ALLOCATE BUFFER
  //*****************************************
  
  
  int current_size = 1024;
  char* buffer = (char*)checked_malloc(sizeof(char)*current_size);
  int byte_count = 0;
  for(;;) {
    int c = get_next_byte(get_next_byte_argument);

    if (byte_count == current_size) {
      current_size = current_size*2;
      size_t size_size = sizeof(char)*current_size;
      buffer = (char*)checked_grow_alloc((void*)buffer, &(size_size));
    }
    if (c != EOF && byte_count < current_size) {
      buffer[byte_count] = c;
      byte_count++;
    }
    else
      break;
  }
   
  //*****************************************
  //   MAKE COMMAND STREAM OF COMMAND NODES
  //*****************************************

  int currentPos = 0;
  int lineNum = 1;

  // initialize command stream
  command_stream_t command_stream = checked_malloc(sizeof(struct command_stream));
  
  // initialize first node
  command_node_t firstCommandNode = checked_malloc(sizeof(struct command_node));
  command_stream->current_node = firstCommandNode;
  command_node_t currentCommandNode = command_stream->current_node;
  
  // initialize first command
  command_t firstCommand = checked_malloc(sizeof(struct command));
  firstCommandNode->command = firstCommand;
  command_t currentCommand = currentCommandNode->command;

  while (get_command(buffer, &currentPos, byte_count, currentCommand, &lineNum) == 1) {
    // create new node
    
    command_node_t newCommandNode = checked_malloc(sizeof(struct command_node));
    newCommandNode->prev = currentCommandNode;
    currentCommandNode->next = newCommandNode;
    currentCommandNode = currentCommandNode->next;

    // create new command for that node
    command_t newCommand = checked_malloc(sizeof(struct command));
    newCommandNode->command = newCommand;
    currentCommand = currentCommandNode->command;
  }
  
  if (currentCommandNode->prev != NULL) // couldn't add first command
    currentCommandNode->prev->next = NULL;
  else
    command_stream->current_node = NULL;

  return command_stream;
}