Example #1
0
void
hstcpcli::request_buf_exec_generic(size_t pst_id, const string_ref& op,
  const string_ref *kvs, size_t kvslen, uint32 limit, uint32 skip,
  const string_ref& mod_op, const string_ref *mvs, size_t mvslen,
  const hstcpcli_filter *fils, size_t filslen, int invalues_keypart,
  const string_ref *invalues, size_t invalueslen)
{
/*
  if (num_req_sent > 0 || num_req_rcvd > 0) {
*/
  if (num_req_rcvd > 0) {
    close();
    set_error(-1, "request_buf_exec_generic: protocol out of sync");
    return;
  }
  append_uint32(writebuf, pst_id); // FIXME size_t ?
  writebuf.append_literal("\t");
  writebuf.append(op.begin(), op.end());
  writebuf.append_literal("\t");
  append_uint32(writebuf, kvslen); // FIXME size_t ?
  for (size_t i = 0; i < kvslen; ++i) {
    const string_ref& kv = kvs[i];
    append_delim_value(writebuf, kv.begin(), kv.end());
  }
  if (limit != 0 || skip != 0 || invalues_keypart >= 0 ||
    mod_op.size() != 0 || filslen != 0) {
    /* has more option */
    writebuf.append_literal("\t");
    append_uint32(writebuf, limit); // FIXME size_t ?
    if (skip != 0 || invalues_keypart >= 0 ||
      mod_op.size() != 0 || filslen != 0) {
      writebuf.append_literal("\t");
      append_uint32(writebuf, skip); // FIXME size_t ?
    }
    if (invalues_keypart >= 0) {
      writebuf.append_literal("\t@\t");
      append_uint32(writebuf, invalues_keypart);
      writebuf.append_literal("\t");
      append_uint32(writebuf, invalueslen);
      for (size_t i = 0; i < invalueslen; ++i) {
        const string_ref& s = invalues[i];
        append_delim_value(writebuf, s.begin(), s.end());
      }
    }
    for (size_t i = 0; i < filslen; ++i) {
      const hstcpcli_filter& f = fils[i];
      writebuf.append_literal("\t");
      writebuf.append(f.filter_type.begin(), f.filter_type.end());
      writebuf.append_literal("\t");
      writebuf.append(f.op.begin(), f.op.end());
      writebuf.append_literal("\t");
      append_uint32(writebuf, f.ff_offset);
      append_delim_value(writebuf, f.val.begin(), f.val.end());
    }
    if (mod_op.size() != 0) {
      writebuf.append_literal("\t");
      writebuf.append(mod_op.begin(), mod_op.end());
      for (size_t i = 0; i < mvslen; ++i) {
        const string_ref& mv = mvs[i];
        append_delim_value(writebuf, mv.begin(), mv.end());
      }
    }
  }
  writebuf.append_literal("\n");
  ++num_req_bufd;
}
template <DbType Type> void
GncDbiBackend<Type>::session_begin (QofSession* session, const char* book_id,
                                    bool ignore_lock, bool create, bool force)
{
    GncDbiTestResult dbi_test_result = GNC_DBI_PASS;
    PairVec options;

    g_return_if_fail (session != nullptr);
    g_return_if_fail (book_id != nullptr);

    ENTER (" ");

    /* Split the book-id
     * Format is protocol://username:password@hostname:port/dbname
     where username, password and port are optional) */
    UriStrings uri(book_id);

    if (Type == DbType::DBI_PGSQL)
    {
        if (uri.m_portnum == 0)
            uri.m_portnum = PGSQL_DEFAULT_PORT;
        /* Postgres's SQL interface coerces identifiers to lower case, but the
         * C interface is case-sensitive. This results in a mixed-case dbname
         * being created (with a lower case name) but then dbi can't conect to
         * it. To work around this, coerce the name to lowercase first. */
        auto lcname = g_utf8_strdown (uri.dbname(), -1);
        uri.m_dbname = std::string{lcname};
        g_free(lcname);
    }
    connect(nullptr);

    auto conn = conn_setup(options, uri);
    if (conn == nullptr)
    {
        LEAVE("Error");
        return;
    }

    m_exists = true; //May be unset in the error handler.
    auto result = dbi_conn_connect (conn);
    if (result == 0)
    {
        if (Type == DbType::DBI_MYSQL)
            adjust_sql_options (conn);
        if(!conn_test_dbi_library(conn))
        {
            dbi_conn_close(conn);
            LEAVE("Error");
            return;
        }
        if (create && !force && save_may_clobber_data (conn,
                                                       uri.quote_dbname(Type)))
        {
            set_error (ERR_BACKEND_STORE_EXISTS);
            PWARN ("Databse already exists, Might clobber it.");
            dbi_conn_close(conn);
            LEAVE("Error");
            return;
        }

    }
    else
    {

        if (m_exists)
        {
            PERR ("Unable to connect to database '%s'\n", uri.dbname());
            set_error (ERR_BACKEND_SERVER_ERR);
            dbi_conn_close(conn);
            LEAVE("Error");
            return;
        }

        if (create)
        {
            if (!create_database(conn, uri.quote_dbname(Type).c_str()))
            {
                dbi_conn_close(conn);
                LEAVE("Error");
                return;
            }
            conn = conn_setup(options, uri);
            result = dbi_conn_connect (conn);
            if (result < 0)
            {
                PERR ("Unable to create database '%s'\n", uri.dbname());
                set_error (ERR_BACKEND_SERVER_ERR);
                dbi_conn_close(conn);
                LEAVE("Error");
                return;
            }
            if (Type == DbType::DBI_MYSQL)
                adjust_sql_options (conn);
            if (!conn_test_dbi_library(conn))
            {
                if (Type == DbType::DBI_PGSQL)
                    dbi_conn_select_db (conn, "template1");
                dbi_conn_queryf (conn, "DROP DATABASE %s",
                                 uri.quote_dbname(Type).c_str());
                dbi_conn_close(conn);
                return;
            }
        }
        else
        {
            set_error(ERR_BACKEND_NO_SUCH_DB);
            std::string msg{"Database "};
            set_message(msg + uri.dbname() + " not found");
        }
    }

    connect(nullptr);
    try
    {
        connect(new GncDbiSqlConnection(Type, this, conn, ignore_lock));
    }
    catch (std::runtime_error& err)
    {
        return;
    }
    /* We should now have a proper session set up.
     * Let's start logging */
    auto translog_path = gnc_build_translog_path (uri.basename().c_str());
    xaccLogSetBaseName (translog_path);
    PINFO ("logpath=%s", translog_path ? translog_path : "(null)");
    g_free (translog_path);

    LEAVE (" ");
}
Example #3
0
uint8 ArchDrive::open_file(int channel, const uint8 *name, int name_len)
{
	uint8 plain_name[NAMEBUF_LENGTH];
	int plain_name_len;
	int mode = FMODE_READ;
	int type = FTYPE_DEL;
	int rec_len = 0;
	parse_file_name(name, name_len, plain_name, plain_name_len, mode, type, rec_len);

	// Channel 0 is READ, channel 1 is WRITE
	if (channel == 0 || channel == 1) {
		mode = channel ? FMODE_WRITE : FMODE_READ;
		if (type == FTYPE_DEL)
			type = FTYPE_PRG;
	}

	bool writing = (mode == FMODE_WRITE || mode == FMODE_APPEND);

	// Wildcards are only allowed on reading
	if (writing && (strchr((const char *)plain_name, '*') || strchr((const char *)plain_name, '?'))) {
		set_error(ERR_SYNTAX33);
		return ST_OK;
	}

	// Allow only read accesses
	if (writing) {
		set_error(ERR_WRITEPROTECT);
		return ST_OK;
	}

	// Relative files are not supported
	if (type == FTYPE_REL) {
		set_error(ERR_UNIMPLEMENTED);
		return ST_OK;
	}

	// Find file
	int num;
	if (find_first_file(plain_name, plain_name_len, num)) {

		// Open temporary file
		if ((file[channel] = tmpfile()) != NULL) {

			// Write load address (.t64 only)
			if (archive_type == TYPE_T64) {
				fwrite(&file_info[num].sa_lo, 1, 1, file[channel]);
				fwrite(&file_info[num].sa_hi, 1, 1, file[channel]);
			}

			// Copy file contents from archive file to temp file
			uint8 *buf = new uint8[file_info[num].size];
			fseek(the_file, file_info[num].offset, SEEK_SET);
			fread(buf, file_info[num].size, 1, the_file);
			fwrite(buf, file_info[num].size, 1, file[channel]);
			rewind(file[channel]);
			delete[] buf;

			if (mode == FMODE_READ)	// Read and buffer first byte
				read_char[channel] = getc(file[channel]);
		}
	} else
		set_error(ERR_FILENOTFOUND);

	return ST_OK;
}
Example #4
0
/*
 * Process a lease query.
 */
void
dhcpv6_leasequery(struct data_string *reply_ret, struct packet *packet) {
	static struct lq6_state lq;
	struct option_cache *oc;
	int allow_lq;

	/*
	 * Initialize the lease query state.
	 */
	lq.packet = NULL;
	memset(&lq.client_id, 0, sizeof(lq.client_id));
	memset(&lq.server_id, 0, sizeof(lq.server_id));
	memset(&lq.lq_query, 0, sizeof(lq.lq_query));
	lq.query_opts = NULL;
	lq.reply_opts = NULL;
	packet_reference(&lq.packet, packet, MDL);

	/*
	 * Validate our input.
	 */
	if (!valid_query_msg(&lq)) {
		goto exit;
	}

	/*
	 * Prepare our reply.
	 */
	if (!option_state_allocate(&lq.reply_opts, MDL)) {
		log_error("dhcpv6_leasequery: no memory for option state.");
		goto exit;
	}
	execute_statements_in_scope(NULL, lq.packet, NULL, NULL,
				    lq.packet->options, lq.reply_opts,
				    &global_scope, root_group, NULL);

	lq.buf.reply.msg_type = DHCPV6_LEASEQUERY_REPLY;

	memcpy(lq.buf.reply.transaction_id,
	       lq.packet->dhcpv6_transaction_id,
	       sizeof(lq.buf.reply.transaction_id));

	/* 
	 * Because LEASEQUERY has some privacy concerns, default to deny.
	 */
	allow_lq = 0;

	/*
	 * See if we are authorized to do LEASEQUERY.
	 */
	oc = lookup_option(&server_universe, lq.reply_opts, SV_LEASEQUERY);
	if (oc != NULL) {
		allow_lq = evaluate_boolean_option_cache(NULL,
							 lq.packet,
							 NULL, NULL,
							 lq.packet->options,
							 lq.reply_opts,
							 &global_scope,
							 oc, MDL);
	}

	if (!allow_lq) {
		log_info("dhcpv6_leasequery: not allowed, query ignored.");
		goto exit;
	}
	    
	/*
	 * Same than transmission of REPLY message in RFC 3315:
	 *  server-id
	 *  client-id
	 */

	oc = lookup_option(&dhcpv6_universe, lq.reply_opts, D6O_SERVERID);
	if (oc == NULL) {
		/* If not already in options, get from query then global. */
		if (lq.server_id.data == NULL)
			copy_server_duid(&lq.server_id, MDL);
		if (!save_option_buffer(&dhcpv6_universe,
					lq.reply_opts,
					NULL,
					(unsigned char *)lq.server_id.data,
					lq.server_id.len, 
					D6O_SERVERID,
					0)) {
			log_error("dhcpv6_leasequery: "
				  "error saving server identifier.");
			goto exit;
		}
	}

	if (!save_option_buffer(&dhcpv6_universe,
				lq.reply_opts,
				lq.client_id.buffer,
				(unsigned char *)lq.client_id.data,
				lq.client_id.len,
				D6O_CLIENTID,
				0)) {
		log_error("dhcpv6_leasequery: "
			  "error saving client identifier.");
		goto exit;
	}

	lq.cursor = 4;

	/*
	 * Decode the lq-query option.
	 */

	if (lq.lq_query.len <= LQ_QUERY_OFFSET) {
		if (!set_error(&lq, STATUS_MalformedQuery,
			       "OPTION_LQ_QUERY too short.")) {
			log_error("dhcpv6_leasequery: unable "
				  "to set MalformedQuery status code.");
			goto exit;
		}
		goto done;
	}

	lq.query_type = lq.lq_query.data [0];
	memcpy(&lq.link_addr, lq.lq_query.data + 1, sizeof(lq.link_addr));
	switch (lq.query_type) {
		case LQ6QT_BY_ADDRESS:
			break;
		case LQ6QT_BY_CLIENTID:
			if (!set_error(&lq, STATUS_UnknownQueryType,
				       "QUERY_BY_CLIENTID not supported.")) {
				log_error("dhcpv6_leasequery: unable to "
					  "set UnknownQueryType status code.");
				goto exit;
			}
			goto done;
		default:
			if (!set_error(&lq, STATUS_UnknownQueryType,
				       "Unknown query-type.")) {
				log_error("dhcpv6_leasequery: unable to "
					  "set UnknownQueryType status code.");
				goto exit;
			}
			goto done;
	}

	if (!option_state_allocate(&lq.query_opts, MDL)) {
		log_error("dhcpv6_leasequery: no memory for option state.");
		goto exit;
	}
	if (!parse_option_buffer(lq.query_opts,
				 lq.lq_query.data + LQ_QUERY_OFFSET,
				 lq.lq_query.len - LQ_QUERY_OFFSET,
				 &dhcpv6_universe)) {
		log_error("dhcpv6_leasequery: error parsing query-options.");
		if (!set_error(&lq, STATUS_MalformedQuery,
			       "Bad query-options.")) {
			log_error("dhcpv6_leasequery: unable "
				  "to set MalformedQuery status code.");
			goto exit;
		}
		goto done;
	}

	/* Do it. */
	if (!process_lq_by_address(&lq))
		goto exit;

      done:
	/* Store the options. */
	lq.cursor += store_options6((char *)lq.buf.data + lq.cursor,
				    sizeof(lq.buf) - lq.cursor,
				    lq.reply_opts,
				    lq.packet,
				    required_opts_lq,
				    NULL);

	/* Return our reply to the caller. */
	reply_ret->len = lq.cursor;
	reply_ret->buffer = NULL;
	if (!buffer_allocate(&reply_ret->buffer, lq.cursor, MDL)) {
		log_fatal("dhcpv6_leasequery: no memory to store Reply.");
	}
	memcpy(reply_ret->buffer->data, lq.buf.data, lq.cursor);
	reply_ret->data = reply_ret->buffer->data;

      exit:
	/* Cleanup. */
	if (lq.packet != NULL)
		packet_dereference(&lq.packet, MDL);
	if (lq.client_id.data != NULL)
		data_string_forget(&lq.client_id, MDL);
	if (lq.server_id.data != NULL)
		data_string_forget(&lq.server_id, MDL);
	if (lq.lq_query.data != NULL)
		data_string_forget(&lq.lq_query, MDL);
	if (lq.query_opts != NULL)
		option_state_dereference(&lq.query_opts, MDL);
	if (lq.reply_opts != NULL)
		option_state_dereference(&lq.reply_opts, MDL);
}
Example #5
0
static int look(Scanner *s) {
  int state = 0;
  int c = 0;
  String *str_delimiter = 0;

  Clear(s->text);
  s->start_line = s->line;
  Setfile(s->text, Getfile(s->str));


  while (1) {
    switch (state) {
    case 0:
      if ((c = nextchar(s)) == 0)
	return (0);

      /* Process delimiters */

      if (c == '\n') {
	return SWIG_TOKEN_ENDLINE;
      } else if (!isspace(c)) {
	retract(s, 1);
	state = 1000;
	Clear(s->text);
	Setline(s->text, s->line);
	Setfile(s->text, Getfile(s->str));
      }
      break;

    case 1000:
      if ((c = nextchar(s)) == 0)
        return (0);
      if (c == '%')
	state = 4;		/* Possibly a SWIG directive */
      
      /* Look for possible identifiers or unicode/delimiter strings */
      else if ((isalpha(c)) || (c == '_') ||
	       (s->idstart && strchr(s->idstart, c))) {
	state = 7;
      }

      /* Look for single character symbols */

      else if (c == '(') {
        brackets_push(s);
	return SWIG_TOKEN_LPAREN;
      }
      else if (c == ')') {
        brackets_pop(s);
	return SWIG_TOKEN_RPAREN;
      }
      else if (c == ';') {
        brackets_clear(s);
	return SWIG_TOKEN_SEMI;
      }
      else if (c == ',')
	return SWIG_TOKEN_COMMA;
      else if (c == '*')
	state = 220;
      else if (c == '}')
	return SWIG_TOKEN_RBRACE;
      else if (c == '{') {
        brackets_reset(s);
	return SWIG_TOKEN_LBRACE;
      }
      else if (c == '=')
	state = 33;
      else if (c == '+')
	state = 200;
      else if (c == '-')
	state = 210;
      else if (c == '&')
	state = 31;
      else if (c == '|')
	state = 32;
      else if (c == '^')
	state = 230;
      else if (c == '<')
	state = 60;
      else if (c == '>')
	state = 61;
      else if (c == '~')
	return SWIG_TOKEN_NOT;
      else if (c == '!')
	state = 3;
      else if (c == '\\')
	return SWIG_TOKEN_BACKSLASH;
      else if (c == '[')
	return SWIG_TOKEN_LBRACKET;
      else if (c == ']')
	return SWIG_TOKEN_RBRACKET;
      else if (c == '@')
	return SWIG_TOKEN_AT;
      else if (c == '$')
	state = 75;
      else if (c == '#')
	return SWIG_TOKEN_POUND;
      else if (c == '?')
	return SWIG_TOKEN_QUESTION;

      /* Look for multi-character sequences */

      else if (c == '/') {
	state = 1;		/* Comment (maybe)  */
	s->start_line = s->line;
      }

      else if (c == ':')
	state = 5;		/* maybe double colon */
      else if (c == '0')
	state = 83;		/* An octal or hex value */
      else if (c == '\"') {
	state = 2;              /* A string constant */
	s->start_line = s->line;
	Clear(s->text);
      }
      else if (c == '\'') {
	s->start_line = s->line;
	Clear(s->text);
	state = 9;		/* A character constant */
      } else if (c == '`') {
	s->start_line = s->line;
	Clear(s->text);
	state = 900;
      }

      else if (c == '.')
	state = 100;		/* Maybe a number, maybe just a period */
      else if (isdigit(c))
	state = 8;		/* A numerical value */
      else
	state = 99;		/* An error */
      break;

    case 1:			/*  Comment block */
      if ((c = nextchar(s)) == 0)
	return (0);
      if (c == '/') {
	state = 10;		/* C++ style comment */
	Clear(s->text);
	Setline(s->text, Getline(s->str));
	Setfile(s->text, Getfile(s->str));
	Append(s->text, "//");
      } else if (c == '*') {
	state = 11;		/* C style comment */
	Clear(s->text);
	Setline(s->text, Getline(s->str));
	Setfile(s->text, Getfile(s->str));
	Append(s->text, "/*");
      } else if (c == '=') {
	return SWIG_TOKEN_DIVEQUAL;
      } else {
	retract(s, 1);
	return SWIG_TOKEN_SLASH;
      }
      break;
    case 10:			/* C++ style comment */
      if ((c = nextchar(s)) == 0) {
	Swig_error(cparse_file, cparse_start_line, "Unterminated comment\n");
	return SWIG_TOKEN_ERROR;
      }
      if (c == '\n') {
	retract(s,1);
	return SWIG_TOKEN_COMMENT;
      } else {
	state = 10;
      }
      break;
    case 11:			/* C style comment block */
      if ((c = nextchar(s)) == 0) {
	Swig_error(cparse_file, cparse_start_line, "Unterminated comment\n");
	return SWIG_TOKEN_ERROR;
      }
      if (c == '*') {
	state = 12;
      } else {
	state = 11;
      }
      break;
    case 12:			/* Still in C style comment */
      if ((c = nextchar(s)) == 0) {
	Swig_error(cparse_file, cparse_start_line, "Unterminated comment\n");
	return SWIG_TOKEN_ERROR;
      }
      if (c == '*') {
	state = 12;
      } else if (c == '/') {
	return SWIG_TOKEN_COMMENT;
      } else {
	state = 11;
      }
      break;

    case 2:			/* Processing a string */
      if (!str_delimiter) {
	state=20;
	break;
      }
      
      if ((c = nextchar(s)) == 0) {
	Swig_error(cparse_file, cparse_start_line, "Unterminated string\n");
	return SWIG_TOKEN_ERROR;
      }
      else if (c == '(') {
	state = 20;
      }
      else {
	char temp[2] = { 0, 0 };
	temp[0] = c;
	Append( str_delimiter, temp );
      }
    
      break;

    case 20:			/* Inside the string */
      if ((c = nextchar(s)) == 0) {
	Swig_error(cparse_file, cparse_start_line, "Unterminated string\n");
	return SWIG_TOKEN_ERROR;
      }
      
      if (!str_delimiter) { /* Ordinary string: "value" */
	if (c == '\"') {
	  Delitem(s->text, DOH_END);
	  return SWIG_TOKEN_STRING;
	} else if (c == '\\') {
	  Delitem(s->text, DOH_END);
	  get_escape(s);
	}
      } else {             /* Custom delimiter string: R"XXXX(value)XXXX" */
	if (c==')') {
	  int i=0;
	  String *end_delimiter = NewStringEmpty();
	  while ((c = nextchar(s)) != 0 && c!='\"') {
	    char temp[2] = { 0, 0 };
	    temp[0] = c;
	    Append( end_delimiter, temp );
	    i++;
	  }
	  
	  if (Strcmp( str_delimiter, end_delimiter )==0) {
	    Delete( end_delimiter ); /* Correct end delimiter )XXXX" occured */
	    Delete( str_delimiter );
	    str_delimiter = 0;
	    return SWIG_TOKEN_STRING;
	  } else {                   /* Incorrect end delimiter occured */
	    if (c == 0) {
	      Swig_error(cparse_file, cparse_start_line, "Unterminated raw string, started with R\"%s( is not terminated by )%s\"\n", str_delimiter, str_delimiter);
	      return SWIG_TOKEN_ERROR;
	    }
	    retract( s, i );
	    Delete( end_delimiter );
	  }
	}
      }
      
      break;

    case 3:			/* Maybe a not equals */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_LNOT;
      else if (c == '=')
	return SWIG_TOKEN_NOTEQUAL;
      else {
	retract(s, 1);
	return SWIG_TOKEN_LNOT;
      }
      break;

    case 31:			/* AND or Logical AND or ANDEQUAL */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_AND;
      else if (c == '&')
	return SWIG_TOKEN_LAND;
      else if (c == '=')
	return SWIG_TOKEN_ANDEQUAL;
      else {
	retract(s, 1);
	return SWIG_TOKEN_AND;
      }
      break;

    case 32:			/* OR or Logical OR */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_OR;
      else if (c == '|')
	return SWIG_TOKEN_LOR;
      else if (c == '=')
	return SWIG_TOKEN_OREQUAL;
      else {
	retract(s, 1);
	return SWIG_TOKEN_OR;
      }
      break;

    case 33:			/* EQUAL or EQUALTO */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_EQUAL;
      else if (c == '=')
	return SWIG_TOKEN_EQUALTO;
      else {
	retract(s, 1);
	return SWIG_TOKEN_EQUAL;
      }
      break;

    case 4:			/* A wrapper generator directive (maybe) */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_PERCENT;
      if (c == '{') {
	state = 40;		/* Include block */
	Clear(s->text);
	Setline(s->text, Getline(s->str));
	Setfile(s->text, Getfile(s->str));
	s->start_line = s->line;
      } else if (s->idstart && strchr(s->idstart, '%') &&
	         ((isalpha(c)) || (c == '_'))) {
	state = 7;
      } else if (c == '=') {
	return SWIG_TOKEN_MODEQUAL;
      } else if (c == '}') {
	Swig_error(cparse_file, cparse_line, "Syntax error. Extraneous '%%}'\n");
	exit(1);
      } else {
	retract(s, 1);
	return SWIG_TOKEN_PERCENT;
      }
      break;

    case 40:			/* Process an include block */
      if ((c = nextchar(s)) == 0) {
	Swig_error(cparse_file, cparse_start_line, "Unterminated block\n");
	return SWIG_TOKEN_ERROR;
      }
      if (c == '%')
	state = 41;
      break;
    case 41:			/* Still processing include block */
      if ((c = nextchar(s)) == 0) {
	set_error(s,s->start_line,"Unterminated code block");
	return 0;
      }
      if (c == '}') {
	Delitem(s->text, DOH_END);
	Delitem(s->text, DOH_END);
	Seek(s->text,0,SEEK_SET);
	return SWIG_TOKEN_CODEBLOCK;
      } else {
	state = 40;
      }
      break;

    case 5:			/* Maybe a double colon */

      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_COLON;
      if (c == ':')
	state = 50;
      else {
	retract(s, 1);
	return SWIG_TOKEN_COLON;
      }
      break;

    case 50:			/* DCOLON, DCOLONSTAR */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_DCOLON;
      else if (c == '*')
	return SWIG_TOKEN_DCOLONSTAR;
      else {
	retract(s, 1);
	return SWIG_TOKEN_DCOLON;
      }
      break;

    case 60:			/* shift operators */
      if ((c = nextchar(s)) == 0) {
	brackets_increment(s);
	return SWIG_TOKEN_LESSTHAN;
      }
      if (c == '<')
	state = 240;
      else if (c == '=')
	return SWIG_TOKEN_LTEQUAL;
      else {
	retract(s, 1);
	brackets_increment(s);
	return SWIG_TOKEN_LESSTHAN;
      }
      break;
    case 61:
      if ((c = nextchar(s)) == 0) {
        brackets_decrement(s);
	return SWIG_TOKEN_GREATERTHAN;
      }
      if (c == '>' && brackets_allow_shift(s))
	state = 250;
      else if (c == '=')
	return SWIG_TOKEN_GTEQUAL;
      else {
	retract(s, 1);
        brackets_decrement(s);
	return SWIG_TOKEN_GREATERTHAN;
      }
      break;
    
    case 7:			/* Identifier or true/false or unicode/custom delimiter string */
      if (c == 'R') { /* Possibly CUSTOM DELIMITER string */
	state = 72;
	break;
      }
      else if (c == 'L') { /* Probably identifier but may be a wide string literal */
	state = 77;
	break;
      }
      else if (c != 'u' && c != 'U') { /* Definitely an identifier */
	state = 70;
	break;
      }
      
      if ((c = nextchar(s)) == 0) {
	state = 76;
      }
      else if (c == '\"') { /* Definitely u, U or L string */
	retract(s, 1);
	state = 1000;
      }
      else if (c == 'R') { /* Possibly CUSTOM DELIMITER u, U, L string */
	state = 73;
      }
      else if (c == '8') { /* Possibly u8 string */
	state = 71;
      }
      else {
	retract(s, 1);   /* Definitely an identifier */
	state = 70;
      }
      break;

    case 70:			/* Identifier */
      if ((c = nextchar(s)) == 0)
	state = 76;
      else if (isalnum(c) || (c == '_') || (c == '$')) {
	state = 70;
      } else {
	retract(s, 1);
	state = 76;
      }
      break;
    
    case 71:			/* Possibly u8 string */
      if ((c = nextchar(s)) == 0) {
	state = 76;
      }
      else if (c=='\"') {
	retract(s, 1); /* Definitely u8 string */
	state = 1000;
      }
      else if (c=='R') {
	state = 74; /* Possibly CUSTOM DELIMITER u8 string */
      }
      else {
	retract(s, 2); /* Definitely an identifier. Retract 8" */
	state = 70;
      }
      
      break;

    case 72:			/* Possibly CUSTOM DELIMITER string */
    case 73:
    case 74:
      if ((c = nextchar(s)) == 0) {
	state = 76;
      }
      else if (c=='\"') {
	retract(s, 1); /* Definitely custom delimiter u, U or L string */
	str_delimiter = NewStringEmpty();
	state = 1000;
      }
      else {
	if (state==72) {
	  retract(s, 1); /* Definitely an identifier. Retract ? */
	}
	else if (state==73) {
	  retract(s, 2); /* Definitely an identifier. Retract R? */
	}
	else if (state==74) {
	  retract(s, 3); /* Definitely an identifier. Retract 8R? */
	}
	state = 70;
      }
      
      break;

    case 75:			/* Special identifier $ */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_DOLLAR;
      if (isalnum(c) || (c == '_') || (c == '*') || (c == '&')) {
	state = 70;
      } else {
	retract(s,1);
	if (Len(s->text) == 1) return SWIG_TOKEN_DOLLAR;
	state = 76;
      }
      break;

    case 76:			/* Identifier or true/false */
      if (cparse_cplusplus) {
	if (Strcmp(s->text, "true") == 0)
	  return SWIG_TOKEN_BOOL;
	else if (Strcmp(s->text, "false") == 0)
	  return SWIG_TOKEN_BOOL;
	}
      return SWIG_TOKEN_ID;
      break;

    case 77: /*identifier or wide string literal*/
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_ID;
      else if (c == '\"') {
	s->start_line = s->line;
	Clear(s->text);
	state = 78;
      }
      else if (c == '\'') {
	s->start_line = s->line;
	Clear(s->text);
	state = 79;
      }
      else if (isalnum(c) || (c == '_') || (c == '$'))
	state = 7;
      else {
	retract(s, 1);
	return SWIG_TOKEN_ID;
      }
    break;

    case 78:			/* Processing a wide string literal*/
      if ((c = nextchar(s)) == 0) {
	Swig_error(cparse_file, cparse_start_line, "Unterminated wide string\n");
	return SWIG_TOKEN_ERROR;
      }
      if (c == '\"') {
	Delitem(s->text, DOH_END);
	return SWIG_TOKEN_WSTRING;
      } else if (c == '\\') {
	if ((c = nextchar(s)) == 0) {
	  Swig_error(cparse_file, cparse_start_line, "Unterminated wide string\n");
	  return SWIG_TOKEN_ERROR;
	}
      }
      break;

    case 79:			/* Processing a wide char literal */
      if ((c = nextchar(s)) == 0) {
	Swig_error(cparse_file, cparse_start_line, "Unterminated wide character constant\n");
	return SWIG_TOKEN_ERROR;
      }
      if (c == '\'') {
	Delitem(s->text, DOH_END);
	return (SWIG_TOKEN_WCHAR);
      } else if (c == '\\') {
	if ((c = nextchar(s)) == 0) {
	  Swig_error(cparse_file, cparse_start_line, "Unterminated wide character literal\n");
	  return SWIG_TOKEN_ERROR;
	}
      }
      break;

    case 8:			/* A numerical digit */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_INT;
      if (c == '.') {
	state = 81;
      } else if ((c == 'e') || (c == 'E')) {
	state = 82;
      } else if ((c == 'f') || (c == 'F')) {
	Delitem(s->text, DOH_END);
	return SWIG_TOKEN_FLOAT;
      } else if (isdigit(c)) {
	state = 8;
      } else if ((c == 'l') || (c == 'L')) {
	state = 87;
      } else if ((c == 'u') || (c == 'U')) {
	state = 88;
      } else {
	retract(s, 1);
	return SWIG_TOKEN_INT;
      }
      break;
    case 81:			/* A floating pointer number of some sort */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_DOUBLE;
      if (isdigit(c))
	state = 81;
      else if ((c == 'e') || (c == 'E'))
	state = 820;
      else if ((c == 'f') || (c == 'F')) {
	Delitem(s->text, DOH_END);
	return SWIG_TOKEN_FLOAT;
      } else if ((c == 'l') || (c == 'L')) {
	Delitem(s->text, DOH_END);
	return SWIG_TOKEN_DOUBLE;
      } else {
	retract(s, 1);
	return (SWIG_TOKEN_DOUBLE);
      }
      break;
    case 82:
      if ((c = nextchar(s)) == 0) {
	retract(s, 1);
	return SWIG_TOKEN_INT;
      }
      if ((isdigit(c)) || (c == '-') || (c == '+'))
	state = 86;
      else {
	retract(s, 2);
	return (SWIG_TOKEN_INT);
      }
      break;
    case 820:
      /* Like case 82, but we've seen a decimal point. */
      if ((c = nextchar(s)) == 0) {
	retract(s, 1);
	return SWIG_TOKEN_DOUBLE;
      }
      if ((isdigit(c)) || (c == '-') || (c == '+'))
	state = 86;
      else {
	retract(s, 2);
	return (SWIG_TOKEN_DOUBLE);
      }
      break;
    case 83:
      /* Might be a hexadecimal or octal number */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_INT;
      if (isdigit(c))
	state = 84;
      else if ((c == 'x') || (c == 'X'))
	state = 85;
      else if (c == '.')
	state = 81;
      else if ((c == 'l') || (c == 'L')) {
	state = 87;
      } else if ((c == 'u') || (c == 'U')) {
	state = 88;
      } else {
	retract(s, 1);
	return SWIG_TOKEN_INT;
      }
      break;
    case 84:
      /* This is an octal number */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_INT;
      if (isdigit(c))
	state = 84;
      else if ((c == 'l') || (c == 'L')) {
	state = 87;
      } else if ((c == 'u') || (c == 'U')) {
	state = 88;
      } else {
	retract(s, 1);
	return SWIG_TOKEN_INT;
      }
      break;
    case 85:
      /* This is an hex number */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_INT;
      if (isxdigit(c))
	state = 85;
      else if ((c == 'l') || (c == 'L')) {
	state = 87;
      } else if ((c == 'u') || (c == 'U')) {
	state = 88;
      } else {
	retract(s, 1);
	return SWIG_TOKEN_INT;
      }
      break;

    case 86:
      /* Rest of floating point number */

      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_DOUBLE;
      if (isdigit(c))
	state = 86;
      else if ((c == 'f') || (c == 'F')) {
	Delitem(s->text, DOH_END);
	return SWIG_TOKEN_FLOAT;
      } else if ((c == 'l') || (c == 'L')) {
	Delitem(s->text, DOH_END);
	return SWIG_TOKEN_DOUBLE;
      } else {
	retract(s, 1);
	return SWIG_TOKEN_DOUBLE;
      }
      break;

    case 87:
      /* A long integer of some sort */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_LONG;
      if ((c == 'u') || (c == 'U')) {
	return SWIG_TOKEN_ULONG;
      } else if ((c == 'l') || (c == 'L')) {
	state = 870;
      } else {
	retract(s, 1);
	return SWIG_TOKEN_LONG;
      }
      break;

      /* A long long integer */

    case 870:
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_LONGLONG;
      if ((c == 'u') || (c == 'U')) {
	return SWIG_TOKEN_ULONGLONG;
      } else {
	retract(s, 1);
	return SWIG_TOKEN_LONGLONG;
      }

      /* An unsigned number */
    case 88:

      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_UINT;
      if ((c == 'l') || (c == 'L')) {
	state = 880;
      } else {
	retract(s, 1);
	return SWIG_TOKEN_UINT;
      }
      break;

      /* Possibly an unsigned long long or unsigned long */
    case 880:
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_ULONG;
      if ((c == 'l') || (c == 'L'))
	return SWIG_TOKEN_ULONGLONG;
      else {
	retract(s, 1);
	return SWIG_TOKEN_ULONG;
      }

      /* A character constant */
    case 9:
      if ((c = nextchar(s)) == 0) {
	Swig_error(cparse_file, cparse_start_line, "Unterminated character constant\n");
	return SWIG_TOKEN_ERROR;
      }
      if (c == '\'') {
	Delitem(s->text, DOH_END);
	return (SWIG_TOKEN_CHAR);
      } else if (c == '\\') {
	Delitem(s->text, DOH_END);
	get_escape(s);
      }
      break;

      /* A period or maybe a floating point number */

    case 100:
      if ((c = nextchar(s)) == 0)
	return (0);
      if (isdigit(c))
	state = 81;
      else {
	retract(s, 1);
	return SWIG_TOKEN_PERIOD;
      }
      break;

    case 200:			/* PLUS, PLUSPLUS, PLUSEQUAL */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_PLUS;
      else if (c == '+')
	return SWIG_TOKEN_PLUSPLUS;
      else if (c == '=')
	return SWIG_TOKEN_PLUSEQUAL;
      else {
	retract(s, 1);
	return SWIG_TOKEN_PLUS;
      }
      break;

    case 210:			/* MINUS, MINUSMINUS, MINUSEQUAL, ARROW */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_MINUS;
      else if (c == '-')
	return SWIG_TOKEN_MINUSMINUS;
      else if (c == '=')
	return SWIG_TOKEN_MINUSEQUAL;
      else if (c == '>')
	state = 211;
      else {
	retract(s, 1);
	return SWIG_TOKEN_MINUS;
      }
      break;

    case 211:			/* ARROW, ARROWSTAR */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_ARROW;
      else if (c == '*')
	return SWIG_TOKEN_ARROWSTAR;
      else {
	retract(s, 1);
	return SWIG_TOKEN_ARROW;
      }
      break;


    case 220:			/* STAR, TIMESEQUAL */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_STAR;
      else if (c == '=')
	return SWIG_TOKEN_TIMESEQUAL;
      else {
	retract(s, 1);
	return SWIG_TOKEN_STAR;
      }
      break;

    case 230:			/* XOR, XOREQUAL */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_XOR;
      else if (c == '=')
	return SWIG_TOKEN_XOREQUAL;
      else {
	retract(s, 1);
	return SWIG_TOKEN_XOR;
      }
      break;

    case 240:			/* LSHIFT, LSEQUAL */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_LSHIFT;
      else if (c == '=')
	return SWIG_TOKEN_LSEQUAL;
      else {
	retract(s, 1);
	return SWIG_TOKEN_LSHIFT;
      }
      break;

    case 250:			/* RSHIFT, RSEQUAL */
      if ((c = nextchar(s)) == 0)
	return SWIG_TOKEN_RSHIFT;
      else if (c == '=')
	return SWIG_TOKEN_RSEQUAL;
      else {
	retract(s, 1);
	return SWIG_TOKEN_RSHIFT;
      }
      break;


      /* An illegal character */

      /* Reverse string */
    case 900:
      if ((c = nextchar(s)) == 0) {
	Swig_error(cparse_file, cparse_start_line, "Unterminated character constant\n");
	return SWIG_TOKEN_ERROR;
      }
      if (c == '`') {
	Delitem(s->text, DOH_END);
	return (SWIG_TOKEN_RSTRING);
      }
      break;

    default:
      return SWIG_TOKEN_ILLEGAL;
    }
  }
}
Example #6
0
static gpg_error_t
cmd_export (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  char *p;
  strlist_t list, sl;
  int use_data;
  int opt_secret;
  int opt_raw = 0;
  int opt_pkcs12 = 0;

  use_data = has_option (line, "--data");
  if (use_data)
    {
      /* We need to override any possible setting done by an OUTPUT command. */
      ctrl->create_pem = has_option (line, "--armor");
      ctrl->create_base64 = has_option (line, "--base64");
    }
  opt_secret = has_option (line, "--secret");
  if (opt_secret)
    {
      opt_raw = has_option (line, "--raw");
      opt_pkcs12 = has_option (line, "--pkcs12");
    }

  line = skip_options (line);

  /* Break the line down into an strlist_t. */
  list = NULL;
  for (p=line; *p; line = p)
    {
      while (*p && *p != ' ')
        p++;
      if (*p)
        *p++ = 0;
      if (*line)
        {
          sl = xtrymalloc (sizeof *sl + strlen (line));
          if (!sl)
            {
              free_strlist (list);
              return out_of_core ();
            }
          sl->flags = 0;
          strcpy_escaped_plus (sl->d, line);
          sl->next = list;
          list = sl;
        }
    }

  if (opt_secret)
    {
      if (!list || !*list->d)
        return set_error (GPG_ERR_NO_DATA, "No key given");
      if (list->next)
        return set_error (GPG_ERR_TOO_MANY, "Only one key allowed");
  }

  if (use_data)
    {
      estream_t stream;

      stream = es_fopencookie (ctx, "w", data_line_cookie_functions);
      if (!stream)
        {
          free_strlist (list);
          return set_error (GPG_ERR_ASS_GENERAL,
                            "error setting up a data stream");
        }
      if (opt_secret)
        gpgsm_p12_export (ctrl, list->d, stream,
                          opt_raw? 2 : opt_pkcs12 ? 0 : 1);
      else
        gpgsm_export (ctrl, list, stream);
      es_fclose (stream);
    }
  else
    {
      int fd = translate_sys2libc_fd (assuan_get_output_fd (ctx), 1);
      estream_t out_fp;

      if (fd == -1)
        {
          free_strlist (list);
          return set_error (GPG_ERR_ASS_NO_OUTPUT, NULL);
        }
      out_fp = es_fdopen_nc (fd, "w");
      if (!out_fp)
        {
          free_strlist (list);
          return set_error (gpg_err_code_from_syserror (), "fdopen() failed");
        }

      if (opt_secret)
        gpgsm_p12_export (ctrl, list->d, out_fp,
                          opt_raw? 2 : opt_pkcs12 ? 0 : 1);
      else
        gpgsm_export (ctrl, list, out_fp);
      es_fclose (out_fp);
    }

  free_strlist (list);
  /* Close and reset the fds. */
  close_message_fd (ctrl);
  assuan_close_input_fd (ctx);
  assuan_close_output_fd (ctx);
  return 0;
}
Example #7
0
int
efile_readdir(Efile_error* errInfo, /* Where to return error codes. */
	      char* name,           /* Name of directory to list */
	      EFILE_DIR_HANDLE* dir_handle, /* Handle of opened directory or NULL */
	      char* buffer,                 /* Buffer to put one filename in */ 
	      size_t *size)                 /* in-out size of buffer/size of filename excluding zero
					       termination in bytes*/
{
    HANDLE dir;			/* Handle to directory. */
    WCHAR wildcard[MAX_PATH];	/* Wildcard to search for. */
    WIN32_FIND_DATAW findData;	/* Data found by FindFirstFile() or FindNext(). */
    /* Alignment is not honored, this works on x86 because of alignment fixup by processor.
       Not perfect, but faster than alinging by hand (really) */
    WCHAR *wname = (WCHAR *) name;
    WCHAR *wbuffer = (WCHAR *) buffer;

    /*
     * First time we must setup everything.
     */

    if (*dir_handle == NULL) {
	int length = wcslen(wname);
	WCHAR* s;

	if (length+3 >= MAX_PATH) {
	    errno = ENAMETOOLONG;
	    return check_error(-1, errInfo);
	}

	wcscpy(wildcard, wname);
	s = wildcard+length-1;
	if (*s != L'/' && *s != L'\\')
	    *++s = L'\\';
	*++s = L'*';
	*++s = L'\0';
	DEBUGF(("Reading %ws\n", wildcard));
	dir = FindFirstFileW(wildcard, &findData);
	if (dir == INVALID_HANDLE_VALUE)
	    return set_error(errInfo);
	*dir_handle = (EFILE_DIR_HANDLE) dir;

	if (!IS_DOT_OR_DOTDOT(findData.cFileName)) {
	    wcscpy(wbuffer, findData.cFileName);
	    *size = wcslen(wbuffer)*2;
	    return 1;
	}
    }


    /*
     * Retrieve the name of the next file using the directory handle.
     */

    dir = (HANDLE) *dir_handle;

    for (;;) {
	if (FindNextFileW(dir, &findData)) {
	    if (IS_DOT_OR_DOTDOT(findData.cFileName))
		continue;
	    wcscpy(wbuffer, findData.cFileName);
	    *size = wcslen(wbuffer)*2;
	    return 1;
	}

	if (GetLastError() == ERROR_NO_MORE_FILES) {
	    FindClose(dir);
	    errInfo->posix_errno = errInfo->os_errno = 0;
	    return 0;
	}

	set_error(errInfo);
	FindClose(dir);
	return 0;
    }
}
Example #8
0
File: file.c Project: geek-li/wine
/* set the last error depending on errno */
void file_set_error(void)
{
    switch (errno)
    {
    case ETXTBSY:
    case EAGAIN:    set_error( STATUS_SHARING_VIOLATION ); break;
    case EBADF:     set_error( STATUS_INVALID_HANDLE ); break;
    case ENOSPC:    set_error( STATUS_DISK_FULL ); break;
    case EACCES:
    case ESRCH:
    case EROFS:
    case EPERM:     set_error( STATUS_ACCESS_DENIED ); break;
    case EBUSY:     set_error( STATUS_FILE_LOCK_CONFLICT ); break;
    case ENOENT:    set_error( STATUS_NO_SUCH_FILE ); break;
    case EISDIR:    set_error( STATUS_FILE_IS_A_DIRECTORY ); break;
    case ENFILE:
    case EMFILE:    set_error( STATUS_TOO_MANY_OPENED_FILES ); break;
    case EEXIST:    set_error( STATUS_OBJECT_NAME_COLLISION ); break;
    case EINVAL:    set_error( STATUS_INVALID_PARAMETER ); break;
    case ESPIPE:    set_error( STATUS_ILLEGAL_FUNCTION ); break;
    case ENOTEMPTY: set_error( STATUS_DIRECTORY_NOT_EMPTY ); break;
    case EIO:       set_error( STATUS_ACCESS_VIOLATION ); break;
    case ENOTDIR:   set_error( STATUS_NOT_A_DIRECTORY ); break;
    case EFBIG:     set_error( STATUS_SECTION_TOO_BIG ); break;
    case ENODEV:    set_error( STATUS_NO_SUCH_DEVICE ); break;
    case ENXIO:     set_error( STATUS_NO_SUCH_DEVICE ); break;
#ifdef EOVERFLOW
    case EOVERFLOW: set_error( STATUS_INVALID_PARAMETER ); break;
#endif
    default:
        perror("wineserver: file_set_error() can't map error");
        set_error( STATUS_UNSUCCESSFUL );
        break;
    }
}
_ERR_CODE move_extents_random_waypoints(MatchingInstance * m, uint32_t iteration_number, movement_restriction restriction, void (*instance_solver)(MatchingInstance *,bitmatrix *), char * output_dir, SPACE_TYPE velocity, SPACE_TYPE acceleration)
{
    uint64_t i, j, g;
    uint32_t r;
    uint_fast16_t k;
    waypoint * waypoints;
    FILE * fp;
    SPACE_TYPE temp;
    uint64_t extent_width;
    char filename[MAX_FILE_PATH_LENGHT];
    extent * ext;
    uint64_t waypoint_count = 0;

   //Allocating waypoints
    switch(restriction)
    {
        case RESTR_NONE: //move all extents
            waypoint_count = m->subscriptions+m->updates;
            ext = m->extents;
            break;
        case RESTR_LOCK_SUBSCRIPTION:
            waypoint_count = m->updates;
            ext = &(m->extents[m->subscriptions]);
            break;
        case RESTR_LOCK_UPDATES:
            waypoint_count = m->subscriptions;
            ext = m->extents;
            break;
        default:
            return set_error(err_invalid_input, __FILE__,__FUNCTION__,__LINE__);
    }
    //Alloc waypoints data structure
    waypoints = (waypoint*) malloc(sizeof(waypoint)*(waypoint_count));
    if(waypoints == NULL)
        return set_error(err_alloc,__FILE__,__FUNCTION__,__LINE__);

    for(i=0; i<waypoint_count; i++)
    {
        waypoints[i].destination = (SPACE_TYPE*) malloc(sizeof(SPACE_TYPE) * m->dimensions);
        if(waypoints[i].destination == NULL)
        {
            free(waypoints);
            return set_error(err_alloc, __FILE__,__FUNCTION__,__LINE__);
        }
        waypoints[i].reached = true;
    }
    for(r = 1; r < iteration_number; r++)
    {
        //Move extents and set dirty bit if moved
        bool reached;
        for(j=0; j<waypoint_count; j++)
        {
            if(waypoints[j].reached)
            {
                //Generate new random waypoint
                if(rand() % 10 == 0)
                {
                //printf("%"PRIu64" starts moving again on iteration %"PRIu64"\n", ext[j].id, i);
                    for(k=0; k<m->dimensions; k++)
                    {
                        waypoints[j].destination[k] = BIGRANDOM(SPACE_TYPE_MIN, SPACE_TYPE_MAX);
                    }
                    waypoints[j].reached = false;
                }
                else
                {
                    continue;
                }
            }
            reached = true;
            for(k=0; k<m->dimensions; k++)
            {
                if(ext[j].bounds[k].lower != waypoints[j].destination[k])
                {
                    reached = false;
                    if(ext[j].bounds[k].lower > waypoints[j].destination[k])
                    {
                        extent_width = ext[j].bounds[k].upper - ext[j].bounds[k].lower;
                        temp = ext[j].bounds[k].lower;
                        ext[j].bounds[k].lower -= velocity;
                        if(temp < ext[j].bounds[k].lower)
                        {
                            //Overflow detected
                            ext[j].bounds[k].lower = SPACE_TYPE_MIN;
                            ext[j].bounds[k].upper = SPACE_TYPE_MIN + extent_width;
                        }
                        else
                        {
                            //Move upper bound too, this operation can't overflow
                           ext[j].bounds[k].upper -= velocity;
                        }

                        if(ext[j].bounds[k].lower <= waypoints[j].destination[k])
                        {
                            //If the extent overtook the destination, move it back
                            ext[j].bounds[k].upper += (waypoints[j].destination[k] - ext[j].bounds[k].lower);
                            ext[j].bounds[k].lower = waypoints[j].destination[k];
                        }
                    }
                    else
                    {
                        extent_width = ext[j].bounds[k].upper - ext[j].bounds[k].lower;
                        temp = ext[j].bounds[k].upper;
                        ext[j].bounds[k].upper += velocity;
                        if(temp > ext[j].bounds[k].lower)
                        {
                            //Overflow detected
                            ext[j].bounds[k].upper = SPACE_TYPE_MAX;
                            ext[j].bounds[k].lower = SPACE_TYPE_MAX - extent_width;
                        }
                        else
                        { //Move the lower bound too, this operation can't overflow
                           ext[j].bounds[k].lower += velocity;
                        }

                        if(ext[j].bounds[k].lower > waypoints[j].destination[k])
                        {
                             //If the extent overtook the destination, move it back
                            ext[j].bounds[k].upper -= (ext[j].bounds[k].lower - waypoints[j].destination[k]);
                            ext[j].bounds[k].lower = waypoints[j].destination[k];
                        }
                    }
                    /*Another possible way to handle the overflow of the extent out of the bound SPACE_TYPE_MIN AND SPACE_TYPE_MAX
                    if(ext[j].bounds[k].upper < ext[j].bounds[k].lower)
                    {//One possible solution: Swap them
                        temp = ext[j].bounds[k].upper;
                        ext[j].bounds[k].upper = ext[j].bounds[k].lower;
                        ext[j].bounds[k].lower = temp;
                    }*/
                }
            }
            ext[j].dirtyBit = true;
            if(reached == true)
            {
                //printf("Extent %"PRIu64" reached its waypoint on iteration: %"PRIu64".\n", ext[j].id, i);
                waypoints[j].reached = true;
            }
        }

        //Solve this instance
        reset_whole_bit_mat(*(m->matching_result), m->updates, m->subscriptions);
        (*instance_solver)(m, m->matching_result);

        //Print output file as changelog (call function)

        sprintf(filename, "%s/"INPUT_FILE_NAME,output_dir, r);
        fp = fopen(filename,"w");
        if(fp == NULL)
            return set_error(err_file, __FILE__,__FUNCTION__, __LINE__);
            bool firstextent = true;
            switch (restriction)
            {
                case RESTR_NONE:

                //Note that this case don't have a break; as we want to fall in the cases below

                case RESTR_LOCK_UPDATES:
                for(g=0; g<m->subscriptions; g++)
                {
                    if(m->extents[g].dirtyBit)
                    {
                        if(firstextent)
                        {//Print header
                        fprintf(fp, "#Subscriptions <id> <D1 edges> [<D2 edges>]...\ns\n");
                        firstextent=false;
                        }
                        m->extents[g].dirtyBit = false;
                        fprintf(fp, "%"PRIu64" ", m->extents[g].id);
                        for(k=0; k<m->dimensions; k++)
                        {
                            fprintf(fp, " %"PRId64" ""%"PRId64, m->extents[g].bounds[k].lower, m->extents[g].bounds[k].upper);
                        }
                        fputs("\n", fp);
                    }
                }
                if(restriction == RESTR_LOCK_UPDATES)
                    break;
                //else if it was RESTR_NONE print update extents too.

                case RESTR_LOCK_SUBSCRIPTION:
                    firstextent=true;
                for(g=m->subscriptions; g<m->extent_number; g++)
                {
                    if(m->extents[g].dirtyBit)
                    {
                    if(firstextent)
                    {   //Print header
                        fprintf(fp, "#Updates <id> <D1 edges> [<D2 edges>]...\nu\n");
                        firstextent=false;
                    }
                        m->extents[g].dirtyBit = false;
                        fprintf(fp, "%"PRIu64, m->extents[g].id);
                        for(k=0; k<m->dimensions; k++)
                        {
                            fprintf(fp, " %"PRId64" %"PRId64, m->extents[g].bounds[k].lower, m->extents[g].bounds[k].upper);
                        }
                        fputs("\n", fp);
                    }
                }
                break;
            }
        fclose(fp);

        //print bitmatrix result
        snprintf(filename, MAX_FILE_PATH_LENGHT, "%s/"OUTPUT_FILE_NAME, output_dir, r); //N.B. OUTPUT_FILE_NAME cointains a placeholder
        print_bit_matrix(*(m->matching_result), filename, true, m->updates, m->subscriptions);

    }//end for
    free(waypoints);
    return err_none;
}
Example #10
0
File: ptrace.c Project: r6144/wine
/* read data from a process memory space */
int read_process_memory( struct process *process, client_ptr_t ptr, data_size_t size, char *dest )
{
    struct thread *thread = get_ptrace_thread( process );
    unsigned int first_offset, last_offset, len;
    long data, *addr;

    if (!thread) return 0;

    if ((unsigned long)ptr != ptr)
    {
        set_error( STATUS_ACCESS_DENIED );
        return 0;
    }

    first_offset = ptr % sizeof(long);
    last_offset = (size + first_offset) % sizeof(long);
    if (!last_offset) last_offset = sizeof(long);

    addr = (long *)(unsigned long)(ptr - first_offset);
    len = (size + first_offset + sizeof(long) - 1) / sizeof(long);

    if (suspend_for_ptrace( thread ))
    {
        if (len > 3)  /* /proc/pid/mem should be faster for large sizes */
        {
            char procmem[24];
            int fd;

            sprintf( procmem, "/proc/%u/mem", process->unix_pid );
            if ((fd = open( procmem, O_RDONLY )) != -1)
            {
                ssize_t ret = pread( fd, dest, size, ptr );
                close( fd );
                if (ret == size)
                {
                    len = 0;
                    goto done;
                }
            }
        }

        if (len > 1)
        {
            if (read_thread_long( thread, addr++, &data ) == -1) goto done;
            memcpy( dest, (char *)&data + first_offset, sizeof(long) - first_offset );
            dest += sizeof(long) - first_offset;
            first_offset = 0;
            len--;
        }

        while (len > 1)
        {
            if (read_thread_long( thread, addr++, &data ) == -1) goto done;
            memcpy( dest, &data, sizeof(long) );
            dest += sizeof(long);
            len--;
        }

        if (read_thread_long( thread, addr++, &data ) == -1) goto done;
        memcpy( dest, (char *)&data + first_offset, last_offset - first_offset );
        len--;

    done:
        resume_after_ptrace( thread );
    }
    return !len;
}
Example #11
0
File: ptrace.c Project: r6144/wine
/* write data to a process memory space */
int write_process_memory( struct process *process, client_ptr_t ptr, data_size_t size, const char *src )
{
    struct thread *thread = get_ptrace_thread( process );
    int ret = 0;
    long data = 0;
    data_size_t len;
    long *addr;
    unsigned long first_mask, first_offset, last_mask, last_offset;

    if (!thread) return 0;

    if ((unsigned long)ptr != ptr)
    {
        set_error( STATUS_ACCESS_DENIED );
        return 0;
    }

    /* compute the mask for the first long */
    first_mask = ~0;
    first_offset = ptr % sizeof(long);
    memset( &first_mask, 0, first_offset );

    /* compute the mask for the last long */
    last_offset = (size + first_offset) % sizeof(long);
    if (!last_offset) last_offset = sizeof(long);
    last_mask = 0;
    memset( &last_mask, 0xff, last_offset );

    addr = (long *)(unsigned long)(ptr - first_offset);
    len = (size + first_offset + sizeof(long) - 1) / sizeof(long);

    if (suspend_for_ptrace( thread ))
    {
        if (!check_process_write_access( thread, addr, len ))
        {
            set_error( STATUS_ACCESS_DENIED );
            goto done;
        }
        /* first word is special */
        if (len > 1)
        {
            memcpy( (char *)&data + first_offset, src, sizeof(long) - first_offset );
            src += sizeof(long) - first_offset;
            if (write_thread_long( thread, addr++, data, first_mask ) == -1) goto done;
            first_offset = 0;
            len--;
        }
        else last_mask &= first_mask;

        while (len > 1)
        {
            memcpy( &data, src, sizeof(long) );
            src += sizeof(long);
            if (write_thread_long( thread, addr++, data, ~0ul ) == -1) goto done;
            len--;
        }

        /* last word is special too */
        memcpy( (char *)&data + first_offset, src, last_offset - first_offset );
        if (write_thread_long( thread, addr, data, last_mask ) == -1) goto done;
        ret = 1;

    done:
        resume_after_ptrace( thread );
    }
    return ret;
}
Example #12
0
/* Adds a tap with the file/qid of the underlying device for the requested FD.
 * The FD must be a chan, and the device must support the filter requested.
 *
 * Returns -1 or some other device-specific non-zero number on failure, 0 on
 * success. */
int add_fd_tap(struct proc *p, struct fd_tap_req *tap_req)
{
	struct fd_table *fdt = &p->open_files;
	struct fd_tap *tap;
	int ret = 0;
	struct chan *chan;
	int fd = tap_req->fd;

	if (fd < 0) {
		set_errno(EBADF);
		return -1;
	}
	tap = kzmalloc(sizeof(struct fd_tap), MEM_WAIT);
	tap->proc = p;
	tap->fd = fd;
	tap->filter = tap_req->filter;
	tap->ev_q = tap_req->ev_q;
	tap->ev_id = tap_req->ev_id;
	tap->data = tap_req->data;

	spin_lock(&fdt->lock);
	if (fd >= fdt->max_fdset) {
		set_errno(ENFILE);
		goto out_with_lock;
	}
	if (!GET_BITMASK_BIT(fdt->open_fds->fds_bits, fd)) {
		set_errno(EBADF);
		goto out_with_lock;
	}
	if (!fdt->fd[fd].fd_chan) {
		set_error(EINVAL, "Can't tap a VFS file");
		goto out_with_lock;
	}
	chan = fdt->fd[fd].fd_chan;
	if (fdt->fd[fd].fd_tap) {
		set_error(EBUSY, "FD %d already has a tap", fd);
		goto out_with_lock;
	}
	if (!devtab[chan->type].tapfd) {
		set_error(ENOSYS, "Device %s does not handle taps",
				  devtab[chan->type].name);
		goto out_with_lock;
	}
	/* need to keep chan alive for our call to the device.  someone else
	 * could come in and close the FD and the chan, once we unlock */
	chan_incref(chan);
	tap->chan = chan;
	/* One for the FD table, one for us to keep the removal of *this* tap from
	 * happening until we've attempted to register with the device. */
	kref_init(&tap->kref, tap_full_release, 2);
	fdt->fd[fd].fd_tap = tap;
	/* As soon as we unlock, another thread can come in and remove our old tap
	 * from the table and decref it.  Our ref keeps us from removing it yet,
	 * as well as keeps the memory safe.  However, a new tap can be installed
	 * and registered with the device before we even attempt to register.  The
	 * devices should be able to handle multiple, distinct taps, even if they
	 * happen to have the same {proc, fd} tuple. */
	spin_unlock(&fdt->lock);
	/* For refcnting fans, the tap ref is weak/uncounted.  We'll protect the
	 * memory and call the device when tap is being released. */
	ret = devtab[chan->type].tapfd(chan, tap, FDTAP_CMD_ADD);
	if (ret) {
		/* we failed, so we need to make sure *our* tap is removed.  We haven't
		 * decreffed, so we know our tap pointer is unique. */
		spin_lock(&fdt->lock);
		if (fdt->fd[fd].fd_tap == tap) {
			fdt->fd[fd].fd_tap = 0;
			/* normally we can't decref a tap while holding a lock, but we
			 * know we have another reference so this won't trigger a release */
			kref_put(&tap->kref);
		}
		spin_unlock(&fdt->lock);
		/* Regardless of whether someone else removed it or not, *we* are the
		 * only ones that know that registration failed and that we shouldn't
		 * remove it.  Since we still hold a ref, we can change the release
		 * method to skip the device dereg. */
		tap->kref.release = tap_min_release;
	}
	kref_put(&tap->kref);
	return ret;
out_with_lock:
	spin_unlock(&fdt->lock);
	kfree(tap);
	return -1;
}
Example #13
0
static void
request_join(InfTestGtkBrowserWindow* test,
             const gchar* user_name)
{
  InfcUserRequest* request;
  InfAdoptedStateVector* v;
  GError* error;
  GtkTextBuffer* buffer;
  GtkTextMark* mark;
  GtkTextIter iter;
  GParameter params[3] = {
    { "name", { 0 } },
    { "vector", { 0 } },
    { "caret-position", { 0 } }
  };

  g_value_init(&params[0].value, G_TYPE_STRING);
  g_value_init(&params[1].value, INF_ADOPTED_TYPE_STATE_VECTOR);
  g_value_init(&params[2].value, G_TYPE_UINT);

  g_value_set_static_string(&params[0].value, user_name);

  /* Use current state vector. Infinote should already do this. */
  v = inf_adopted_state_vector_copy(
    inf_adopted_algorithm_get_current(
      inf_adopted_session_get_algorithm(
        INF_ADOPTED_SESSION(infc_session_proxy_get_session(test->proxy))
      )
    )
  );

  g_value_take_boxed(&params[1].value, v);

  buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(test->textview));
  mark = gtk_text_buffer_get_insert(buffer);
  gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
  g_value_set_uint(&params[2].value, gtk_text_iter_get_offset(&iter));

  error = NULL;
  request = infc_session_proxy_join_user(test->proxy, params, 3, &error);

  /* TODO: Free GValues? */

  if(request == NULL)
  {
    set_error(test, "Failed to request user join", error->message);
  }
  else
  {
    g_signal_connect_after(
      G_OBJECT(request),
      "failed",
      G_CALLBACK(on_join_failed),
      test
    );

    g_signal_connect_after(
      G_OBJECT(request),
      "finished",
      G_CALLBACK(on_join_finished),
      test
    );
  }
}
Example #14
0
int
hstcpcli::response_recv(size_t& num_flds_r)
{
  if (error_code < 0) {
    return error_code;
  }
  clear_error();
  if (num_req_bufd > 0 || num_req_sent == 0 || num_req_rcvd > 0 ||
    response_end_offset != 0) {
    close();
    return set_error(-1, "response_recv: protocol out of sync");
  }
  cur_row_offset = 0;
  num_flds_r = num_flds = 0;
  if (fd.get() < 0) {
    return set_error(-1, "read: closed");
  }
  size_t offset = 0;
  while (true) {
    const char *const lbegin = readbuf.begin() + offset;
    const char *const lend = readbuf.end();
    if (lbegin < lend)
    {
      const char *const nl = memchr_char(lbegin, '\n', lend - lbegin);
      if (nl != 0) {
        offset += (nl + 1) - lbegin;
        break;
      }
      offset += lend - lbegin;
    }
    if (read_more() <= 0) {
      close();
      error_code = -1;
      return error_code;
    }
  }
  response_end_offset = offset;
  --num_req_sent;
  ++num_req_rcvd;
  char *start = readbuf.begin();
  char *const finish = start + response_end_offset - 1;
  const size_t resp_code = read_ui32(start, finish);
  skip_one(start, finish);
  num_flds_r = num_flds = read_ui32(start, finish);
  if (resp_code != 0) {
    skip_one(start, finish);
    char *const err_begin = start;
    read_token(start, finish);
    char *const err_end = start;
    String e = String(err_begin, err_end - err_begin, &my_charset_bin);
    if (!e.length()) {
      e = String("unknown_error", &my_charset_bin);
    }
    return set_error(resp_code, e);
  }
  cur_row_offset = start - readbuf.begin();
  DBG(fprintf(stderr, "[%s] ro=%zu eol=%zu\n",
    String(readbuf.begin(), readbuf.begin() + response_end_offset)
      .c_str(),
    cur_row_offset, response_end_offset));
  DBG(fprintf(stderr, "RES 0\n"));
  if (flds.max_element < num_flds)
  {
    if (allocate_dynamic(&flds, num_flds))
      return set_error(-1, "out of memory");
  }
  flds.elements = num_flds;
  return 0;
}
Example #15
0
void FindReplaceBar::_replace_all() {

	text_edit->disconnect("text_changed", this, "_editor_text_changed");
	// line as x so it gets priority in comparison, column as y
	Point2i orig_cursor(text_edit->cursor_get_line(), text_edit->cursor_get_column());
	Point2i prev_match = Point2(-1, -1);

	bool selection_enabled = text_edit->is_selection_active();
	Point2i selection_begin, selection_end;
	if (selection_enabled) {
		selection_begin = Point2i(text_edit->get_selection_from_line(), text_edit->get_selection_from_column());
		selection_end = Point2i(text_edit->get_selection_to_line(), text_edit->get_selection_to_column());
	}

	int vsval = text_edit->get_v_scroll();

	text_edit->cursor_set_line(0);
	text_edit->cursor_set_column(0);

	String replace_text = get_replace_text();
	int search_text_len = get_search_text().length();

	int rc = 0;

	replace_all_mode = true;

	text_edit->begin_complex_operation();

	if (search_current()) {
		do {
			// replace area
			Point2i match_from(result_line, result_col);
			Point2i match_to(result_line, result_col + search_text_len);

			if (match_from < prev_match) {
				break; // done
			}

			prev_match = Point2i(result_line, result_col + replace_text.length());

			text_edit->unfold_line(result_line);
			text_edit->select(result_line, result_col, result_line, match_to.y);

			if (selection_enabled && is_selection_only()) {
				if (match_from < selection_begin || match_to > selection_end) {
					continue;
				}

				// replace but adjust selection bounds
				text_edit->insert_text_at_cursor(replace_text);
				if (match_to.x == selection_end.x) {
					selection_end.y += replace_text.length() - search_text_len;
				}

			} else {
				// just replace
				text_edit->insert_text_at_cursor(replace_text);
			}

			rc++;
		} while (search_next());
	}

	text_edit->end_complex_operation();

	replace_all_mode = false;

	// restore editor state (selection, cursor, scroll)
	text_edit->cursor_set_line(orig_cursor.x);
	text_edit->cursor_set_column(orig_cursor.y);

	if (selection_enabled && is_selection_only()) {
		// reselect
		text_edit->select(selection_begin.x, selection_begin.y, selection_end.x, selection_end.y);
	} else {
		text_edit->deselect();
	}

	text_edit->set_v_scroll(vsval);
	set_error(vformat(TTR("Replaced %d occurrence(s)."), rc));

	text_edit->call_deferred("connect", "text_changed", this, "_editor_text_changed");
}
Example #16
0
config_info::config_info( int argc, char **argv )
{
  int dn=-1, cn=-1, pn=-1, lp=-1;

  is_version=0;
  num_clients=1;
  protocol_lib_path=NULL;
  client_lib_path=NULL;
  payload_lib_path=NULL;
  client_min=client_max=client_inc=client_time=0;
  payload_min=payload_max=payload_inc=payload_time=0;
  protocol_dest_port=0;
  protocol_dest_address=NULL;
  installed=0;
  error_string=NULL;

  if (argc<3)
    {
      if (argv[1] && strcmp( argv[1], "-v" ))
	{
	  set_error( "Not enough parameters specified" );
	  return;
	}
    }
  for (int cnt=1;cnt<argc;cnt++)
    {
      int result;
      if (argv[cnt][0]!='-' && argv[cnt][0]!='/')
	{
	  set_error( "Parameter specified that does not start with - or /" );
	  return;
	}
      switch (argv[cnt][1])
	{
	case 'd':
	  result=parse_protocol_data( cnt, argc, argv, &dn );
	  if (result) return;
	  cnt+=1;
	  continue;
	case 'c':
	  result=parse_client_data( cnt, argc, argv, &cn );
	  if (result) return;
	  cnt+=1;
	  continue;
	case 'p':
	  result=parse_payload_data( cnt, argc, argv, &pn );
	  if (result) return;
	  cnt+=1;
	  continue;
	case 'n': // num clients
	  if (!argv[cnt+1])
	    {
	      set_error( "Parameter specified without value" );
	      return;
	    }
	  num_clients=atol( argv[cnt+1] );
	  cnt+=1;
	  continue;
	case 'L': // lib path
	  if (!argv[cnt+1])
	    {
	      set_error( "Parameter specified without value" );
	      return;
	    }
	  lp=cnt+1;
	  cnt+=1;
	  continue;
	case 'v': // version
	  char buf[1024];
	  snprintf( buf, 1024, "%s version %s", PRODUCT_NAME, PRODUCT_VERSION );
	  set_error( buf );
	  is_version=1;
	  return;
	default:
	  set_error( "Unknown parameter specified" );
	  return;
	}
    }
  // Logic checking
  if (dn==-1 || cn==-1 || pn==-1)
    {
      set_error( "You must specify -cn and -dn and -pn" );
      return;
    }
  if (num_clients<1)
    {
      set_error( "You must specify at least one client" );
      return;
    }
  char err_msg[1024];
  
  protocol_lib_path=set_library_path( argc, argv, dn, lp, "protocol", err_msg, 1024 );
  if (!protocol_lib_path) 
    {
      set_error( err_msg );
      return;
    }
  client_lib_path=set_library_path( argc, argv, cn, lp, "client", err_msg, 1024 );
  if (!client_lib_path) 
    {
      set_error( err_msg );
      return;
    }
  payload_lib_path=set_library_path( argc, argv, pn, lp, "payload", err_msg, 1024 );
  if (!payload_lib_path) 
    {
      set_error( err_msg );
      return;
    }
  if (protocol_dest_port<=0)
    {
      set_error( "Protocol destination port must be defined" );
      return;
    }
  if (!protocol_dest_address)
    {
      set_error( "Protocol destination address must be defined" );
      return;
    }
  installed=1;
}
Example #17
0
static gpg_error_t
cmd_getinfo (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  int rc = 0;

  if (!strcmp (line, "version"))
    {
      const char *s = VERSION;
      rc = assuan_send_data (ctx, s, strlen (s));
    }
  else if (!strcmp (line, "pid"))
    {
      char numbuf[50];

      snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
      rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
    }
  else if (!strcmp (line, "agent-check"))
    {
      rc = gpgsm_agent_send_nop (ctrl);
    }
  else if (!strncmp (line, "cmd_has_option", 14)
           && (line[14] == ' ' || line[14] == '\t' || !line[14]))
    {
      char *cmd, *cmdopt;
      line += 14;
      while (*line == ' ' || *line == '\t')
        line++;
      if (!*line)
        rc = gpg_error (GPG_ERR_MISSING_VALUE);
      else
        {
          cmd = line;
          while (*line && (*line != ' ' && *line != '\t'))
            line++;
          if (!*line)
            rc = gpg_error (GPG_ERR_MISSING_VALUE);
          else
            {
              *line++ = 0;
              while (*line == ' ' || *line == '\t')
                line++;
              if (!*line)
                rc = gpg_error (GPG_ERR_MISSING_VALUE);
              else
                {
                  cmdopt = line;
                  if (!command_has_option (cmd, cmdopt))
                    rc = gpg_error (GPG_ERR_GENERAL);
                }
            }
        }
    }
  else if (!strcmp (line, "offline"))
    {
      rc = ctrl->offline? 0 : gpg_error (GPG_ERR_GENERAL);
    }
  else
    rc = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");

  return rc;
}
Example #18
0
ZIP_EXTERN struct zip *
zip_open(const char *fn, int flags, int *zep)
{
	FILE *fp;
	struct zip *za;
	struct zip_cdir *cdir;
	int i;
	off_t len;

	switch (_zip_file_exists(fn, flags, zep)) {
	case -1:
		return NULL;
	case 0:
		return _zip_allocate_new(fn, zep);
	default:
		break;
	}

	if ((fp=fopen(fn, "rb")) == NULL) {
		set_error(zep, NULL, ZIP_ER_OPEN);
		return NULL;
	}

	__android_log_print(ANDROID_LOG_VERBOSE, "ZIP", "FILE OPENED");


	fseeko(fp, 0, SEEK_END);
	len = ftello(fp);

	/* treat empty files as empty archives */
	if (len == 0) {
		if ((za=_zip_allocate_new(fn, zep)) == NULL)
			fclose(fp);
		else
			za->zp = fp;
		return za;
	}

	__android_log_print(ANDROID_LOG_VERBOSE, "ZIP", "SCANNING");


	cdir = _zip_find_central_dir(fp, flags, zep, len);
	if (cdir == NULL) {
		fclose(fp);
		return NULL;
	}

	__android_log_print(ANDROID_LOG_VERBOSE, "ZIP", "DIR FOUND");


	if ((za=_zip_allocate_new(fn, zep)) == NULL) {
		_zip_cdir_free(cdir);
		fclose(fp);
		return NULL;
	}

	za->cdir = cdir;
	za->zp = fp;

	__android_log_print(ANDROID_LOG_VERBOSE, "ZIP", "ALLOCING ENTRIES");


	if ((za->entry=(struct zip_entry *)malloc(sizeof(*(za->entry))
											  * cdir->nentry)) == NULL) {
		set_error(zep, NULL, ZIP_ER_MEMORY);
		_zip_free(za);
		return NULL;
	}

	za->nentry_alloc = cdir->nentry;

	__android_log_print(ANDROID_LOG_VERBOSE, "ZIP", "FILLING ENTRIES");

	for (i=0; i<cdir->nentry; i++)
		_zip_entry_new2(za);

	__android_log_print(ANDROID_LOG_VERBOSE, "ZIP", "CHECK TORRENTZIP");

	_zip_check_torrentzip(za);
	za->ch_flags = za->flags;

	__android_log_print(ANDROID_LOG_VERBOSE, "ZIP", "DONE");

	return za;
}
Example #19
0
static int
do_listkeys (assuan_context_t ctx, char *line, int mode)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  estream_t fp;
  char *p;
  strlist_t list, sl;
  unsigned int listmode;
  gpg_error_t err;

  /* Break the line down into an strlist. */
  list = NULL;
  for (p=line; *p; line = p)
    {
      while (*p && *p != ' ')
        p++;
      if (*p)
        *p++ = 0;
      if (*line)
        {
          sl = xtrymalloc (sizeof *sl + strlen (line));
          if (!sl)
            {
              free_strlist (list);
              return out_of_core ();
            }
          sl->flags = 0;
          strcpy_escaped_plus (sl->d, line);
          sl->next = list;
          list = sl;
        }
    }

  if (ctrl->server_local->list_to_output)
    {
      int outfd = translate_sys2libc_fd (assuan_get_output_fd (ctx), 1);

      if ( outfd == -1 )
        return set_error (GPG_ERR_ASS_NO_OUTPUT, NULL);
      fp = es_fdopen_nc (outfd, "w");
      if (!fp)
        return set_error (gpg_err_code_from_syserror (), "es_fdopen() failed");
    }
  else
    {
      fp = es_fopencookie (ctx, "w", data_line_cookie_functions);
      if (!fp)
        return set_error (GPG_ERR_ASS_GENERAL,
                          "error setting up a data stream");
    }

  ctrl->with_colons = 1;
  listmode = mode;
  if (ctrl->server_local->list_internal)
    listmode |= (1<<6);
  if (ctrl->server_local->list_external)
    listmode |= (1<<7);
  err = gpgsm_list_keys (assuan_get_pointer (ctx), list, fp, listmode);
  free_strlist (list);
  es_fclose (fp);
  if (ctrl->server_local->list_to_output)
    assuan_close_output_fd (ctx);
  return err;
}
Example #20
0
int connect_to(int fd, struct addrinfo *ai, double timeout, char *tfo, char *msg, int msg_len, char *msg_accepted)
{
	int rc = -1;
	struct timeval to;
	fd_set wfds;

	/* make fd nonblocking */
	if (set_fd_nonblocking(fd) == -1)
		return RC_INVAL;

	/* wait for connection */
	FD_ZERO(&wfds);
	FD_SET(fd, &wfds);

	to.tv_sec  = (long)(timeout / 1000.0);
	to.tv_usec = (long)(timeout * 1000.0) % 1000000;

	/* connect to peer */
#ifdef TCP_TFO
	if (tfo && *tfo)
	{
		rc = sendto(fd, msg, msg_len, MSG_FASTOPEN, ai -> ai_addr, ai -> ai_addrlen);
		
		if(rc == msg_len)
			*msg_accepted = 1;
		if(errno == 0)
			return RC_OK;
		if(errno == ENOTSUP)
		{
			printf(gettext("TCP TFO Not Supported. Please check if \"/proc/sys/net/ipv4/tcp_fastopen\" is 1. Disabling TFO for now.\n"));
			*tfo = 0;
			goto old_connect;
		}
	}
			
	else
#else
	(void)tfo;
	(void)msg;
	(void)msg_len;
	(void)msg_accepted;
#endif
	{
		int rc = -1;

old_connect:
		rc = connect(fd, ai -> ai_addr, ai -> ai_addrlen);

		if (rc == 0)
		{
			/* connection made, return */
			return RC_OK;
		}

		if (rc == -1)
		{
			/* problem connecting */
			if (errno != EINPROGRESS)
			{
				set_error(gettext("problem connecting to host: %s"), strerror(errno));
				return RC_INVAL;
			}
		}
	}

	if (stop)
		return RC_CTRLC;

	/* wait for connection */
	rc = select(fd + 1, NULL, &wfds, NULL, &to);
	if (rc == 0)
	{
		set_error(gettext("connect time out"));
		return RC_TIMEOUT;	/* timeout */
	}
	else if (rc == -1)
	{
		if (errno == EINTR)
			return RC_CTRLC;/* ^C pressed */

		set_error(gettext("select() failed: %s"), strerror(errno));

		return RC_INVAL;	/* error */
	}
	else
	{
		int optval=0;
		socklen_t optvallen = sizeof optval;

		/* see if the connect succeeded or failed */
		if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &optval, &optvallen) == -1)
		{
			set_error(gettext("getsockopt failed (%s)"), strerror(errno));
			return RC_INVAL;
		}

		/* no error? */
		if (optval == 0)
			return RC_OK;

		/* don't ask */
		errno = optval;
	}

	set_error(gettext("could not connect (%s)"), strerror(errno));

	return RC_INVAL;
}
Example #21
0
int
efile_openfile(Efile_error* errInfo,		/* Where to return error codes. */
	       char* name,			/* Name of directory to open. */
	       int flags,			/* Flags to use for opening. */
	       int* pfd,			/* Where to store the file descriptor. */
	       Sint64* pSize)			/* Where to store the size of the file. */
{
    BY_HANDLE_FILE_INFORMATION fileInfo; /* File information from a handle. */
    HANDLE fd;			/* Handle to open file. */
    DWORD access;		/* Access mode: GENERIC_READ, GENERIC_WRITE. */
    DWORD crFlags;
    WCHAR *wname = (WCHAR *) name;

    switch (flags & (EFILE_MODE_READ|EFILE_MODE_WRITE)) {
    case EFILE_MODE_READ:
	access = GENERIC_READ;
	crFlags = OPEN_EXISTING;
	break;
    case EFILE_MODE_WRITE:
	access = GENERIC_WRITE;
	crFlags = CREATE_ALWAYS;
	break;
    case EFILE_MODE_READ_WRITE:
	access = GENERIC_READ|GENERIC_WRITE;
	crFlags = OPEN_ALWAYS;
	break;
    default:
	errno = EINVAL;
	check_error(-1, errInfo);
	return 0;
    }

    if (flags & EFILE_MODE_APPEND) {
	crFlags = OPEN_ALWAYS;
    }
    if (flags & EFILE_MODE_EXCL) {
	crFlags = CREATE_NEW;
    }
    fd = CreateFileW(wname, access,
		    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
		    NULL, crFlags, FILE_ATTRIBUTE_NORMAL, NULL);

    /*
     * Check for errors.
     */

    if (fd == INVALID_HANDLE_VALUE) {
	DWORD attr;

	set_error(errInfo);

	/*
	 * If the error is EACESS, the reason could be that we tried to
	 * open a directory.  In that case, we'll change the error code
	 * to EISDIR.
	 */
	if (errInfo->posix_errno && 
	    (attr = GetFileAttributesW(wname)) != INVALID_FILE_ATTRIBUTES && 
	    (attr & FILE_ATTRIBUTE_DIRECTORY)) {
	    errInfo->posix_errno = EISDIR;
	}
	return 0;
    }

    /*
     * Get and return the length of the open file.
     */
       
    if (!GetFileInformationByHandle(fd, &fileInfo))
	return set_error(errInfo);
    *pfd = (int) fd;
    if (pSize) {
	*pSize = (Sint64)
	    (((Uint64)fileInfo.nFileSizeHigh << 32) | 
	     (Uint64)fileInfo.nFileSizeLow);
    }
    return 1;
}
Example #22
0
int create_socket(struct sockaddr *bind_to, struct addrinfo *ai, int recv_buffer_size, int tx_buffer_size, int max_mtu, char use_no_delay, int priority, int tos)
{
	int fd = -1;

	/* create socket */
	fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
	if (fd == -1)
	{
		set_error(gettext("problem creating socket (%s)"), strerror(errno));
		return RC_INVAL;
	}

	/* go through a specific interface? */
	if (bind_to)
	{
		int set = 1;

		/* set reuse flags */
		if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &set, sizeof set) == -1)
		{
			set_error(gettext("error setting sockopt to interface (%s)"), strerror(errno));
			close(fd);
			return RC_INVAL;
		}

		if (bind(fd, bind_to, sizeof *bind_to) == -1)
		{
			set_error(gettext("error binding to interface (%s)"), strerror(errno));
			close(fd);
			return RC_INVAL;
		}
	}

	if (max_mtu >= 0)
	{
		if (setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, &max_mtu, sizeof max_mtu) == -1)
		{
			set_error(gettext("error setting MTU size (%s)"), strerror(errno));
			close(fd);
			return RC_INVAL;
		}
	}

	if (use_no_delay)
	{
		int rc = -1;

		if ((rc = set_no_delay(fd)) != 0)
			return rc;
	}

	if (tx_buffer_size > 0)
        {
		if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *)&tx_buffer_size, sizeof tx_buffer_size) == -1)
		{
			set_error(gettext("error setting transmit buffer size (%s)"), strerror(errno));
			close(fd);
			return RC_INVAL;
		}
	}

	if (recv_buffer_size > 0)
        {
		if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *)&recv_buffer_size, sizeof recv_buffer_size) == -1)
		{
			set_error(gettext("error setting receive buffer size (%s)"), strerror(errno));
			close(fd);
			return RC_INVAL;
		}
	}

#ifdef linux
	if (priority >= 0)
	{
		if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, (char *)&priority, sizeof priority) == -1)
		{
			set_error(gettext("error setting priority (%s)"), strerror(errno));
			close(fd);
			return RC_INVAL;
		}
	}
#endif

	if (tos >= 0)
	{
		if (setsockopt(fd, IPPROTO_IP, IP_TOS, (char *)&tos, sizeof tos) == -1)
		{
			set_error(gettext("failed to set TOS info"));
			close(fd);
			return RC_INVAL;
		}
	}

	return fd;
}
Example #23
0
/*
 * Process a by-address lease query.
 */
static int
process_lq_by_address(struct lq6_state *lq) {
	struct packet *packet = lq->packet;
	struct option_cache *oc;
	struct ipv6_pool *pool = NULL;
	struct data_string data;
	struct in6_addr addr;
	struct iasubopt *iaaddr = NULL;
	struct option_state *opt_state = NULL;
	u_int32_t lifetime;
	unsigned opt_cursor;
	int ret_val = 0;

	/*
	 * Get the IAADDR.
	 */
	oc = lookup_option(&dhcpv6_universe, lq->query_opts, D6O_IAADDR);
	if (oc == NULL) {
		if (!set_error(lq, STATUS_MalformedQuery,
			       "No OPTION_IAADDR.")) {
			log_error("process_lq_by_address: unable "
				  "to set MalformedQuery status code.");
			return 0;
		}
		return 1;
	}
	memset(&data, 0, sizeof(data));
	if (!evaluate_option_cache(&data, packet,
				   NULL, NULL,
				   lq->query_opts, NULL,
				   &global_scope, oc, MDL) ||
	    (data.len < IAADDR_OFFSET)) {
		log_error("process_lq_by_address: error evaluating IAADDR.");
		goto exit;
	}
	memcpy(&addr, data.data, sizeof(addr));
	data_string_forget(&data, MDL);

	/*
	 * Find the lease.
	 * Note the RFC 5007 says to use the link-address to find the link
	 * or the ia-aadr when it is :: but in any case the ia-addr has
	 * to be on the link, so we ignore the link-address here.
	 */
	if (find_ipv6_pool(&pool, D6O_IA_NA, &addr) != ISC_R_SUCCESS) {
		if (!set_error(lq, STATUS_NotConfigured,
			       "Address not in a pool.")) {
			log_error("process_lq_by_address: unable "
				  "to set NotConfigured status code.");
			goto exit;
		}
		ret_val = 1;
		goto exit;
	}
	if (iasubopt_hash_lookup(&iaaddr, pool->leases, &addr,
				 sizeof(addr), MDL) == 0) {
		ret_val = 1;
		goto exit;
	}
	if ((iaaddr == NULL) || (iaaddr->state != FTS_ACTIVE) ||
	    (iaaddr->ia == NULL) || (iaaddr->ia->iaid_duid.len <= 4)) {
		ret_val = 1;
		goto exit;
	}

	/*
	 * Build the client-data option (with client-id, ia-addr and clt-time).
	 */
	if (!option_state_allocate(&opt_state, MDL)) {
		log_error("process_lq_by_address: "
			  "no memory for option state.");
		goto exit;
	}

	data_string_copy(&data, &iaaddr->ia->iaid_duid, MDL);
	data.data += 4;
	data.len -= 4;
	if (!save_option_buffer(&dhcpv6_universe, opt_state,
				NULL, (unsigned char *)data.data, data.len,
				D6O_CLIENTID, 0)) {
		log_error("process_lq_by_address: error saving client ID.");
		goto exit;
	}
	data_string_forget(&data, MDL);

	data.len = IAADDR_OFFSET;
	if (!buffer_allocate(&data.buffer, data.len, MDL)) {
		log_error("process_lq_by_address: no memory for ia-addr.");
		goto exit;
	}
	data.data = data.buffer->data;
	memcpy(data.buffer->data, &iaaddr->addr, 16);
	lifetime = iaaddr->prefer;
	putULong(data.buffer->data + 16, lifetime);
	lifetime = iaaddr->valid;
	putULong(data.buffer->data + 20, lifetime);
	if (!save_option_buffer(&dhcpv6_universe, opt_state,
				NULL, (unsigned char *)data.data, data.len,
				D6O_IAADDR, 0)) {
		log_error("process_lq_by_address: error saving ia-addr.");
		goto exit;
	}
	data_string_forget(&data, MDL);

	lifetime = htonl(iaaddr->ia->cltt);
	if (!save_option_buffer(&dhcpv6_universe, opt_state,
				NULL, (unsigned char *)&lifetime, 4,
				D6O_CLT_TIME, 0)) {
		log_error("process_lq_by_address: error saving clt time.");
		goto exit;
	}

	/*
	 * Store the client-data option.
	 */
	opt_cursor = lq->cursor;
	putUShort(lq->buf.data + lq->cursor, (unsigned)D6O_CLIENT_DATA);
	lq->cursor += 2;
	/* Skip option length. */
	lq->cursor += 2;

	lq->cursor += store_options6((char *)lq->buf.data + lq->cursor,
				     sizeof(lq->buf) - lq->cursor,
				     opt_state, lq->packet,
				     required_opt_CLIENT_DATA, NULL);
	/* Reset the length. */
	putUShort(lq->buf.data + opt_cursor + 2,
		  lq->cursor - (opt_cursor + 4));

	/* Done. */
	ret_val = 1;

     exit:
	if (data.data != NULL)
		data_string_forget(&data, MDL);
	if (pool != NULL)
		ipv6_pool_dereference(&pool, MDL);
	if (iaaddr != NULL)
		iasubopt_dereference(&iaaddr, MDL);
	if (opt_state != NULL)
		option_state_dereference(&opt_state, MDL);
	return ret_val;
}
Example #24
0
	void radc_compiler::compile(int options)
	{
		if (_cache_program != -1)
		{
			varlist = programs[_cache_program].value->varlist;
			statements = programs[_cache_program].value->statements;

			return ;
		}

		char * str = buffer.c_ptr();
		int line = 1;
		int depth = 0;

		_options = options;

		while (*str && !is_error())
		{
			str = str_skip(str, ' ');

			if (*str == '#') // comment
			{
				while (*str && *str != '\n')
					++str;

				if (*str == '\n')
					++str;

				continue;
			}

			char * line_str = str;
			int line_length = 0;

			while (*str && *str != '\n')
			{
				++str;
				++line_length;
			}

			if (*str == '\n')
			{
				*str = 0;
				++str;
			}

			str_trim(line_str, line_length);
			if (*line_str)
			{
				const char * matched_str = NULL;
				radc_stat * stat = NULL;
				bool insert_empty = false;

				do
				{
					matched_str = str_match(line_str, "function");
					if (matched_str && (*matched_str == ' ' || *matched_str == '\0'))
					{
						matched_str = str_skip(matched_str, ' ');

						matched_str = str_match(matched_str, "main");
						if (matched_str)
						{
							stat = new rstat_entry;
							stat->str = str_skip(matched_str, ' ');
						}
						else
						{
							set_error("Error: [%d] - main.", line);
						}

						depth += 1;

						break;
					}

					matched_str = str_match(line_str, "if");
					if (matched_str && (*matched_str == ' ' || *matched_str == '\0'))
					{
						stat = new rstat_if;
						stat->str = str_skip(matched_str, ' ');
						insert_empty = true;
						depth += 1;

						break;
					}

					matched_str = str_match(line_str, "else");
					if (matched_str && (*matched_str == ' ' || *matched_str == '\0'))
					{
						matched_str = str_skip(matched_str, ' ');

						const char * matched_str2 = str_match(matched_str, "if");
						if (matched_str2 && (*matched_str2 == ' ' || *matched_str2 == '\0'))
						{
							stat = new rstat_elseif;
							stat->str = str_skip(matched_str2, ' ');
							insert_empty = true;
						}
						else
						{
							stat = new rstat_else;
							stat->str = str_skip(matched_str, ' ');
							insert_empty = true;
						}

						break;
					}

					matched_str = str_match(line_str, "end");
					if (matched_str  && (*matched_str == ' ' || *matched_str == '\0'))
					{
						stat = new rstat_end;
						stat->str = str_skip(matched_str, ' ');
						depth -= 1;

						break;
					}

					matched_str = str_match(line_str, "while");
					if (matched_str  && (*matched_str == ' ' || *matched_str == '\0'))
					{
						stat = new rstat_while;
						stat->str = str_skip(matched_str, ' ');
						insert_empty = true;
						depth += 1;

						break;
					}

					matched_str = str_match(line_str, "return");
					if (matched_str  && (*matched_str == ' ' || *matched_str == '\0'))
					{
						stat = new rstat_return;
						stat->str = str_skip(matched_str, ' ');

						break;
					}

					stat = new rstat_exp;
					stat->str = str_skip(line_str, ' ');

				} while (0);
				
				if (stat != NULL)
				{
					stat->line = line;
					statements.PushBack(stat);

					if (insert_empty)
					{
						statements.PushBack(new rstat_empty);
					}
				}
			}

			++line;
		}

		if (!is_error() && depth != 0)
		{
			set_error("Error: end don't macthed.");
		}

		// if Ìøת
		for (int i = 0; i < statements.Size(); ++i)
		{
			if (TYPE_OF(rstat_if, statements[i]) ||
				TYPE_OF(rstat_elseif, statements[i]) ||
				TYPE_OF(rstat_else, statements[i]))
			{
				int in_if = 0, end_if = 0;

				for (int j = i + 1; j < statements.Size(); ++j)
				{
					if (TYPE_OF(rstat_elseif, statements[j]) ||
						TYPE_OF(rstat_else, statements[j]) ||
						TYPE_OF(rstat_end, statements[j]))
					{
						if (in_if == 0)
						{
							end_if = j - 1;
							statements[i]->jump = j;
							break;
						}
					}

					if (TYPE_OF(rstat_if, statements[j]) ||
						TYPE_OF(rstat_while, statements[j]))
					{
						in_if += 1;
					}

					if (TYPE_OF(rstat_end, statements[j]))
					{
						in_if -= 1;
					}
				}

				d_assert (end_if > i);

				in_if = 0;
				for (int j = end_if + 1; j < statements.Size(); ++j)
				{
					if (TYPE_OF(rstat_end, statements[j]))
					{
						if (in_if == 0)
						{
							statements[end_if]->jump = j;
							break;
						}
					}

					if (TYPE_OF(rstat_if, statements[j]) ||
						TYPE_OF(rstat_while, statements[j]))
					{
						in_if += 1;
					}

					if (TYPE_OF(rstat_end, statements[j]))
					{
						in_if -= 1;
					}
				}
			}
		}

		// while Ìøת
		for (int i = 0; i < statements.Size(); ++i)
		{
			if (TYPE_OF(rstat_while, statements[i]))
			{
				int in_while = 0, end_while = 0;

				for (int j = i + 1; j < statements.Size(); ++j)
				{
					if (TYPE_OF(rstat_end, statements[j]))
					{
						if (in_while == 0)
						{
							end_while = j - 1;
							statements[i]->jump = j;
							break;
						}
					}

					if (TYPE_OF(rstat_if, statements[j]) ||
						TYPE_OF(rstat_while, statements[j]))
					{
						in_while += 1;
					}

					if (TYPE_OF(rstat_end, statements[j]))
					{
						in_while -= 1;
					}
				}

				d_assert (end_while > i);

				statements[end_while]->jump = i;
			}
		}

		for (int i = 0; i < statements.Size(); ++i)
		{
			statements[i]->build();
		}
	}
template <> void
GncDbiBackend<DbType::DBI_SQLITE>::session_begin(QofSession* session,
                                                 const char* book_id,
                                                 bool ignore_lock,
                                                 bool create, bool force)
{
    gboolean file_exists;
    PairVec options;

    g_return_if_fail (session != nullptr);
    g_return_if_fail (book_id != nullptr);

    ENTER (" ");

    /* Remove uri type if present */
    auto path = gnc_uri_get_path (book_id);
    std::string filepath{path};
    g_free(path);
    GFileTest ftest = static_cast<decltype (ftest)> (
        G_FILE_TEST_IS_REGULAR | G_FILE_TEST_EXISTS) ;
    file_exists = g_file_test (filepath.c_str(), ftest);
    if (!create && !file_exists)
    {
        set_error (ERR_FILEIO_FILE_NOT_FOUND);
        std::string msg{"Sqlite3 file "};
        set_message (msg + filepath + " not found");
        PWARN ("Sqlite3 file %s not found", filepath.c_str());
        LEAVE("Error");
	return;
    }

    if (create && !force && file_exists)
    {
        set_error (ERR_BACKEND_STORE_EXISTS);
        auto msg = "Might clobber, no force";
        PWARN ("%s", msg);
        LEAVE("Error");
	return;
    }

    connect(nullptr);
    /* dbi-sqlite3 documentation says that sqlite3 doesn't take a "host" option */
    options.push_back(std::make_pair("host", "localhost"));
    auto dirname = g_path_get_dirname (filepath.c_str());
    auto basename = g_path_get_basename (filepath.c_str());
    options.push_back(std::make_pair("dbname", basename));
    options.push_back(std::make_pair("sqlite3_dbdir", dirname));
    if (basename != nullptr) g_free (basename);
    if (dirname != nullptr) g_free (dirname);
    UriStrings uri;
    auto conn = conn_setup(options, uri);
    if (conn == nullptr)
    {
        LEAVE("Error");
        return;
    }

    auto result = dbi_conn_connect (conn);

    if (result < 0)
    {
        dbi_conn_close(conn);
        PERR ("Unable to connect to %s: %d\n", book_id, result);
        set_error (ERR_BACKEND_BAD_URL);
        LEAVE("Error");
	return;
    }

    if (!conn_test_dbi_library(conn))
    {
        if (create && !file_exists)
        {
         /* File didn't exist before, but it does now, and we don't want to
          * leave it lying around.
          */
            dbi_conn_close (conn);
            conn = nullptr;
            g_unlink (filepath.c_str());
        }
        dbi_conn_close(conn);
        LEAVE("Bad DBI Library");
        return;
    }

    try
    {
        connect(new GncDbiSqlConnection(DbType::DBI_SQLITE,
                                            this, conn, ignore_lock));
    }
    catch (std::runtime_error& err)
    {
        return;
    }

    /* We should now have a proper session set up.
     * Let's start logging */
    xaccLogSetBaseName (filepath.c_str());
    PINFO ("logpath=%s", filepath.c_str() ? filepath.c_str() : "(null)");

    LEAVE ("");
}
Example #26
0
/* set the last error depending on errno */
static void sock_set_error(void)
{
    set_error( sock_get_ntstatus( errno ) );
}
Example #27
0
/** \brief Main algorithm function.

This function performs all the operations needed to feed the data one dimension at a time to the matching_1D function.

\param data the data set
\param out the output bit matrix

\retval error code
*/
_ERR_CODE sort_matching(const match_data_t data, const bitmatrix out)
{
	_UINT i;
	_UINT line_width;
	_UINT matrix_size;
	THREAD_T thread[MAX_DIMENSIONS];
	MUTEX_T *line_mutex;
	thread_params params[MAX_DIMENSIONS];
	RETVAL_T retval = 0;
#ifndef _MSC_VER
	_ERR_CODE retcpy;
#endif // _MSC_VER

	line_width = BIT_VEC_WIDTH(data.size_subscr);
	matrix_size = data.size_update * line_width;

	if (data.dimensions < 1)
		return set_error(err_invalid_input, __FILE__, __FUNCTION__, __LINE__);

	if (data.dimensions > MAX_DIMENSIONS)
		return set_error(err_too_many_dim, __FILE__, __FUNCTION__, __LINE__);

	// allocate memory for the mutexes array (one mutex for every line of the bit matrix)
	line_mutex = (MUTEX_T *)malloc(data.size_update * sizeof(MUTEX_T));
	if (line_mutex == NULL)
		return set_error(err_alloc, __FILE__, __FUNCTION__, __LINE__);

	for (i = 0; i < data.size_update; i++)
	{
#ifdef _MSC_VER
		// create (initialize) mutexes
		line_mutex[i] = CreateMutex(NULL, FALSE, NULL);
		if (line_mutex[i] == NULL)
			return set_error(err_threads, __FILE__, __FUNCTION__, __LINE__);
#else // _MSC_VER
		// create (initialize) mutexes
		if (pthread_mutex_init(&line_mutex[i], NULL) != 0)
			return set_error(err_threads, __FILE__, __FUNCTION__, __LINE__);
#endif // _MSC_VER
	}

	// for each dimension
	for (i = 0; i < data.dimensions; i++)
	{
		// set the parameters for the i-th thread
		params[i].data = data;
		params[i].line_mutex = line_mutex;
		params[i].out = out;
		params[i].dimension = i;

#ifdef _MSC_VER
		// create and start the thread
		thread[i] = (HANDLE)_beginthreadex(NULL, 0U, sort_matching_1D, &params[i], _P_NOWAIT, NULL);
		if (thread[i] == NULL)
			return set_error(err_threads, __FILE__, __FUNCTION__, __LINE__);
#else // _MSC_VER
		// create and start the thread
		if (pthread_create(&thread[i], NULL, sort_matching_1D, &params[i]) != 0)
			return set_error(err_threads, __FILE__, __FUNCTION__, __LINE__);
#endif // _MSC_VER
	}

#ifdef _MSC_VER
	// wait for all threads to finish
	if (WaitForMultipleObjects(data.dimensions, thread, TRUE, INFINITE) == WAIT_FAILED)
		return set_error(err_threads, __FILE__, __FUNCTION__, __LINE__);

#ifndef __NOFREE
	// for each line in the bit matrix
	for (i = 0; i < data.size_update; i++)
	{
		// close mutex handle
		if (CloseHandle(line_mutex[i]) == 0)
			return set_error(err_threads, __FILE__, __FUNCTION__, __LINE__);
	}
	// free the mutexes array
	free(line_mutex);
#endif // __NOFREE

	// for each thread
	for (i = 0; i < data.dimensions; i++)
	{
		// get the exit code of the thread
		if (GetExitCodeThread(thread[i], &retval) == 0)
			return set_error(err_threads, __FILE__, __FUNCTION__, __LINE__);
		// check for errors in exit code
		if ((_ERR_CODE)retval != err_none)
			return (_ERR_CODE)retval;

#ifndef __NOFREE
		// close thread handle
		if (CloseHandle(thread[i]) == 0)
			return set_error(err_threads, __FILE__, __FUNCTION__, __LINE__);
#endif // __NOFREE
	}
#else // _MSC_VER
	// for each thread
	for (i = 0; i < data.dimensions; i++)
	{
		// wait for all threads to finish (and get the exit code of the thread)
		if (pthread_join(thread[i], (void *)&retval) != 0)
			return set_error(err_threads, __FILE__, __FUNCTION__, __LINE__);

		// if a thread returns NULL it means something has gone wrong during the allocation of the memory for the return code
		if (retval == NULL)
		{
			return set_error(err_alloc, __FILE__, __FUNCTION__, __LINE__);
		}
		else
		{
			retcpy = *retval;
#ifndef __NOFREE
		// free the memory allocated by the thread
			free(retval);
#endif // __NOFREE
		// check for errors in exit code
			if (retcpy != err_none)
				return retcpy;
		}
	}

#ifndef __NOFREE
	// for each line in the bit matrix, destroy the mutex
	for (i = 0; i < data.size_update; i++)
		pthread_mutex_destroy(&line_mutex[i]);

	// free the mutexes array
	free(line_mutex);
#endif // __NOFREE
#endif // _MSC_VER

	// bitwise NOT of the non-matching table to obtain the matching table
	vector_bitwise_not(out[0], matrix_size);

	return err_none;
}
Example #28
0
static struct zip_cdir *
_zip_find_central_dir(FILE *fp, unsigned int flags, int *zep, off_t len)
{
    struct zip_cdir *cdir, *cdirnew;
    unsigned char *buf, *match;
    off_t buf_offset;
    size_t buflen;
    zip_int64_t a, i;
    zip_int64_t best;
    struct zip_error zerr;

    if (len < (off_t)EOCDLEN) {
        set_error(zep, NULL, ZIP_ER_NOZIP);
        return NULL;
    }
    
    i = fseeko(fp, -(len < CDBUFSIZE ? len : CDBUFSIZE), SEEK_END);
    if (i == -1 && errno != EFBIG) {
	/* seek before start of file on my machine */
	set_error(zep, NULL, ZIP_ER_SEEK);
	return NULL;
    }
    buf_offset = ftello(fp);
    
    /* 64k is too much for stack */
    if ((buf=(unsigned char *)malloc(CDBUFSIZE)) == NULL) {
	set_error(zep, NULL, ZIP_ER_MEMORY);
	return NULL;
    }

    clearerr(fp);
    buflen = fread(buf, 1, CDBUFSIZE, fp);

    if (ferror(fp)) {
	set_error(zep, NULL, ZIP_ER_READ);
	free(buf);
	return NULL;
    }
    
    best = -1;
    cdir = NULL;
    match = buf+ (buflen < CDBUFSIZE ? 0 : EOCD64LOCLEN);
    _zip_error_set(&zerr, ZIP_ER_NOZIP, 0);

    while ((match=_zip_memmem(match, buflen-(size_t)(match-buf)-(EOCDLEN-4),
			      (const unsigned char *)EOCD_MAGIC, 4))!=NULL) {
	/* found match -- check, if good */
	/* to avoid finding the same match all over again */
	match++;
	if ((cdirnew=_zip_readcdir(fp, buf_offset, buf, match-1, buflen, flags,
				   &zerr)) == NULL)
	    continue;

	if (cdir) {
	    if (best <= 0)
		best = _zip_checkcons(fp, cdir, &zerr);
	    a = _zip_checkcons(fp, cdirnew, &zerr);
	    if (best < a) {
		_zip_cdir_free(cdir);
		cdir = cdirnew;
		best = a;
	    }
	    else
		_zip_cdir_free(cdirnew);
	}
	else {
	    cdir = cdirnew;
	    if (flags & ZIP_CHECKCONS)
		best = _zip_checkcons(fp, cdir, &zerr);
	    else
		best = 0;
	}
	cdirnew = NULL;
    }

    free(buf);
    
    if (best < 0) {
	set_error(zep, &zerr, 0);
	_zip_cdir_free(cdir);
	return NULL;
    }

    return cdir;
}
Example #29
0
static struct object *create_file( struct fd *root, const char *nameptr, data_size_t len,
                                   unsigned int access, unsigned int sharing, int create,
                                   unsigned int options, unsigned int attrs,
                                   const struct security_descriptor *sd )
{
    struct object *obj = NULL;
    struct fd *fd;
    int flags;
    char *name;
    mode_t mode;

    if (!len || ((nameptr[0] == '/') ^ !root))
    {
        set_error( STATUS_OBJECT_PATH_SYNTAX_BAD );
        return NULL;
    }
    if (!(name = mem_alloc( len + 1 ))) return NULL;
    memcpy( name, nameptr, len );
    name[len] = 0;

    switch(create)
    {
    case FILE_CREATE:       flags = O_CREAT | O_EXCL; break;
    case FILE_OVERWRITE_IF: /* FIXME: the difference is whether we trash existing attr or not */
                            access |= FILE_WRITE_ATTRIBUTES;
    case FILE_SUPERSEDE:    flags = O_CREAT | O_TRUNC; break;
    case FILE_OPEN:         flags = 0; break;
    case FILE_OPEN_IF:      flags = O_CREAT; break;
    case FILE_OVERWRITE:    flags = O_TRUNC;
                            access |= FILE_WRITE_ATTRIBUTES; break;
    default:                set_error( STATUS_INVALID_PARAMETER ); goto done;
    }

    if (sd)
    {
        const SID *owner = sd_get_owner( sd );
        if (!owner)
            owner = token_get_user( current->process->token );
        mode = sd_to_mode( sd, owner );
    }
    else if (options & FILE_DIRECTORY_FILE)
        mode = (attrs & FILE_ATTRIBUTE_READONLY) ? 0555 : 0777;
    else
        mode = (attrs & FILE_ATTRIBUTE_READONLY) ? 0444 : 0666;

    if (len >= 4 &&
        (!strcasecmp( name + len - 4, ".exe" ) || !strcasecmp( name + len - 4, ".com" )))
    {
        if (mode & S_IRUSR)
            mode |= S_IXUSR;
        if (mode & S_IRGRP)
            mode |= S_IXGRP;
        if (mode & S_IROTH)
            mode |= S_IXOTH;
    }

    access = generic_file_map_access( access );

    /* FIXME: should set error to STATUS_OBJECT_NAME_COLLISION if file existed before */
    fd = open_fd( root, name, flags | O_NONBLOCK | O_LARGEFILE, &mode, access, sharing, options );
    if (!fd) goto done;

    if (S_ISDIR(mode))
        obj = create_dir_obj( fd, access, mode );
    else if (S_ISCHR(mode) && is_serial_fd( fd ))
        obj = create_serial( fd );
    else
        obj = create_file_obj( fd, access, mode );

    release_object( fd );

done:
    free( name );
    return obj;
}
Example #30
0
void RequestHandler::on_timeout() {
  assert(!is_query_plan_exhausted_ && "Tried to timeout on a non-existent host");
  set_error(CASS_ERROR_LIB_REQUEST_TIMED_OUT, "Request timed out");
}