Exemple #1
0
int		parse_file(t_tetrim *t, int fd, char *data)
{
	char		last;
	t_buffer	*buffer;
	int			i;

	i = 0;
	buffer = create_buffer();
	while ((read(fd, data, 1)) > 0)
	{
		if ((i == 20 || i == 21) && (last == '\n' &&
					data[0] == '\n' && parse_buffer(buffer, t, 0)))
			return (-1);
		else if ((i == 20 || i == 21) && last == '\n' &&
				data[0] == '\n' && (t = t->next) != NULL)
		{
			buffer = reset_buffer(buffer);
			i = 0;
		}
		add_buffer(buffer, data[0]);
		last = data[0];
		i++;
	}
	if ((i != 21 && i != 20) || (parse_buffer(buffer, t, 1) || close(fd)))
		return (-1);
	free(buffer);
	return (0);
}
Exemple #2
0
static void get_meta_bam_hdr( vdb_info_bam_hdr * bam_hdr, const KMetadata * meta )
{
    const KMDataNode * node;
    rc_t rc = KMetadataOpenNodeRead ( meta, &node, "BAM_HEADER" );
    bam_hdr -> present = ( rc == 0 );
    if ( bam_hdr -> present )
    {
        bam_hdr->hdr_bytes = get_node_size( node );
        if ( bam_hdr->hdr_bytes > 0 )
        {
            char * buffer = malloc( bam_hdr->hdr_bytes );
            if ( buffer != NULL )
            {
                size_t num_read, remaining;
                rc = KMDataNodeRead( node, 0, buffer, bam_hdr->hdr_bytes, &num_read, &remaining );
                if ( rc == 0 )
                {
                    parse_buffer( bam_hdr, buffer, bam_hdr->hdr_bytes );
                }
                free( buffer );
            }
        }
        KMDataNodeRelease ( node );
    }
}
Exemple #3
0
/*
 * For each file given on the command line, open it, read its
 * contents into a buffer and then invoke the RDF parser on the
 * buffer.
 */
int main (int argc, char ** argv)
{
    BOOL status;
    char *msg;
    char *buffer = NULL;
    int buff_len = 0;
    int i;

    if (argc <= 1) {
        (void) fprintf(stderr, "Usage: %s file_name(s)_to_parse\n", argv[0]);
        return 1;
    }

    for (i=1; i < argc; i++) {
        msg = parse_buffer(argv[i], &buffer, &buff_len);
        if (!msg) {
            status = HTRDF_parseBuffer(buffer, argv[i], buff_len, new_triple_handler, NULL);
            if (!status)
                (void) fprintf (stderr, "ERROR parsing the buffer from file: '%s'\n", argv[i]);
        }
        else
            (void) fprintf (stderr, "ERROR creating the buffer: '%s'\n", msg);
    }

    return 0;
}
Exemple #4
0
static PyObject*
cogent_get(CogentObject *self, PyObject *args, PyObject *kwds)
{
	const char *key;

	static char *kwlist[] = {"key", NULL};
	if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", kwlist, &key))
		return NULL;

	size_t buf_len = 0;
	void *buf = construct_client_get(key, (uint8_t) (strlen(key) + 1), &buf_len);

	if (send(self->sock, buf, buf_len, 0) < 0)
		perror("cogent_get: send()");

	size_t amt = recv(self->sock, self->recv_buf, RECVBUFSZ, 0);
	if (amt < 0)
		perror("cogent_get: recv()");

	/* FIXME */
	void *v = parse_buffer(self->recv_buf, amt);
	assert(v != NULL);
	assert(CMD_BYTE(v) == CMD_SERVER_GET);
	proto_server_get *s = (proto_server_get *) v;

	/* FIXME: leaks memory */
	PyObject *obj = PyString_FromStringAndSize(s->val, s->val_len);
	//printf("got %d bytes\n", (int) amt);
	//g_slice_free1(buf_len, buf);
	return obj;
}
Exemple #5
0
static PyObject*
cogent_del(CogentObject *self, PyObject *args, PyObject *kwds)
{
	const char *key;
	int len;

	static char *kwlist[] = {"key", NULL};
	if (!PyArg_ParseTupleAndKeywords(args, kwds, "s#", kwlist, &key, &len))
		return NULL;

	size_t buf_len = 0;
	void *buf = construct_client_del(key, (uint8_t) (strlen(key) + 1), &buf_len);

	if (send(self->sock, buf, buf_len, 0) < 0)
		perror("cogent_del: send()");

	g_slice_free1(buf_len, buf);

	size_t amt = recv(self->sock, self->recv_buf, RECVBUFSZ, 0);
	if (amt < 0)
		perror("cogent_del: recv()");

	/* TODO: not totally efficient... */
	void *v = parse_buffer(self->recv_buf, amt);
	assert(v != NULL);
	assert(CMD_BYTE(v) == CMD_SERVER_DEL);
	g_slice_free1(amt, v);

	Py_INCREF(Py_None);
	return Py_None;
}
Exemple #6
0
int main(int argc, char *argv[]){
    int s, E, b;
	char *trace = (char*) malloc(50 * sizeof(char));
	cache sim_cache;
	get_opts(argc,argv, &s, &E, &b, trace);
	init_cache(&sim_cache, s, E, b);

	FILE *p_t = fopen(trace, "r");
	if(! p_t){
		fprintf(stderr, "error when open trace file %s\n", trace);
		return -1;
	}

	int hit, miss, evict;
	hit = miss = evict = 0;
	
	char *buffer = (char*) malloc(50 * sizeof(char));
	while(fgets(buffer, 50, p_t) != NULL){
		if(buffer[0] == ' '){
			parse_buffer(&sim_cache, buffer, s, E, b, &hit, &miss, &evict);
		}
	}

	printSummary(hit, miss, evict);
	return 0;
}
Exemple #7
0
void serial_periodic( void ) {

     // transfer uart buffer
     while (1) {
	  
	  uint16_t c = uart_getc();

	  if (c == UART_NO_DATA)
	       break;
	  
	  if (c & 0xff00)
	       continue;
	  
	  if (c == 10)
	       continue;
	  
	  buffer[buf_cnt++] = c;
	  buffer[buf_cnt]   = 0;
     }
     
          
     // EOT?
     if (buf_cnt && (buffer[buf_cnt-1] == 13)) {
	  
	  wd_ticks = 0;

	  buffer[--buf_cnt] = 0;
	  
	  parse_buffer();
	  
	  buffer[0] = 0;
	  buf_cnt   = 0;
     }
     
}
    void ParserImpl::parse(std::vector<char> const & text)
    {
        char const * p = &text[0];
        char const * pe = &text[0] + text.size();
        char const * eof = nullptr;

        clear();
        parse_buffer(p, pe, eof);
    }
    void ParserImpl::parse(std::string const & text)
    {
        char const * p = text.data();
        char const * pe = text.data() + text.size();
        char const * eof = nullptr;

        clear();
        parse_buffer(p, pe, eof);
    }
/*
 * Called by client when ami_connection has new data to process
 */
void ami_handle_data(ami_connection* con)
{
	//printf("Handling data on AMI connection\n");
	int idx = 0; //buffer position
	char* message = NULL;
	char buf[AMI_BUFLEN * 2 + 1];

	//Read data from ami
	memset(buf, 0, AMI_BUFLEN * 2 + 1);
	if (read(con->sd, buf, AMI_BUFLEN-1) <= 0) {
		ami_disconnect(con); //we have been disconnected
		return;
	}

	//Concatenate left over data with newly read
	if (strlen(con->left_over)) {
		char tmp[AMI_BUFLEN * 2 + 1];
		strcpy(tmp, con->left_over);
		strcat(tmp, buf);
		strcpy(buf, tmp);
		con->left_over[0] = '\0';
	}

	ami_message message_type = UNKNOWN_MESSAGE;
	ami_event event;
	memset(&event, 0, sizeof(event));

	while(idx < strlen(buf)) {
		message_type = parse_buffer(con->message_frame, buf, &message, &idx);
		if (message_type == UNKNOWN_MESSAGE) {
			break;
		}
		switch (message_type) {
			case LOGIN_MESSAGE:
				//Send login event to client (time to log in...)
				event.type = LOGIN;
				con->event_callback(con, event);
				ami_free_event(event);
				break;
			case EVENT_MESSAGE:
				ami_handle_event(con, message + 7);
				break;
			case RESPONSE_MESSAGE:
				ami_handle_response(con, message);
				break;
			default:
				printf("Unknown data from AMI: %s\n", message);
				break;
		}
		free(message);
	}

	//store remaining buffer until next packet is read
	if (idx < strlen(buf)) {
		strcpy(con->left_over, &buf[idx]);
	}
}
Exemple #11
0
/* This reads the file at \path in memory and parses it as if it was given as
 * command line options. */
int conf_parse_file(struct conf_option *opts, size_t len, const char *path)
{
	int fd, ret;
	size_t size, pos;
	char *buf, *tmp;

	if (!path)
		return -EINVAL;

	log_info("reading config file %s", path);
	fd = open(path, O_RDONLY | O_CLOEXEC | O_NOCTTY);
	if (fd < 0) {
		log_error("cannot open %s (%d): %m", path, errno);
		return -EFAULT;
	}

	buf = NULL;
	size = 0;
	pos = 0;

	do {
		if (size - pos < CONF_BUFSIZE) {
			tmp = realloc(buf, size + CONF_BUFSIZE + 1);
			if (!tmp) {
				log_error("cannot allocate enough memory to parse config file %s (%d): %m",
					  path, errno);
				ret = -ENOMEM;
				goto out_free;
			}
			buf = tmp;
			size += CONF_BUFSIZE;
		}

		ret = read(fd, &buf[pos], CONF_BUFSIZE);
		if (ret < 0) {
			log_error("cannot read from config file %s (%d): %m",
				  path, errno);
			ret = -EFAULT;
			goto out_free;
		}
		pos += ret;
	} while (ret > 0);

	buf[pos] = 0;
	ret = parse_buffer(opts, len, buf, pos);

out_free:
	free(buf);
	close(fd);
	return ret;
}
Exemple #12
0
void
TextContent::parse() 
{ 
    _parsed = parse_buffer( _buf ); 
    if ( _parsed ) { 
        if ( _parse_tree ) { 
            delete _parse_tree;
            _parse_tree = NULL;
        }
        _parse_tree = new tree_a_File_(_parsed, 1, _buf->nlines() );
        int f = _parse_tree->findfirst();
        _parse_tree->firstline = 1;
        fprintf(stderr, "first is %d\n", f);
    }
}
Exemple #13
0
xmlDoc *xml_parse_file(gchar *filename)
{
	unsigned int l;
	GNode *root;
	xmlDoc *doc;
	NODE_DATA *node_data;
	char buff[65535];
	FILE *fp;

#ifdef XML_TRACE
	LOG(LOG_DEBUG, "IN : xml_parse_file(%s)", filename);
#endif

	fp = fopen(filename, "r");
	if(fp == NULL){
		LOG(LOG_CRITICAL, "fopen: %s", strerror(errno));
		return(NULL);
	}

	//サイズは最大65535バイト
	memset(buff, 0, sizeof(buff));
	l = fread(buff, 1, sizeof(buff), fp);
	fclose(fp);
	if(l <= 0){
		return(NULL);
	}
	
	doc = (xmlDoc *)calloc(sizeof(xmlDoc), 1);
	doc->version = NULL;
	doc->encoding = NULL;
	
	node_data = (NODE_DATA *)calloc(sizeof(NODE_DATA), 1);
	node_data->name = NULL;
	node_data->content = NULL;
	node_data->attr = NULL;
	node_data->depth = 0;
	node_data->doc = doc;
	root = g_node_new((gpointer)node_data);

	doc->root = root;

	parse_buffer(root, buff, l);

#ifdef XML_TRACE
	LOG(LOG_DEBUG, "OUT : xml_parse_file()");
#endif
	return(doc);
}
Exemple #14
0
void TdfParser::LoadFile(std::string const& filename)
{

	this->filename = filename;
	CFileHandler file(filename);
	if (!file.FileExists()) {
		throw content_error(("file " + filename + " not found").c_str());
	}

	const size_t fileBuf_size = file.FileSize();
	//char* fileBuf = new char[fileBuf_size];
	boost::scoped_array<char> fileBuf(new char[fileBuf_size]);

	file.Read(fileBuf.get(), file.FileSize());
	parse_buffer(fileBuf.get(), fileBuf_size);

	//delete[] fileBuf;
}
Exemple #15
0
static int parse_section_buffer(const char *buf, char **entry, char **value, prelude_bool_t default_value)
{
        int ret;
        char *ptr;

        buf += strspn(buf, "\n [");

        ptr = strchr(buf, ']');
        if ( ptr )
                *ptr = 0;

        ret = parse_buffer(buf, entry, value);
        if ( ptr )
                *ptr = ']';

        if ( ! *value && default_value )
                *value = strdup("default");

        return ret;
}
Exemple #16
0
/*
 * Search an entry (delimited by '=' character) in content.
 * returns the line number matching 'entry' or -1.
 */
static int search_entry(config_t *cfg, const char *section,
                        const char *entry, unsigned int *index, char **eout, char **vout)
{
        int ret;
        unsigned int i = *index;

        if ( ! cfg->content || i >= cfg->elements )
                return -1;

        if ( section && ! index ) {

                ret = search_section(cfg, section, 0);
                if ( ret < 0 )
                        return ret;

                i = (unsigned int) ret + 1;
        }

        for ( ; i < cfg->elements; i++ ) {

                if ( section && is_section(cfg->content[i]) )
                        return -1;

                ret = parse_buffer(cfg->content[i], eout, vout);
                if ( ret < 0 || ! *eout )
                        continue;

                ret = strcmp(entry, *eout);
                if ( ret == 0 ) {
                        *index = i;
                        return 0;
                }

                free_val(eout);
                free_val(vout);
        }

        return -1;
}
Exemple #17
0
int jt_dbg_debug_file(int argc, char **argv)
{
	int fdin;
	int fdout;
	int rc;

	if (argc > 3 || argc < 2) {
		fprintf(stderr, "usage: %s <input> [output]\n", argv[0]);
		return 0;
	}

	fdin = open(argv[1], O_RDONLY | O_LARGEFILE);
	if (fdin < 0) {
		fprintf(stderr, "open(%s) failed: %s\n", argv[1],
			strerror(errno));
		return 1;
	}
	if (argc > 2) {
		fdout = open(argv[2],
			     O_CREAT | O_TRUNC | O_WRONLY | O_LARGEFILE,
			     0600);
		if (fdout < 0) {
			fprintf(stderr, "open(%s) failed: %s\n", argv[2],
				strerror(errno));
			close(fdin);
			return 1;
		}
	} else {
		fdout = fileno(stdout);
	}

	rc = parse_buffer(fdin, fdout);

	close(fdin);
	if (fdout != fileno(stdout))
		close(fdout);

	return rc;
}
Exemple #18
0
/*
 * _config_get_next:
 * @cfg: Configuration file identifier.
 * @section: Pointer address where the current section should be stored.
 * @entry: Pointer address where the current entry should be stored.
 * @value: Pointer address where the current value should be stored.
 * @line: Pointer to a line number we should start the search at.
 *
 * Parses the whole configuration file starting at @line,
 * and stores the current section, entry and value within the
 * provided argument.
 *
 * The caller has to call config_get_next() until it returns -1
 * or memory will be leaked.
 *
 * If the value gathered starts with a '$', which means it is
 * a variable, the variable is automatically looked up.
 *
 * Returns: 0 on success, -1 if there is nothing more to read.
 */
int _config_get_next(config_t *cfg, char **section, char **entry, char **value, unsigned int *line)
{
        int ret;
        char *ptr;

        free_val(entry);
        free_val(value);
        free_val(section);

        if ( ! cfg->content || *line >= cfg->elements )
                return -1;

        while ( *line < cfg->elements ) {

                ptr = cfg->content[*line];
                ptr += strspn(ptr, " \t\r");
                (*line)++;

                if ( ! *ptr || is_line_commented(ptr) )
                        continue;

                if ( is_section(ptr) )
                        return parse_section_buffer(ptr, section, value, FALSE);

                ret = parse_buffer(ptr, entry, value);
                if ( ret >= 0 && **entry == '$' ) {
                        free_val(entry);
                        free_val(value);
                        continue;
                }

                return ret;
        }

        (*line)--;

        return -1;
}
Exemple #19
0
/*
 * Parse the UsnJrnl file.
 * Iterates through the file in blocks.
 * Returns 0 on success, 1 otherwise
 */
static uint8_t
parse_file(NTFS_INFO * ntfs, unsigned char *buf,
           TSK_FS_USNJENTRY_WALK_CB action, void *ptr)
{
    ssize_t size = 0;
    TSK_OFF_T offset = 0, ret = 0;

    while ((size = tsk_fs_file_read(ntfs->usnjinfo->fs_file, offset,
                                    (char*)buf, ntfs->usnjinfo->bsize,
                                    TSK_FS_FILE_READ_FLAG_NONE)) > 0)
    {
        ret = parse_buffer(buf, size, ntfs->fs_info.endian, action, ptr);

        if (ret < 0)
            return 1;
        else if (ret == 0)
            return 0;

        offset += ret;
    }

    return 0;
}
Exemple #20
0
int
CodeRevision::parse() { 

    if ( _status >= rev_PARSED ) return 1; //already parsed

    _parsed_program = parse_buffer( _buffer );
    if ( _parsed_program ) { 
      //        if ( _parse_tree ) { 
      //      delete _parse_tree;
      //      _parse_tree = NULL;
      //  }
      //  _parse_tree = new tree_a_File_(_parsed_program, 1, _buffer->nlines() );
      //  int f = _parse_tree->findfirst();
      //  _parse_tree->firstline = 1;
      //
        _status = rev_PARSED;
        fprintf (stderr, "rev-parsed\n");

        return 1;
    }
    else 
        return 0;
}
void * sp_in_thread::Entry()
{
   while ( !this->TestDestroy()){
      if ( idx == 999){
         idx = 0;
      }
      auto & app = wxGetApp();
      bool new_data = false;
      char ch;
      { // CS
         wxCriticalSectionLocker lock(app.m_sp_CS);
         if ( app.have_sp() ){
            auto sp = app.get_sp();
            if ( sp->in_avail() ){
               unsigned  char uch;
               sp->read(&uch,1);
               ch = (char) uch;
               new_data = true;
            }
         }
      }// ~CS
      if (new_data){
         if ( ch == '\n'){
            buffer[idx] = '\0';
            idx = 0;
            parse_buffer();
         }else{
            buffer[idx] = ch;
            ++idx;
         }
      }
   }
   wxCriticalSectionLocker(m_main_frame->m_thread_CS);
   m_main_frame->m_sp_in_thread = nullptr;
   return nullptr;
}
Exemple #22
0
static term *tool_read_term(void)
{
  int nelem;
  term *trm, *rtrm;
  inport *inp;
  TBbool sndvoid = TBfalse;

  while(TBtrue){
    if(stand_alone){
      fprintf(stdout, "%s", single_prompt);
      fflush(stdout);
    }
    inp = NULL;
    nelem = read_from_any_channel(&inp);
    if(nelem < 0){
      err_warn("tool_read_term: cannot find ready input channel");
      continue;
    }
    if(inp && inp->term_port){
      if((trm = parse_buffer())){
	/*TBmsg("tool_read_term: ***%t***\n", trm);*/
	if(streq(get_txt(fun_sym(trm)), "rec-do"))
          sndvoid = TBtrue;
	rtrm = (*inp->callbackTerm)(trm);
	if(sndvoid)
	  return Snd_Void;
	else
	  return rtrm;
      }
    } else {
      if(inp)
	return (*inp->callbackChar)(inp->in);
    } 
  }
  return NULL; /* <PO> missing return from lcc */
}
Exemple #23
0
feed parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag, newsbeuter::remote_api * api) {
	std::string buf;
	CURLcode ret;

	CURL * easyhandle = curl_easy_init();
	if (!easyhandle) {
		throw exception(_("couldn't initialize libcurl"));
	}

	if (ua) {
		curl_easy_setopt(easyhandle, CURLOPT_USERAGENT, ua);
	}
	if (api) {
		api->configure_handle(easyhandle);
	}
	curl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str());
	curl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, 0);
	curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data);
	curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf);
	curl_easy_setopt(easyhandle, CURLOPT_NOSIGNAL, 1);
	curl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(easyhandle, CURLOPT_MAXREDIRS, 10);
	curl_easy_setopt(easyhandle, CURLOPT_FAILONERROR, 1);
	curl_easy_setopt(easyhandle, CURLOPT_ENCODING, "gzip, deflate");
	if (to != 0)
		curl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, to);

	if (prx){
		curl_easy_setopt(easyhandle, CURLOPT_PROXY, prx);
        curl_easy_setopt(easyhandle, CURLOPT_HTTPPROXYTUNNEL ,"1");
    }

	if (prxauth) {
		curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
		curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, prxauth);
	}

	curl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, prxtype);

	header_values hdrs = { 0, "" };

	curl_slist * custom_headers = NULL;

	if (lastmodified != 0) {
		curl_easy_setopt(easyhandle, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
		curl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, lastmodified);
		curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs);
		curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers);
	}
	if (etag.length() > 0) {
		custom_headers = curl_slist_append(custom_headers, utils::strprintf("If-None-Match: %s", etag.c_str()).c_str());
		curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, custom_headers);
		curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs);
		curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers);
	}

	ret = curl_easy_perform(easyhandle);

	lm = hdrs.lastmodified;
	et = hdrs.etag;

	if (custom_headers) {
		curl_slist_free_all(custom_headers);
	}

	LOG(LOG_DEBUG, "rsspp::parser::parse_url: ret = %d", ret);

	long status;
	curl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE, &status);

	if (status >= 400) {
		LOG(LOG_USERERROR, _("Error: trying to download feed `%s' returned HTTP status code %ld."), url.c_str(), status);
	}

	curl_easy_cleanup(easyhandle);

	if (ret != 0) {
		LOG(LOG_ERROR, "rsspp::parser::parse_url: curl_easy_perform returned err %d: %s", ret, curl_easy_strerror(ret));
		throw exception(curl_easy_strerror(ret));
	}

	LOG(LOG_INFO, "parser::parse_url: retrieved data for %s: %s", url.c_str(), buf.c_str());

	if (buf.length() > 0) {
		LOG(LOG_DEBUG, "parser::parse_url: handing over data to parse_buffer()");
		return parse_buffer(buf.c_str(), buf.length(), url.c_str());
	}

	return feed();
}
Exemple #24
0
int jt_dbg_debug_kernel(int argc, char **argv)
{
	struct stat	st;
	char		filename[PATH_MAX];
	int		raw = 0;
	int		save_errno;
	int		fdin;
	int		fdout;
	int		rc;

	if (argc > 3) {
		fprintf(stderr, "usage: %s [file] [raw]\n", argv[0]);
		return 0;
	}

	if (argc > 2) {
		raw = atoi(argv[2]);
	} else if (argc > 1 && (argv[1][0] == '0' || argv[1][0] == '1')) {
		raw = atoi(argv[1]);
		argc--;
	}

	/* If we are dumping raw (which means no conversion step to ASCII)
	 * then dump directly to any supplied filename, otherwise this is
	 * just a temp file and we dump to the real file at convert time. */
	if (argc > 1 && raw) {
		if (strlen(argv[1]) >= sizeof(filename)) {
			fprintf(stderr, "File name too long: %s\n", argv[1]);
			return 1;
		}
		strncpy(filename, argv[1], sizeof(filename));
	} else {
		if (snprintf(filename, sizeof(filename), "%s"CFS_TIME_T".%u",
			     LIBCFS_DEBUG_FILE_PATH_DEFAULT, time(NULL),
			     getpid())
		    >= sizeof(filename)) {
			fprintf(stderr, "File name too long\n");
			return 1;
		}
	}

	if (stat(filename, &st) == 0 && S_ISREG(st.st_mode))
		unlink(filename);

	fdin = dbg_open_ctlhandle(DUMP_KERNEL_CTL_NAME);
	if (fdin < 0) {
		fprintf(stderr, "open(dump_kernel) failed: %s\n",
			strerror(errno));
		return 1;
	}

	rc = dbg_write_cmd(fdin, filename, strlen(filename));
	save_errno = errno;
	dbg_close_ctlhandle(fdin);
	if (rc != 0) {
		fprintf(stderr, "write(%s) failed: %s\n", filename,
			strerror(save_errno));
		return 1;
	}

	if (raw)
		return 0;

	fdin = open(filename, O_RDONLY);
	if (fdin < 0) {
		if (errno == ENOENT) /* no dump file created */
			return 0;
		fprintf(stderr, "fopen(%s) failed: %s\n", filename,
			strerror(errno));
		return 1;
	}
	if (argc > 1) {
		fdout = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC,
			     S_IRUSR | S_IWUSR);
		if (fdout < 0) {
			fprintf(stderr, "fopen(%s) failed: %s\n", argv[1],
				strerror(errno));
			close(fdin);
			return 1;
		}
	} else {
		fdout = fileno(stdout);
	}

	rc = parse_buffer(fdin, fdout);
	close(fdin);
	if (argc > 1)
		close(fdout);
	if (rc) {
		fprintf(stderr, "parse_buffer failed; leaving tmp file %s "
			"behind.\n", filename);
	} else {
		rc = unlink(filename);
		if (rc)
			fprintf(stderr, "dumped successfully, but couldn't "
				"unlink tmp file %s: %s\n", filename,
				strerror(errno));
	}

	return rc;
}
Exemple #25
0
LUA_API int lua_loadbuffer (lua_State *L, const char *buff, size_t size, const char *name) {
  int status = parse_buffer(L, buff, size, name);
  return status;
}
Exemple #26
0
LUA_API int lua_dobuffer (lua_State *L, const char *buff, size_t size, const char *name) {
  int status = parse_buffer(L, buff, size, name);
  if (status == 0)  /* parse OK? */
    status = lua_call(L, 0, LUA_MULTRET);  /* call main */
  return status;
}
 void ParserImpl::end()
 {
     char const * empty = "";
     clear();
     parse_buffer(empty, empty, empty);
 }
Exemple #28
0
int main(int argc, char** argv) {
  //variables
  int A;	// number of slots to Actions that can be received
  int B;	// number of bartenders 
  int C;	// number of cups
  int S;	// number of students
  int M;	// maximum number of students that can be at the bar at once
  int fconf;
  int conf_size;
  struct stat bufstat;
  
  fconf = open("con.conf",O_RDONLY);
  fstat(fconf,&bufstat);
  conf_size = bufstat.size;
  char bufconf[conf_size];
  read(fconf,bufconf,conf_size);
  int inputs_parsed[5]; //{Aval, Bval, Cval, Sval, Mval}
  
  parse_buffer(bufconf, inputs_parsed);
  A = inputs_parsed[0];
  B = inputs_parsed[1];
  C = inputs_parsed[2];
  S = inputs_parsed[3];
  M = inputs_parsed[4];
  
  printf(1,"A: %d B: %d C: %d  S: %d M: %d\n",A,B,C,S,M);
  
  void* students_stacks[S];
  void* bartenders_stacks[B];
  void* cup_boy_stack;
  int i;
  int student_tids[S];
  //int bartender_tids[B];
  finished_shift = 0; // cup_boy changes it to 1 if all students left the bar and sends Action => GO_HOME to bartenders

  
  file_to_write = open("out.txt",(O_CREATE | O_WRONLY)); //
  if(file_to_write == -1){
      printf(1,"There was an error opening out.txt\n");
      exit();
  }
  
  
  //Databases
   bouncer = semaphore_create(M);		//this is the bouncer to the Beinstein
   ABB = BB_create(A); 				//this is a BB for student actions: drink, ans for a dring
   DrinkBB = BB_create(A);			//this is a BB holding the drinks that are ready to be drinking
   CBB = BB_create(C);				//this is a BB hold clean cups
   DBB = BB_create(C);				//this is a BB hold dirty cups
   cup_boy_lock = binary_semaphore_create(0); 	// initial cup_boy with 0 so he goes to sleep imidietly on first call to down
   general_mutex = binary_semaphore_create(1);

   //initialize C clean cups
   struct Cup* cup_array[C];
   for(i = 0; i < C; i++){
      cup_array[i] = malloc(sizeof(struct Cup)); //TODO free cups
      //memset(cup_array[i],0,sizeof(void*)*STACK_SIZE);
      cup_array[i]->id = i;
      add_clean_cup(cup_array[i]);
   }
   
   //initialize cup_boy
   cup_boy_stack = (void*)malloc(sizeof(void*)*STACK_SIZE);
   memset(cup_boy_stack,0,sizeof(void*)*STACK_SIZE);
   if(thread_create((void*)cup_boy,cup_boy_stack,sizeof(void*)*STACK_SIZE) < 0){
     printf(2,"Failed to create cupboy thread. Exiting...\n");
    exit();
   }
   
   //initialize B bartenders
   for(i = 0; i < B; i++){
      bartenders_stacks[i] = (void*)malloc(sizeof(void*)*STACK_SIZE);
      memset(bartenders_stacks[i],0,sizeof(void*)*STACK_SIZE);
     thread_create((void*)bartender,bartenders_stacks[i],sizeof(void*)*STACK_SIZE);//TODO test
      //bartender_tids[i] = 
  }
   
   //initialize S students
   for(i = 0; i < S; i++){//TODO test for fail
      students_stacks[i] = malloc(sizeof(void*)*STACK_SIZE);
      memset(students_stacks[i],0,sizeof(void*)*STACK_SIZE);
      student_tids[i] = thread_create((void*)student,students_stacks[i],sizeof(void*)*STACK_SIZE);
  }
  
   join_peoples(student_tids,S); //join students
   finished_shift = 1;
    
    
   //join_peoples(bartender_tids,B); //join bartenders
   sleep(2); // delay so exit will not come before threads finished TODO (need better soloution)
   
   
   if(finished_shift){
      binary_semaphore_up(cup_boy_lock); 
    }
    
    
   if(close(file_to_write) == -1){
    printf(1,"There was an error closing out.txt\n");
    exit();
   }
   
  //free cup_boy_stack
  free(cup_boy_stack);
  
  //after all students have finished need to exit all bartenders and cup boy, and free all memory allocation
  //free cups
  for(i = 0; i < C; i++){
    free(cup_array[i]);
  }
  //free bartenders_stacks
  for(i = 0; i < B; i++){
   free(bartenders_stacks[i]); 
  }
  //free students_stacks
  for(i = 0; i < S; i++){
   free(students_stacks[i]); 
  }
  semaphore_free(bouncer);
  BB_free(ABB);
  BB_free(DrinkBB);
  BB_free(CBB);
  BB_free(DBB);
 
  exit();
  return 0;
}
Exemple #29
0
void TdfParser::LoadBuffer(char const* buf, size_t size)
{
	this->filename = "buffer";
	parse_buffer(buf, size);
}
Exemple #30
0
feed parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag, newsbeuter::remote_api * api, const std::string& cookie_cache, CURL *ehandle) {
	std::string buf;
	CURLcode ret;
	curl_slist* custom_headers {};

	CURL * easyhandle = ehandle;
	if (!easyhandle) {
		easyhandle = curl_easy_init();
		if (!easyhandle) {
			throw exception(_("couldn't initialize libcurl"));
		}
	}

	if (! ua.empty()) {
		curl_easy_setopt(easyhandle, CURLOPT_USERAGENT, ua.c_str());
	}

	if (api) {
		api->add_custom_headers(&custom_headers);
	}
	curl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str());
	curl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, verify_ssl);
	curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data);
	curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf);
	curl_easy_setopt(easyhandle, CURLOPT_NOSIGNAL, 1);
	curl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(easyhandle, CURLOPT_MAXREDIRS, 10);
	curl_easy_setopt(easyhandle, CURLOPT_FAILONERROR, 1);
	curl_easy_setopt(easyhandle, CURLOPT_ENCODING, "gzip, deflate");
	if (cookie_cache != "") {
		curl_easy_setopt(easyhandle, CURLOPT_COOKIEFILE, cookie_cache.c_str());
		curl_easy_setopt(easyhandle, CURLOPT_COOKIEJAR, cookie_cache.c_str());
	}
	if (to != 0)
		curl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, to);

	if (! prx.empty())
		curl_easy_setopt(easyhandle, CURLOPT_PROXY, prx.c_str());

	if (! prxauth.empty()) {
		curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
		curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, prxauth.c_str());
	}

	curl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, prxtype);

	header_values hdrs;
	curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs);
	curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers);

	if (lastmodified != 0) {
		curl_easy_setopt(easyhandle, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
		curl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, lastmodified);
	}

	if (etag.length() > 0) {
		auto header = strprintf::fmt("If-None-Match: %s", etag);
		custom_headers = curl_slist_append(custom_headers, header.c_str());
	}

	if (lastmodified != 0 || etag.length() > 0) {
		custom_headers = curl_slist_append(custom_headers, "A-IM: feed");
	}

	if (custom_headers) {
		curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, custom_headers);
	}

	ret = curl_easy_perform(easyhandle);

	lm = hdrs.lastmodified;
	et = hdrs.etag;

	if (custom_headers) {
		curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, 0);
		curl_slist_free_all(custom_headers);
	}

	LOG(level::DEBUG, "rsspp::parser::parse_url: ret = %d", ret);

	long status;
	curl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE, &status);

	if (status >= 400) {
		LOG(level::USERERROR, _("Error: trying to download feed `%s' returned HTTP status code %ld."), url, status);
	}

	curl_easy_reset(easyhandle);

	if (!ehandle)
		curl_easy_cleanup(easyhandle);

	if (ret != 0) {
		LOG(level::ERROR, "rsspp::parser::parse_url: curl_easy_perform returned err %d: %s", ret, curl_easy_strerror(ret));
		throw exception(curl_easy_strerror(ret));
	}

	LOG(level::INFO, "parser::parse_url: retrieved data for %s: %s", url, buf);

	if (buf.length() > 0) {
		LOG(level::DEBUG, "parser::parse_url: handing over data to parse_buffer()");
		return parse_buffer(buf, url);
	}

	return feed();
}