Ejemplo n.º 1
0
static int pgsql_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquotedlen, char **quoted, int *quotedlen, enum pdo_param_type paramtype)
{
	unsigned char *escaped;
	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
	size_t tmp_len;

	switch (paramtype) {
		case PDO_PARAM_LOB:
			/* escapedlen returned by PQescapeBytea() accounts for trailing 0 */
			escaped = PQescapeByteaConn(H->server, (unsigned char *)unquoted, (size_t)unquotedlen, &tmp_len);
			*quotedlen = (int)tmp_len + 1;
			*quoted = emalloc(*quotedlen + 1);
			memcpy((*quoted)+1, escaped, *quotedlen-2);
			(*quoted)[0] = '\'';
			(*quoted)[*quotedlen-1] = '\'';
			(*quoted)[*quotedlen] = '\0';
			PQfreemem(escaped);
			break;
		default:
			*quoted = safe_emalloc(2, unquotedlen, 3);
			(*quoted)[0] = '\'';
			*quotedlen = PQescapeStringConn(H->server, *quoted + 1, unquoted, (size_t)unquotedlen, NULL);
			(*quoted)[*quotedlen + 1] = '\'';
			(*quoted)[*quotedlen + 2] = '\0';
			*quotedlen += 2;
	}
	return 1;
}
Ejemplo n.º 2
0
static VALUE cConnection_quote_byte_array(VALUE self, VALUE string) {
  PGconn *db = DATA_PTR(rb_iv_get(self, "@connection"));

  const unsigned char *source = (unsigned char*) RSTRING_PTR(string);
  size_t source_len     = RSTRING_LEN(string);

  unsigned char *escaped;
  unsigned char *escaped_quotes;
  size_t quoted_length = 0;
  VALUE result;

  // Allocate space for the escaped version of 'string'
  // http://www.postgresql.org/docs/8.3/static/libpq-exec.html#LIBPQ-EXEC-ESCAPE-STRING
  escaped = PQescapeByteaConn(db, source, source_len, &quoted_length);
  escaped_quotes = (unsigned char *)calloc(quoted_length + 1, sizeof(unsigned char));
  memcpy(escaped_quotes + 1, escaped, quoted_length);

  // Wrap the escaped string in single-quotes, this is DO's convention (replace trailing \0)
  escaped_quotes[quoted_length] = escaped_quotes[0] = '\'';

  result = rb_str_new((const char *)escaped_quotes, quoted_length + 1);
  PQfreemem(escaped);
  free(escaped_quotes);
  return result;
}
Ejemplo n.º 3
0
static unsigned char *
binary_escape(unsigned char *from, size_t from_length,
               size_t *to_length, PGconn *conn)
{
    if (conn)
        return PQescapeByteaConn(conn, from, from_length, to_length);
    else
        return PQescapeBytea(from, from_length, to_length);
}
Ejemplo n.º 4
0
static unsigned char *
binary_escape(unsigned char *from, size_t from_length,
               size_t *to_length, PGconn *conn)
{
#if PG_VERSION_HEX >= 0x080104
    if (conn)
        return PQescapeByteaConn(conn, from, from_length, to_length);
    else
#endif
        return PQescapeBytea(from, from_length, to_length);
}
Ejemplo n.º 5
0
unsigned char *postgresql_util_escape_binary(postgresql_conn_t *conn,
                                             const unsigned char *from,
                                             size_t from_length,
                                             size_t *to_length)
{
    unsigned char *escaped = PQescapeByteaConn(conn->conn, from, from_length, to_length);
    if (!escaped) {
        msg->err("[FD %i] PostgreSQL Escape Binary Error: %s", PQerrorMessage(conn->conn));
    }
    return escaped;
}
Ejemplo n.º 6
0
CAMLprim value PQescapeByteaConn_stub(
  value v_conn, value v_from, value v_pos_from, value v_len)
{
  size_t len;
  char *buf =
    (char *) PQescapeByteaConn(
      get_conn(v_conn),
      (unsigned char *) String_val(v_from) + Long_val(v_pos_from),
      Long_val(v_len), &len);
  value v_res = caml_alloc_string(--len);
  memcpy(String_val(v_res), buf, len);
  PQfreemem(buf);
  return v_res;
}
std::string DatabasePgSQL::escapeBlob(const char *s, uint32_t length)
{
	// remember to quote even empty stream!
	if(!s)
		return std::string("''");

	// quotes escaped string and frees temporary buffer
	size_t len;
	char* output = (char*)PQescapeByteaConn(m_handle, (uint8_t*)s, length, &len);

	std::string r = std::string("E'");
	r += output;
	r += "'";

	PQfreemem(output);
	return r;
}
Ejemplo n.º 8
0
/* 
 * Adapter function to PQescapeByteaConn()
 * This function should properly escape the raw argument 
 * appropriately depending on connection.
 * Note the single quote is not attached in the return val.
 * The returned string could differ depending on the environment.
 * Especially standard_conforming_strings parameter 
 * is possibly influencial.
 * http://www.postgresql.org/docs/9.3/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
 */
SEXP
RS_PostgreSQL_escape_bytea(SEXP conHandle, SEXP raw_data)
{
    S_EVALUATOR PGconn * my_connection;
    RS_DBI_connection *con;
    SEXP output;
    size_t length;
    char *escapedstring;
    size_t escaped_length;
    con = RS_DBI_getConnection(conHandle);
    my_connection = (PGconn *) con->drvConnection;
    length = LENGTH(raw_data);
    escapedstring = (char *)PQescapeByteaConn(my_connection, RAW(raw_data), length, &escaped_length);
    /* explicit cast to make clang silent for difference in signedness*/
    PROTECT(output = allocVector(STRSXP, 1));
    SET_STRING_ELT(output, 0, mkChar(escapedstring));
    free(escapedstring);
    UNPROTECT(1);
    return output;
}
Ejemplo n.º 9
0
BOOL CPgSQL::WriteScorcoData(char* SQL, BYTE* pData, int Length)
{
	BOOL bWriteSuccess = true;

	unsigned int escaped_data_len = 0;
	char* escaped_data = (char*)PQescapeByteaConn(pgsql, pData, Length, &escaped_data_len);

	unsigned int full_query_len = (strlen(SQL) - 2) + (escaped_data_len + 4);
	char* full_query = new char[full_query_len];

	// Build the full query string. The SQL query must have a %s token to locate the 
	// substituted escaped data. This loops through the original SQL writing it to the
	// full query string until the %s is hit, then inserts the escaped data surrounded 
	// by the proper escape syntax, then returns to write the remaining SQL.
	char* fs_ptr = SQL;
	char* fd_ptr = escaped_data;
	char* tq_ptr = full_query;
	bool tok_hit = false;
	while (fs_ptr[0] != '\x00') {
		if ( !tok_hit && (fs_ptr[0] == '%') && (fs_ptr[1] == 's')) {
			tok_hit = true;
			fs_ptr += 2;
			*tq_ptr++ = 'E'; *tq_ptr++ = '\''; *tq_ptr++ = '\\';
			while (fd_ptr[0] != '\x00') *tq_ptr++ = *fd_ptr++;
			*tq_ptr++ = '\'';
		} else {
			*tq_ptr++ = *fs_ptr++;
		}
	}
	*tq_ptr = '\x00';
	if (!tok_hit) bWriteSuccess = false;
	
	PGresult* sco_result = PQexec(pgsql, full_query);
	if ( PQresultStatus(sco_result) != PGRES_COMMAND_OK ) bWriteSuccess = false;

	PQfreemem(escaped_data);
	delete[] full_query;
	PQclear (sco_result);

	return bWriteSuccess;
}
Ejemplo n.º 10
0
Archivo: val.c Proyecto: NormB/opensips
/*
 * Used when converting result from a query
 */
int db_postgres_val2str(const db_con_t* _con, const db_val_t* _v,
														char* _s, int* _len)
{
	int l, ret;
	int pgret;
	char *tmp_s;
	size_t tmp_len;
	char* old_s;

	if ((!_v) || (!_s) || (!_len) || (!*_len)) {
		LM_ERR("invalid parameter value\n");
		return -1;
	}

	if (VAL_NULL(_v)) {
		if ( *_len < (l=(int)sizeof("NULL")-1)) {
			LM_ERR("buffer too short to print NULL\n");
			return -1;
		}
		memcpy(_s, "NULL", l);
		*_len = l;
		return 0;
	}

	switch(VAL_TYPE(_v)) {
	case DB_INT:
		if (db_int2str(VAL_INT(_v), _s, _len) < 0) {
			LM_ERR("failed to convert string to int\n");
			return -2;
		} else {
			return 0;
		}
		break;

	case DB_BIGINT:
		if (db_bigint2str(VAL_BIGINT(_v), _s, _len) < 0) {
			LM_ERR("failed to convert string to big int\n");
			return -2;
		} else {
			return 0;
		}
		break;

	case DB_BITMAP:
		if (db_int2str(VAL_BITMAP(_v), _s, _len) < 0) {
			LM_ERR("failed to convert string to int\n");
			return -3;
		} else {
			return 0;
		}
		break;

	case DB_DOUBLE:
		if (db_double2str(VAL_DOUBLE(_v), _s, _len) < 0) {
			LM_ERR("failed to convert string to double\n");
			return -3;
		} else {
			return 0;
		}
		break;

	case DB_STRING:
		l = strlen(VAL_STRING(_v));
		if (*_len < (l * 2 + 3)) {
			LM_ERR("destination STRING buffer too short (have %d, need %d)\n",
			       *_len, l * 2 + 3);
			return -4;
		} else {
			old_s = _s;
			*_s++ = '\'';
			ret = PQescapeStringConn(CON_CONNECTION(_con), _s, VAL_STRING(_v),
					l, &pgret);
			if(pgret!=0)
			{
				LM_ERR("PQescapeStringConn failed\n");
				return -4;
			}
			LM_DBG("PQescapeStringConn: in: %d chars,"
				" out: %d chars\n", l, ret);
			_s += ret;
			*_s++ = '\'';
			*_s = '\0'; /* FIXME */
			*_len = _s - old_s;
			return 0;
		}
		break;

	case DB_STR:
		l = VAL_STR(_v).len;
		if (*_len < (l * 2 + 3)) {
			LM_ERR("destination STR buffer too short (have %d, need %d)\n",
			       *_len, l * 2 + 3);
			return -5;
		} else {
			old_s = _s;
			*_s++ = '\'';
			ret = PQescapeStringConn(CON_CONNECTION(_con), _s, VAL_STRING(_v),
					l, &pgret);
			if(pgret!=0)
			{
				LM_ERR("PQescapeStringConn failed \n");
				return -5;
			}
	        LM_DBG("PQescapeStringConn: in: %d chars, out: %d chars\n", l, ret);
			_s += ret;
			*_s++ = '\'';
			*_s = '\0'; /* FIXME */
			*_len = _s - old_s;
			return 0;
		}
		break;

	case DB_DATETIME:
		if (db_time2str(VAL_TIME(_v), _s, _len) < 0) {
			LM_ERR("failed to convert string to time_t\n");
			return -6;
		} else {
			return 0;
		}
		break;

	case DB_BLOB:
		l = VAL_BLOB(_v).len;
		/* this estimation is not always correct, thus we need to check later again */
		if (*_len < (l * 2 + 3)) {
			LM_ERR("destination BLOB buffer too short (have %d, need %d)\n",
			       *_len, l * 2 + 3);
			return -7;
		} else {
			*_s++ = '\'';
			tmp_s = (char*)PQescapeByteaConn(CON_CONNECTION(_con), (unsigned char*)VAL_STRING(_v),
					(size_t)l, (size_t*)&tmp_len);
			if(tmp_s==NULL)
			{
				LM_ERR("PQescapeBytea failed\n");
				return -7;
			}
			if (tmp_len > *_len) {
				LM_ERR("escaped result too long\n");
				return -7;
			}
			memcpy(_s, tmp_s, tmp_len);
			PQfreemem(tmp_s);
			tmp_len = strlen(_s);
			*(_s + tmp_len) = '\'';
			*(_s + tmp_len + 1) = '\0';
			*_len = tmp_len + 2;
			return 0;
		}
		break;

	default:
		LM_DBG("unknown data type\n");
		return -7;
	}
}
Ejemplo n.º 11
0
/** Insert value in the PostgreSQL database.
 *
 * \param db Database that links to the PostgreSQL db
 * \param table DbTable to insert data in
 * \param sender_id sender ID
 * \param seq_no sequence number
 * \param time_stamp timestamp of the receiving data
 * \param values OmlValue array to insert
 * \param value_count number of values
 * \return 0 if successful, -1 otherwise
 */
static int
psql_insert(Database* db,
            DbTable*  table,
            int       sender_id,
            int       seq_no,
            double    time_stamp,
            OmlValue* values,
            int       value_count)
{
  PsqlDB* psqldb = (PsqlDB*)db->handle;
  PsqlTable* psqltable = (PsqlTable*)table->handle;
  PGresult* res;
  int i;
  double time_stamp_server;
  const char* insert_stmt = mstring_buf (psqltable->insert_stmt);
  unsigned char *escaped_blob;
  size_t eblob_len=-1;

  char * paramValues[4+value_count];
  for (i=0;i<4+value_count;i++) {
    paramValues[i] = xmalloc(512*sizeof(char));
  }

  int paramLength[4+value_count];
  int paramFormat[4+value_count];

  sprintf(paramValues[0],"%i",sender_id);
  paramLength[0] = 0;
  paramFormat[0] = 0;

  sprintf(paramValues[1],"%i",seq_no);
  paramLength[1] = 0;
  paramFormat[1] = 0;

  sprintf(paramValues[2],"%.8f",time_stamp);
  paramLength[2] = 0;
  paramFormat[2] = 0;

  struct timeval tv;
  gettimeofday(&tv, NULL);
  time_stamp_server = tv.tv_sec - db->start_time + 0.000001 * tv.tv_usec;

  if (tv.tv_sec > psqldb->last_commit) {
    if (reopen_transaction (psqldb) == -1)
      return -1;
    psqldb->last_commit = tv.tv_sec;
  }

  sprintf(paramValues[3],"%.8f",time_stamp_server);
  paramLength[3] = 0;
  paramFormat[3] = 0;

  OmlValue* v = values;
  for (i = 0; i < value_count; i++, v++) {
    struct schema_field *field = &table->schema->fields[i];
    if (oml_value_get_type(v) != field->type) {
      logerror("psql:%s: Value %d type mismatch for table '%s'\n", db->name, i, table->schema->name);
      return -1;
    }
    switch (field->type) {
    case OML_LONG_VALUE: sprintf(paramValues[4+i],"%i",(int)v->value.longValue); break;
    case OML_INT32_VALUE:  sprintf(paramValues[4+i],"%" PRId32,v->value.int32Value); break;
    case OML_UINT32_VALUE: sprintf(paramValues[4+i],"%" PRIu32,v->value.uint32Value); break;
    case OML_INT64_VALUE:  sprintf(paramValues[4+i],"%" PRId64,v->value.int64Value); break;
    case OML_UINT64_VALUE: sprintf(paramValues[4+i],"%" PRIu64,v->value.uint64Value); break;
    case OML_DOUBLE_VALUE: sprintf(paramValues[4+i],"%.8f",v->value.doubleValue); break;
    case OML_STRING_VALUE: sprintf(paramValues[4+i],"%s", omlc_get_string_ptr(*oml_value_get_value(v))); break;
    case OML_BLOB_VALUE:
                           escaped_blob = PQescapeByteaConn(psqldb->conn,
                               v->value.blobValue.ptr, v->value.blobValue.length, &eblob_len);
                           if (!escaped_blob) {
                             logerror("psql:%s: Error escaping blob in field %d of table '%s': %s\n",
                                 db->name, i, table->schema->name, PQerrorMessage(psqldb->conn));
                           }
                           /* XXX: 512 char is the size allocated above. Nasty. */
                           if (eblob_len > 512) {
                             logdebug("psql:%s: Reallocating %d bytes for big blob\n", db->name, eblob_len);
                             paramValues[4+i] = xrealloc(paramValues[4+i], eblob_len);
                             if (!paramValues[4+i]) {
                               logerror("psql:%s: Could not realloc()at memory for escaped blob in field %d of table '%s'\n",
                                   db->name, i, table->schema->name);
                               return -1;
                             }
                           }
                           snprintf(paramValues[4+i], eblob_len, "%s", escaped_blob);
                           PQfreemem(escaped_blob);
                           break;
    default:
      logerror("psql:%s: Unknown type %d in col '%s' of table '%s'; this is probably a bug\n",
          db->name, field->type, field->name, table->schema->name);
      return -1;
    }
    paramLength[4+i] = 0;
    paramFormat[4+i] = 0;
  }
  /* Use stuff from http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-ERROR-TRAPPING */

  res = PQexecPrepared(psqldb->conn, insert_stmt,
                       4+value_count, (const char**)paramValues,
                       (int*) &paramLength, (int*) &paramFormat, 0 );

  if (PQresultStatus(res) != PGRES_COMMAND_OK) {
    logerror("psql:%s: INSERT INTO '%s' failed: %s\n",
        db->name, table->schema->name, PQerrorMessage(psqldb->conn));
    PQclear(res);
    return -1;
  }
  PQclear(res);

  for (i=0;i<4+value_count;i++) {
    xfree(paramValues[i]);
  }

  return 0;
}
Ejemplo n.º 12
0
/*!
 * \brief Converting a value to a string
 *
 * Converting a value to a string, used when converting result from a query
 * \param _con database connection
 * \param _v source value
 * \param _s target string
 * \param _len target string length
 * \return 0 on success, negative on error
 */
int db_postgres_val2str(
		const db1_con_t *_con, const db_val_t *_v, char *_s, int *_len)
{
	int l, ret, tmp;
	int pgret;
	char *tmp_s;
	size_t tmp_len;
	char *old_s;

	tmp = db_val2str(_con, _v, _s, _len);
	if(tmp < 1)
		return tmp;

	switch(VAL_TYPE(_v)) {
		case DB1_STRING:
			l = strlen(VAL_STRING(_v));
			if(*_len < (l * 2 + 3)) {
				LM_ERR("destination buffer too short for string\n");
				return -6;
			} else {
				old_s = _s;
				*_s++ = '\'';
				ret = PQescapeStringConn(
						CON_CONNECTION(_con), _s, VAL_STRING(_v), l, &pgret);
				if(pgret != 0) {
					LM_ERR("PQescapeStringConn failed\n");
					return -6;
				}
				LM_DBG("PQescapeStringConn: in: %d chars,"
					   " out: %d chars\n",
						l, ret);
				_s += ret;
				*_s++ = '\'';
				*_s = '\0'; /* FIXME */
				*_len = _s - old_s;
				return 0;
			}
			break;

		case DB1_STR:
			l = VAL_STR(_v).len;
			if(*_len < (l * 2 + 3)) {
				LM_ERR("destination buffer too short for str\n");
				return -7;
			} else {
				old_s = _s;
				*_s++ = '\'';
				ret = PQescapeStringConn(
						CON_CONNECTION(_con), _s, VAL_STRING(_v), l, &pgret);
				if(pgret != 0) {
					LM_ERR("PQescapeStringConn failed \n");
					return -7;
				}
				LM_DBG("PQescapeStringConn: in: %d chars, out: %d chars\n", l,
						ret);
				_s += ret;
				*_s++ = '\'';
				*_s = '\0'; /* FIXME */
				*_len = _s - old_s;
				return 0;
			}
			break;

		case DB1_BLOB:
			l = VAL_BLOB(_v).len;
			/* this estimation is not always correct, thus we need to check later again */
			if(*_len < (l * 2 + 3)) {
				LM_ERR("destination buffer too short for blob\n");
				return -9;
			} else {
				*_s++ = '\'';
				tmp_s = (char *)PQescapeByteaConn(CON_CONNECTION(_con),
						(unsigned char *)VAL_STRING(_v), (size_t)l,
						(size_t *)&tmp_len);
				if(tmp_s == NULL) {
					LM_ERR("PQescapeByteaConn failed\n");
					return -9;
				}
				if(tmp_len > *_len) {
					LM_ERR("escaped result too long\n");
					return -9;
				}
				memcpy(_s, tmp_s, tmp_len);
				PQfreemem(tmp_s);
				tmp_len = strlen(_s);
				*(_s + tmp_len) = '\'';
				*(_s + tmp_len + 1) = '\0';
				*_len = tmp_len + 2;
				return 0;
			}
			break;

		default:
			LM_ERR("unknown data type\n");
			return -10;
	}
}