示例#1
0
unsigned long DatabasePostgre::escape_string(char *to, const char *from, unsigned long length)
{
    if (!mPGconn || !to || !from || !length)
        return 0;

    return PQescapeString(to, from, length);
}
示例#2
0
unsigned long PostgreSQLConnection::escape_string(char* to, const char* from, unsigned long length)
{
    if (!mPGconn || !to || !from || !length)
        return 0;

    return PQescapeString(to, from, length);
}
示例#3
0
文件: xyz_sql.c 项目: alannice/learn
int xyz_pgsql_exec(struct xyz_pgsql_t *pgsql, int flag, char *sqlstring)
{
    char execstring[512] = {0};

    if(pgsql == NULL || sqlstring == NULL) {
        return -1;
    }

    PQescapeString(execstring, sqlstring, strlen(sqlstring));

    pgsql->pg_result = PQexec(pgsql->pg_connect, execstring);
    if(PQresultStatus(pgsql->pg_result) != PGRES_TUPLES_OK) {
        fprintf(stderr,"pg exec error :%s\n", PQerrorMessage(pgsql->pg_connect));
        PQclear(pgsql->pg_result);
        pgsql->pg_result = NULL;
        return -1;
    }

    if(flag == 0) {
        PQclear(pgsql->pg_result);
        pgsql->pg_result = NULL;
        return 0;
    }

    return PQntuples(pgsql->pg_result);
}
示例#4
0
文件: pdb_pgsql.c 项目: hajuuk/R7000
static NTSTATUS pgsqlsam_select_by_field ( struct pdb_methods *methods, SAM_ACCOUNT *user, enum sql_search_field field, const char *sname )
{
  struct pdb_pgsql_data *data ;
  
  char *esc ;
  char *query ;
  
  PGresult *result ;
  NTSTATUS retval ;

  SET_DATA(data, methods);

  if ( user == NULL )
  {
    DEBUG( 0, ("pdb_getsampwnam: SAM_ACCOUNT is NULL.\n") ) ;
    return NT_STATUS_INVALID_PARAMETER;
  }
  
  DEBUG( 5, ("pgsqlsam_select_by_field: getting data where %d = %s(nonescaped)\n", field, sname) ) ;
  
  /* Escape sname */
  esc = malloc(strlen(sname) * 2 + 1);
  if ( !esc )
  {
    DEBUG(0, ("Can't allocate memory to store escaped name\n"));
    return NT_STATUS_NO_MEMORY; 
  }
  
  //tmp_sname = smb_xstrdup(sname);
  PQescapeString( esc, sname, strlen(sname) ) ;
  
  query = sql_account_query_select(data->location, True, field, esc);
  
  /* Do it */
  DEBUG( 5, ("Executing query %s\n", query) ) ;
  result = PQexec( data->handle, query ) ;
  
  /* Result? */
  if ( result == NULL )
  {
    DEBUG( 0, ("Error executing %s, %s\n", query, PQerrorMessage( data->handle ) ) ) ;
    retval = NT_STATUS_UNSUCCESSFUL ;
  }
  else if ( PQresultStatus( result ) != PGRES_TUPLES_OK )
  {
    DEBUG( 0, ("Error executing %s, %s\n", query, PQresultErrorMessage( result ) ) ) ;
    retval = NT_STATUS_UNSUCCESSFUL ;
  }
  else
  {
    retval = row_to_sam_account( result, 0, user ) ;
  }
  
  SAFE_FREE( esc   ) ;
  SAFE_FREE( query ) ;
  
  PQclear( result ) ;
  
  return retval ;
}
示例#5
0
	void submit(SQLQuery *req, const std::string& q, const ParamM& p)
	{
		std::string res;
		for(std::string::size_type i = 0; i < q.length(); i++)
		{
			if (q[i] != '$')
				res.push_back(q[i]);
			else
			{
				std::string field;
				i++;
				while (i < q.length() && isalnum(q[i]))
					field.push_back(q[i++]);
				i--;

				ParamM::const_iterator it = p.find(field);
				if (it != p.end())
				{
					std::string parm = it->second;
					std::vector<char> buffer(parm.length() * 2 + 1);
#ifdef PGSQL_HAS_ESCAPECONN
					int error;
					size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
					if (error)
						ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
#else
					size_t escapedsize = PQescapeString(&buffer[0], parm.data(), parm.length());
#endif
					res.append(&buffer[0], escapedsize);
				}
			}
		}
		submit(req, res);
	}
示例#6
0
	void submit(SQLQuery *req, const std::string& q, const ParamL& p)
	{
		std::string res;
		unsigned int param = 0;
		for(std::string::size_type i = 0; i < q.length(); i++)
		{
			if (q[i] != '?')
				res.push_back(q[i]);
			else
			{
				if (param < p.size())
				{
					std::string parm = p[param++];
					std::vector<char> buffer(parm.length() * 2 + 1);
#ifdef PGSQL_HAS_ESCAPECONN
					int error;
					size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
					if (error)
						ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
#else
					size_t escapedsize = PQescapeString(&buffer[0], parm.data(), parm.length());
#endif
					res.append(&buffer[0], escapedsize);
				}
			}
		}
		submit(req, res);
	}
示例#7
0
/*
 * cmd_escapestring: certain strings sent to a database should be properly
 *  escaped -- for instance, quotes need to be escaped to insure that 
 *  a query string is properly formatted.  cmd_escapestring does whatever
 *  is necessary to escape the special characters in a string. 
 *
 * Inputs:
 *  cmd->argv[0]: connection name
 *  cmd->argv[1]: string to escape
 *
 * Returns:
 *  this command CANNOT fail.  The return string is null-terminated and 
 *  stored in the data field of the modret_t structure.
 *
 * Notes:
 *  Different languages may escape different characters in different ways.
 *  A backend should handle this correctly, where possible.  If there is
 *  no client library function to do the string conversion, it is strongly
 *  recommended that the backend module writer do whatever is necessry (read
 *  the database documentation and figure it out) to do the conversion
 *  themselves in this function.
 *
 *  A backend MUST supply a working escapestring implementation.  Simply
 *  copying the data from argv[0] into the data field of the modret allows
 *  for possible SQL injection attacks when this backend is used.
 */
MODRET cmd_escapestring(cmd_rec * cmd) {
  conn_entry_t *entry = NULL;
  db_conn_t *conn = NULL;
  modret_t *cmr = NULL;
  char *unescaped = NULL;
  char *escaped = NULL;
  cmd_rec *close_cmd;
  size_t unescaped_len = 0;
#ifdef HAVE_POSTGRES_PQESCAPESTRINGCONN
  int pgerr = 0;
#endif

  sql_log(DEBUG_FUNC, "%s", "entering \tpostgres cmd_escapestring");

  _sql_check_cmd(cmd, "cmd_escapestring");

  if (cmd->argc != 2) {
    sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_escapestring");
    return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request");
  }

  /* get the named connection */
  entry = _sql_get_connection(cmd->argv[0]);
  if (!entry) {
    sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_escapestring");
    return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
      "unknown named connection");
  }

  conn = (db_conn_t *) entry->data;

  /* Make sure the connection is open. */
  cmr = cmd_open(cmd);
  if (MODRET_ERROR(cmr)) {
    sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_escapestring");
    return cmr;
  }

  unescaped = cmd->argv[1];
  unescaped_len = strlen(unescaped);
  escaped = (char *) pcalloc(cmd->tmp_pool, sizeof(char) *
    (unescaped_len * 2) + 1);

#ifdef HAVE_POSTGRES_PQESCAPESTRINGCONN
  PQescapeStringConn(conn->postgres, escaped, unescaped, unescaped_len, &pgerr);
  if (pgerr != 0) {
    sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_escapestring");
    return _build_error(cmd, conn);
  }
#else
  PQescapeString(escaped, unescaped, unescaped_len);
#endif

  close_cmd = _sql_make_cmd(cmd->tmp_pool, 1, entry->name);
  cmd_close(close_cmd);
  SQL_FREE_CMD(close_cmd);

  sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_escapestring");
  return mod_create_data(cmd, (void *) escaped);
}
示例#8
0
/*
 * get_comma_elts
 *
 * Return the elements of an eary as a (freshly allocated) single string, in
 * single quotes, separated by commas and properly escaped for insertion in an
 * SQL statement.
 */
char *
get_comma_elts(eary *eary)
{
	char	   *ret,
			   *ptr;
	int			i,
				length = 0;

	if (eary->num == 0)
		return mystrdup("");

	/*
	 * PQescapeString wants 2 * length + 1 bytes of breath space.  Add two
	 * chars per element for the single quotes and one for the comma.
	 */
	for (i = 0; i < eary->num; i++)
		length += strlen(eary->array[i]);

	ret = (char *) myalloc(length * 2 + 4 * eary->num);
	ptr = ret;

	for (i = 0; i < eary->num; i++)
	{
		if (i != 0)
			sprintf(ptr++, ",");
		sprintf(ptr++, "'");
		ptr += PQescapeString(ptr, eary->array[i], strlen(eary->array[i]));
		sprintf(ptr++, "'");
	}

	return ret;
}
示例#9
0
static const char *dbd_pgsql_escape(apr_pool_t *pool, const char *arg,
                                    apr_dbd_t *sql)
{
    size_t len = strlen(arg);
    char *ret = apr_palloc(pool, 2*len + 2);
    PQescapeString(ret, arg, len);
    return ret;
}
示例#10
0
string CDBManager::EscapeString(string strsource)
{
	char *ch = new char[strsource.length() + 50];
    PQescapeString (ch,strsource.c_str(),strsource.length());
	string strtmp = ch;
	delete [] ch;
    return strtmp;
}
示例#11
0
QString QgsShapeFile::getFeatureClass(){
  OGRFeature *feat = ogrLayer->GetNextFeature();
  if(feat){
    OGRGeometry *geom = feat->GetGeometryRef();
    if(geom){
      geom_type = QString(geom->getGeometryName());
			char * esc_str = new char[geom_type.length()*2+1];
			PQescapeString(esc_str, (const char *)geom_type, geom_type.length());
			geom_type = QString(esc_str);
			
			delete[] esc_str;
			
      QString file(filename);
      file.replace(file.length()-3, 3, "dbf");
      // open the dbf file
      std::ifstream dbf((const char*)file, std::ios::in | std::ios::binary);
      // read header
      DbaseHeader dbh;
      dbf.read((char *)&dbh, sizeof(dbh));

      Fda fda;
      QString str_type = "varchar(";
      for(int field_count = 0, bytes_read = sizeof(dbh); bytes_read < dbh.size_hdr-1; field_count++, bytes_read +=sizeof(fda)){
      	dbf.read((char *)&fda, sizeof(fda));
        switch(fda.field_type){
          case 'N': if((int)fda.field_decimal>0)
                      column_types.push_back("float");
                    else
                      column_types.push_back("int");          
                    break;
          case 'F': column_types.push_back("float");
                    break;                    
          case 'D': column_types.push_back("date");
                    break;
          case 'C': 
                    str_type= QString("varchar(%1)").arg(fda.field_length);
                    column_types.push_back(str_type);
                    break;
          case 'L': column_types.push_back("boolean");
                    break;
          default:
                    column_types.push_back("varchar(256)");
                    break;
        }
      }
      dbf.close();
      int numFields = feat->GetFieldCount();
      for(int n=0; n<numFields; n++)
        column_names.push_back(feat->GetFieldDefnRef(n)->GetNameRef());
      
    }else valid = false;
    delete feat;
  }else valid = false;
  
  ogrLayer->ResetReading();    
  return valid?geom_type:NULL;
}
示例#12
0
文件: pdb_pgsql.c 项目: hajuuk/R7000
static NTSTATUS pgsqlsam_delete_sam_account( struct pdb_methods *methods, SAM_ACCOUNT *sam_pass )
{
  struct pdb_pgsql_data *data ;
  
  const char *sname = pdb_get_username( sam_pass ) ;
  char *esc ;
  char *query ;
  
  PGresult *result ;
  NTSTATUS retval ;
  
  SET_DATA(data, methods);
  
  if ( !sname )
  {
    DEBUG( 0, ("invalid name specified\n") ) ;
    return NT_STATUS_INVALID_PARAMETER ;
  }
  
  /* Escape sname */
  esc = malloc(strlen(sname) * 2 + 1);
  if ( !esc )
  {
    DEBUG(0, ("Can't allocate memory to store escaped name\n"));
    return NT_STATUS_NO_MEMORY;
  }
  
  PQescapeString( esc, sname, strlen(sname) ) ;
  
  query = sql_account_query_delete(data->location, esc);
  
  /* Do it */
  result = PQexec( data->handle, query ) ;
  
  if ( result == NULL )
  {
    DEBUG( 0, ("Error executing %s, %s\n", query, PQerrorMessage( data->handle ) ) ) ;
    retval = NT_STATUS_UNSUCCESSFUL ;
  }
  else if ( PQresultStatus( result ) != PGRES_COMMAND_OK )
  {
    DEBUG( 0, ("Error executing %s, %s\n", query, PQresultErrorMessage( result ) ) ) ;
    retval = NT_STATUS_UNSUCCESSFUL ;
  }
  else
  {
    DEBUG( 5, ("User '%s' deleted\n", sname) ) ;
    retval = NT_STATUS_OK ;
  }
  
  SAFE_FREE( esc ) ;
  SAFE_FREE( query ) ;
  
  return retval ;
}
示例#13
0
uid_t getUIDByCookie(const string &cookie, int &err, PGconn *dbconn)
{

    err = PC_UNKNOWNERROR;
    PGconn *conn = dbconn;
    uid_t userID;

    if (PQstatus(conn) != CONNECTION_OK)
    {
        err = PC_DBERROR;
        return userID;
    }

    if (userID.size() > MAXLEN_COOKIESIZE)
    {
        err = PC_INPUTFORMATERROR;
        return userID;
    }

    //escapte string of cookie
    char ccook[2 * cookie.size() + 1];
    PQescapeString(ccook, cookie.c_str(), cookie.size());

    string t = ccook;

    string sql = "SELECT user_id FROM users WHERE cookie ='"+t+"'";

    //Exec the SQL query
    PGresult *res = NULL;
    res = PQexec(conn, sql.c_str());

    if (PQresultStatus(res) != PGRES_TUPLES_OK)
    {//If exection failed
        err = PC_DBERROR;
        PQclear(res);
        return userID;
    }

    if (PQntuples(res) == 0)
    {//If userID doesn't match password
        err = PC_MISTATCH;
        PQclear(res);
        return userID;
    }

    userID = PQgetvalue(res, 0, 0);

    //Updated by: Lai
    err = PC_SUCCESSFUL;

    PQclear(res);

    return userID;
}
示例#14
0
    // Sets *to to the escaped value
    void psMysqlConnection::Escape(csString& to, const char *from)
    {
        size_t len = strlen(from);
        char* buff = new char[len*2+1];

        if(conn)
            PQescapeStringConn(conn, buff, from, len, NULL);
        else
            PQescapeString(buff, from, len);
        to = buff;
        delete[] buff;
    }
示例#15
0
bool queryCallback(void *p_context, int p_placeholder, DBBuffer &p_output)
{
    QueryMetadata *t_query_metadata;
    t_query_metadata = (QueryMetadata *)p_context;

    DBString t_parameter_value;
    t_parameter_value = t_query_metadata -> arguments[p_placeholder - 1];

    void *t_escaped_string;
    t_escaped_string = NULL;

    size_t t_escaped_string_length;
    t_escaped_string_length = 0;

    if (t_parameter_value . isbinary)
    {
        t_escaped_string = PQescapeBytea((const unsigned char *)t_parameter_value . sptr, t_parameter_value . length, &t_escaped_string_length);
        if (t_escaped_string == NULL)
            return false;

        // PQescapeBytea appends an extra null char to the end of the escaped string, disregard this.
        t_escaped_string_length--;
    }
    else
    {
        if (t_parameter_value . length != 0)
        {
            t_escaped_string = malloc((t_parameter_value . length * 2) + 1);
            t_escaped_string_length = PQescapeString((char *)t_escaped_string, t_parameter_value . sptr, t_parameter_value . length);
        }
    }

    p_output . ensure(t_escaped_string_length + 2);
    memcpy(p_output . getFrontier(), "'", 1);
    p_output . advance(1);

    if (t_escaped_string != NULL)
    {
        memcpy(p_output . getFrontier(), t_escaped_string, t_escaped_string_length);
        p_output . advance(t_escaped_string_length);
    }

    memcpy(p_output . getFrontier(), "'", 1);
    p_output . advance(1);

    if (t_parameter_value . isbinary)
        PQfreemem(t_escaped_string);
    else
        free(t_escaped_string);

    return true;
}
示例#16
0
文件: pgconn.c 项目: berkus/moto
char *
pgconn_escapeBytes(PGConnection *conn, UnArray *arr){
   int length;
   char *newstring;

   if (arr == NULL)
      THROW_D("NullPointerException");

   newstring = (char*)emalloc((length = arr->meta.length)*2 + 1);
   PQescapeString(newstring, &arr->ya.data[0], length);

   return newstring;
}
示例#17
0
文件: pgconn.c 项目: berkus/moto
char *
pgconn_escape(PGConnection *conn, char *string)
{
   int length;
   char *newstring;

   if (string == NULL)
      THROW_D("NullPointerException");

   newstring = (char*)emalloc((length = strlen(string))*2 + 1);
   PQescapeString(newstring, string, length);

   return newstring;
}
示例#18
0
文件: pgsql.c 项目: AndyLavr/gammu
/* Assume 2 * strlen(from) + 1 buffer in to */
char * SMSDPgSQL_QuoteString(GSM_SMSDConfig * Config, const char *from)
{
	char *to;
	int ret =0;
	to = malloc(strlen(from)*2+3);
	to[0] = '\'';
	to[1] = '\0';
#ifdef HAVE_PQESCAPESTRINGCONN
	PQescapeStringConn(Config->conn.pg, to+1, from, strlen(from), &ret);
#else
	PQescapeString(to+1, from, strlen(from));
#endif
	strcat(to, "'");
	return to;
}
示例#19
0
sql_stream&
sql_stream::operator<<(const char* p)
{
  check_binds();
  size_t len=p?strlen(p):0;
  char local_buf[1024+1];
  char* buf;
  if (len<(sizeof(local_buf)-1)/2)
    buf=local_buf;
  else
    buf=(char*)malloc(2*len+1);
  int escaped_size=PQescapeString(buf, p, len);
  buf[escaped_size]='\0';

  /* Very bad kludge here: if the bind parameter inside the query
     doesn't start with a quote, we add quotes around the value at this point.
     TODO: make all the callers NOT enclose the values, since it's a
     problem for backends that support real bind parameters
     (oracle) */
  int pos = m_vars[m_nArgPos].pos();
  if (pos>0 && m_queryBuf[pos-1]!='\'') {
    //    DBG_PRINTF(5,"bindpos=%d", pos);
    if (p) {
      char placeholder[2+escaped_size+1];
      placeholder[0]='\'';
      strcpy(placeholder+1, buf);
      placeholder[1+escaped_size]='\'';
      placeholder[1+escaped_size+1]='\0';
      replace_placeholder(m_nArgPos, placeholder, escaped_size+2);
    }
    else {
      // null pointer => null sql value
      replace_placeholder(m_nArgPos, "null", 4);
    }
  }
  else {
    if (p)
      replace_placeholder(m_nArgPos, buf, escaped_size);
    else
      replace_placeholder(m_nArgPos, "null", 4);
  }

  if (buf!=local_buf)
    free(buf);

  next_bind();
  return *this;
}
示例#20
0
void
sql_write_fields::add(const char* field, const QString value, int maxlength)
{
    bool alloc=false;
    if (m_fields_nb++>0) {
        m_values+=",";
        m_fields+=",";
    }
    const char *trunc_value;
    QByteArray qvalue;
    if (m_utf8)
        qvalue=value.toUtf8();
    else
        qvalue=value.toLocal8Bit();

    trunc_value=(const char*)qvalue;

    if (maxlength) {
        if (strlen(trunc_value) > (uint)maxlength) {
            char* p = (char*)malloc(maxlength+1);
            alloc=true;
            strncpy (p, trunc_value, maxlength);
            p[maxlength] = '\0';
            trunc_value = p;
        }
    }

    char local_value[1024];
    char* dest;
    int value_len=strlen(trunc_value);
    if (value_len*2<(int)sizeof(local_value)-1)
        dest=local_value;
    else
        dest=(char*)malloc(1+value_len*2);
    PQescapeString (dest, trunc_value, value_len);

    if (m_utf8)
        m_values+=QString("'") + QString::fromUtf8(dest) + QString("'");
    else
        m_values+=QString("'") + QString::fromLocal8Bit(dest) + QString("'");

    m_fields+=field;
    if (dest!=local_value)
        free (dest);
    if (alloc)
        free ((void*)trunc_value);
}
示例#21
0
// field cmp <string value>
void
sql_query::add_clause(const QString field, const QString value, const char *cmp)
{
    char local_value[1024];
    char* dest;
    if (m_num_clauses++>0) {
        m_where += " AND ";
    }
    int value_len=value.length();
    if (value_len*2<(int)sizeof(local_value)-1)
        dest=local_value;
    else
        dest=(char*)malloc(1+value_len*2);
    QByteArray qba = value.toLatin1();
    PQescapeString(dest, qba.constData(), value_len); // FIXME ENCODING
    m_where += field + QString(cmp) + QString("'") + QString(dest) + QString("'");
    if (dest!=local_value)
        free(dest);
}
示例#22
0
/* Routine to escape the 'dangerous' characters that would otherwise
 * corrupt the INSERT string: ', \, and "
 * Also PQescapeString does not place the ' around the string. So we have
 * to do this manually
 */
static const char *log_sql_pgsql_escape(const char *from_str, apr_pool_t *p, 
								logsql_dbconnection *db)
{
	char *temp;
	if (!from_str)
		return NULL;
	else {
	  	char *to_str;
		unsigned long length = strlen(from_str);
		unsigned long retval;

		/* Pre-allocate a new string that could hold twice the original, which would only
		 * happen if the whole original string was 'dangerous' characters. 
		 * And forsee the space for the 2 '
		 */
		temp = to_str = (char *) apr_palloc(p, length * 2 + 3);
		if (!to_str) {
			return from_str;
		}

		*temp = '\'';
		temp++;
		
		retval = PQescapeString(temp, from_str, length);
		
		/* avoid the string to be tolong for the sql database*/
		if (retval > 250) retval = 250;
		
		*(temp+retval) = '\'';
		*(temp+retval+1) = '\0';
		
		/* We must always return the to_str, because we always need the ' added */
//		if (retval)
		  return to_str;
//		else
//		  return from_str;
	}
}
示例#23
0
/*
 * cmd_escapestring: certain strings sent to a database should be properly
 *  escaped -- for instance, quotes need to be escaped to insure that 
 *  a query string is properly formatted.  cmd_escapestring does whatever
 *  is necessary to escape the special characters in a string. 
 *
 * Inputs:
 *  cmd->argv[0]: connection name
 *  cmd->argv[1]: string to escape
 *
 * Returns:
 *  this command CANNOT fail.  The return string is null-terminated and 
 *  stored in the data field of the modret_t structure.
 *
 * Notes:
 *  Different languages may escape different characters in different ways.
 *  A backend should handle this correctly, where possible.  If there is
 *  no client library function to do the string conversion, it is strongly
 *  recommended that the backend module writer do whatever is necessry (read
 *  the database documentation and figure it out) to do the conversion
 *  themselves in this function.
 *
 *  A backend MUST supply a working escapestring implementation.  Simply
 *  copying the data from argv[0] into the data field of the modret allows
 *  for possible SQL injection attacks when this backend is used.
 */
MODRET cmd_escapestring(cmd_rec * cmd) {
  conn_entry_t *entry = NULL;
  db_conn_t *conn = NULL;
  char *unescaped = NULL;
  char *escaped = NULL;

  sql_log(DEBUG_FUNC, "%s", "entering \tpostgres cmd_escapestring");

  _sql_check_cmd(cmd, "cmd_escapestring");

  if (cmd->argc != 2) {
    sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_escapestring");
    return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request");
  }

  /* get the named connection */
  entry = _sql_get_connection(cmd->argv[0]);
  if (!entry) {
    sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_escapestring");
    return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
      "unknown named connection");
  }

  conn = (db_conn_t *) entry->data;

  /* Note: the PQescapeString() function appeared in the C API as of
   * Postgres-7.2.
   */
  unescaped = cmd->argv[1];
  escaped = (char *) pcalloc(cmd->tmp_pool, sizeof(char) *
    (strlen(unescaped) * 2) + 1);

  PQescapeString(escaped, unescaped, strlen(unescaped));

  sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_escapestring");
  return mod_create_data(cmd, (void *) escaped);
}
示例#24
0
bool PostgreSQLStore::set( int msgSeqNum, const std::string& msg )
throw ( IOException )
{
  char* msgCopy = new char[ (msg.size() * 2) + 1 ];
  PQescapeString( msgCopy, msg.c_str(), msg.size() );

  std::stringstream queryString;
  queryString << "INSERT INTO messages "
  << "(beginstring, sendercompid, targetcompid, session_qualifier, msgseqnum, message) "
  << "VALUES ("
  << "'" << m_sessionID.getBeginString().getValue() << "',"
  << "'" << m_sessionID.getSenderCompID().getValue() << "',"
  << "'" << m_sessionID.getTargetCompID().getValue() << "',"
  << "'" << m_sessionID.getSessionQualifier() << "',"
  << msgSeqNum << ","
  << "'" << msgCopy << "')";

  delete [] msgCopy;

  PostgreSQLQuery query( queryString.str() );
  if( !m_pConnection->execute(query) )
  {
    std::stringstream queryString2;
    queryString2 << "UPDATE messages SET message='" << msg << "' WHERE "
    << "beginstring=" << "'" << m_sessionID.getBeginString().getValue() << "' and "
    << "sendercompid=" << "'" << m_sessionID.getSenderCompID().getValue() << "' and "
    << "targetcompid=" << "'" << m_sessionID.getTargetCompID().getValue() << "' and "
    << "session_qualifier=" << "'" << m_sessionID.getSessionQualifier() << "' and "
    << "msgseqnum=" << msgSeqNum;
    PostgreSQLQuery query2( queryString2.str() );
    if( !m_pConnection->execute(query2) )
      query2.throwException();
  }

  return true;
}
示例#25
0
static void _st_pgsql_convert_filter_recursive(st_driver_t drv, st_filter_t f, char **buf, unsigned int *buflen, unsigned int *nbuf) {
    st_filter_t scan;
    int vlen;
    char *cval;

    switch(f->type) {
        case st_filter_type_PAIR:
            /* do sql escaping for apostrophes */
            cval = (char *) malloc(sizeof(char) * ((strlen(f->val) * 2) + 1));
            vlen = PQescapeString(cval, f->val, strlen(f->val));

            PGSQL_SAFE((*buf), *buflen + 12 + vlen - strlen(f->val), *buflen);
            *nbuf += sprintf(&((*buf)[*nbuf]), "( \"%s\" = \'%s\' ) ", f->key, f->val);
            free(cval);

            break;

        case st_filter_type_AND:
            PGSQL_SAFE((*buf), *buflen + 2, *buflen);
            *nbuf += sprintf(&((*buf)[*nbuf]), "( ");

            for(scan = f->sub; scan != NULL; scan = scan->next) {
                _st_pgsql_convert_filter_recursive(drv, scan, buf, buflen, nbuf);

                if(scan->next != NULL) {
                    PGSQL_SAFE((*buf), *buflen + 4, *buflen);
                    *nbuf += sprintf(&((*buf)[*nbuf]), "AND ");
                }
            }

            PGSQL_SAFE((*buf), *buflen + 2, *buflen);
            *nbuf += sprintf(&((*buf)[*nbuf]), ") ");

            return;

        case st_filter_type_OR:
            PGSQL_SAFE((*buf), *buflen + 2, *buflen);
            *nbuf += sprintf(&((*buf)[*nbuf]), "( ");

            for(scan = f->sub; scan != NULL; scan = scan->next) {
                _st_pgsql_convert_filter_recursive(drv, scan, buf, buflen, nbuf);

                if(scan->next != NULL) {
                    PGSQL_SAFE((*buf), *buflen + 3, *buflen);
                    *nbuf += sprintf(&((*buf)[*nbuf]), "OR ");
                }
            }

            PGSQL_SAFE((*buf), *buflen + 2, *buflen);
            *nbuf += sprintf(&((*buf)[*nbuf]), ") ");

            return;

        case st_filter_type_NOT:
            PGSQL_SAFE((*buf), *buflen + 6, *buflen);
            *nbuf += sprintf(&((*buf)[*nbuf]), "( NOT ");

            _st_pgsql_convert_filter_recursive(drv, f->sub, buf, buflen, nbuf);

            PGSQL_SAFE((*buf), *buflen + 2, *buflen);
            *nbuf += sprintf(&((*buf)[*nbuf]), ") ");

            return;
    }
}
示例#26
0
static switch_status_t my_on_reporting(switch_core_session_t *session)
{
    switch_channel_t *channel = switch_core_session_get_channel(session);
    switch_status_t status = SWITCH_STATUS_SUCCESS;
    char *values = NULL, *tmp = NULL, *pq_var = NULL;
    const char *var = NULL;
    cdr_field_t *cdr_field = NULL;
    switch_size_t len, offset;

    if (globals.shutdown) {
        return SWITCH_STATUS_SUCCESS;
    }

    if (!((globals.legs & CDR_LEG_A) && (globals.legs & CDR_LEG_B))) {
        if ((globals.legs & CDR_LEG_A)) {
            if (switch_channel_get_originator_caller_profile(channel)) {
                return SWITCH_STATUS_SUCCESS;
            }
        } else {
            if (switch_channel_get_originatee_caller_profile(channel)) {
                return SWITCH_STATUS_SUCCESS;
            }
        }
    }

    if (switch_dir_make_recursive(globals.spool_dir, SWITCH_DEFAULT_DIR_PERMS, switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error creating %s\n", globals.spool_dir);
        return SWITCH_STATUS_FALSE;
    }

    if (globals.debug) {
        switch_event_t *event;
        if (switch_event_create(&event, SWITCH_EVENT_COMMAND) == SWITCH_STATUS_SUCCESS) {
            char *buf;
            switch_channel_event_set_data(channel, event);
            switch_event_serialize(event, &buf, SWITCH_FALSE);
            switch_assert(buf);
            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "CHANNEL_DATA:\n%s\n", buf);
            switch_event_destroy(&event);
            switch_safe_free(buf);
        }
    }

    switch_zmalloc(values, 1);
    offset = 0;

    for (cdr_field = globals.db_schema->fields; cdr_field->var_name; cdr_field++) {
        if ((var = switch_channel_get_variable(channel, cdr_field->var_name))) {
            /* Allocate sufficient buffer for PQescapeString */
            len = strlen(var);
            tmp = switch_core_session_alloc(session, len * 2 + 1);
            PQescapeString(tmp, var, len);
            var = tmp;
        }

        if (cdr_field->quote) {
            if ((cdr_field->not_null == SWITCH_FALSE) && zstr(var)) {
                pq_var = switch_mprintf("null,", var);
            } else {
                pq_var = switch_mprintf("'%s',", var);
            }
        } else {
            pq_var = switch_mprintf("%s,", var);
        }

        /* Resize values buffer to accomodate next var */
        len = strlen(pq_var);
        tmp = realloc(values, offset + len);
        values = tmp;
        memcpy(values + offset, pq_var, len);
        switch_safe_free(pq_var);
        offset += len;
    }
    *(values + --offset) = '\0';

    insert_cdr(values);
    switch_safe_free(values);

    return status;
}
示例#27
0
/* --------------------------------
 * pool_query_cache_register() - register query cache to the SystemDB
 *
 * returns 0 on sucess, -1 otherwise
 * --------------------------------
 */
int
pool_query_cache_register(char kind,
						  POOL_CONNECTION *frontend,
						  char *database,
						  char *data,
						  int data_len,
						  char *query)
{
	int ret;
	int send_len;

	if (! system_db_connection_exists())
		return -1;
	if (! CACHE_TABLE_INFO.has_prepared_statement)
		define_prepared_statements();

	switch (kind)
	{
		case 'T':				/* RowDescription */
		{
			/* for all SELECT result data from the backend, 'T' must come first */
			if (query_cache_info != NULL)
			{
				pool_error("pool_query_cache_register: received RowDescription in the wrong order");
				free_query_cache_info();
				return -1;
			}

			pool_debug("pool_query_cache_register: saving cache for query: \"%s\"", query);

			/* initialize query_cache_info and save the query */
			ret = init_query_cache_info(frontend, database, query);
			if (ret)
				return ret;

			/* store data into the cache */
			write_cache(&kind, 1);
			send_len = htonl(data_len + sizeof(int));
			write_cache(&send_len, sizeof(int));
			write_cache(data, data_len);

			break;
		}

		case 'D':				/* DataRow */
		{
			/* for all SELECT result data from the backend, 'T' must come first */
			if (query_cache_info == NULL)
			{
				pool_error("pool_query_cache_register: received DataRow in the wrong order");
				return -1;
			}

			write_cache(&kind, 1);
			send_len = htonl(data_len + sizeof(int));
			write_cache(&send_len, sizeof(int));
			write_cache(data, data_len);

			break;
		}

		case 'C':				/* CommandComplete */
		{
			PGresult *pg_result = NULL;
			char *escaped_query = NULL;
			size_t escaped_query_len;
			time_t now = time(NULL);
			char *values[5];
			int values_len[5];
			int values_format[5];
			int i;

			/* for all SELECT result data from the backend, 'T' must come first */
			if (query_cache_info == NULL)
			{
				pool_error("pool_query_cache_register: received CommandComplete in the wrong order");
				return -1;
			}

			/* pack CommandComplete data into the cache */
			write_cache(&kind, 1);
			send_len = htonl(data_len + sizeof(int));
			write_cache(&send_len, sizeof(int));
			write_cache(data, data_len);

			query_cache_info->create_time = pq_time_to_str(now);
			if (malloc_failed(query_cache_info->create_time))
			{
				free_query_cache_info();
				return -1;
			}

			escaped_query = (char *)malloc(strlen(query_cache_info->query) * 2 + 1);
			if (malloc_failed(escaped_query))
			{
				free_query_cache_info();
				return -1;
			}

/* 			escaped_query_len = PQescapeStringConn(system_db_info->pgconn, */
/* 												   escaped_query, */
/* 												   query_cache_info->query, */
/* 												   strlen(query_cache_info->query))); */
			escaped_query_len = PQescapeString(escaped_query, query_cache_info->query, strlen(query_cache_info->query));

			/* all the result data have been received. store into the SystemDB */
			values[0] = strdup(query_cache_info->md5_query);
			values[1] = strdup(escaped_query);
			values[2] = (char *)malloc(query_cache_info->cache_offset);
			memcpy(values[2], query_cache_info->cache, query_cache_info->cache_offset);
			values[3] = strdup(query_cache_info->db_name);
			values[4] = strdup(query_cache_info->create_time);
			for (i = 0; i < 5; i++)
			{
				if (malloc_failed(values[i]))
				{
					pool_error("pool_query_cache_register: malloc() failed");
					free_query_cache_info();
					{
						int j;
						for (j = 0; j < i; j++)
							free(values[j]);
					}
					return -1;
				}

				values_len[i] = strlen(values[i]);
			}
			values_format[0] = values_format[1] = values_format[3] = values_format[4] = 0;
			values_format[2] = 1;
			values_len[2] = query_cache_info->cache_offset;

			pg_result = PQexecPrepared(system_db_info->pgconn,
									   CACHE_TABLE_INFO.register_prepared_statement,
									   5,
									   (const char * const *)values,
									   values_len,
									   values_format,
									   0);
			if (!pg_result || PQresultStatus(pg_result) != PGRES_COMMAND_OK)
			{
				pool_error("pool_query_cache_register: PQexecPrepared() failed. reason: %s",
						   PQerrorMessage(system_db_info->pgconn));

				PQclear(pg_result);
				PQfreemem(escaped_query);
				free_query_cache_info();
				for (i = 0; i < 5; i++)
					free(values[i]);
				return -1;
			}

			PQclear(pg_result);
			PQfreemem(escaped_query);
			for (i = 0; i < 5; i++)
				free(values[i]);
			free_query_cache_info();

			break;
		}

		case 'E':
		{
			pool_debug("pool_query_cache_register: received 'E': free query cache buffer");

			pool_close_libpq_connection();
			free_query_cache_info();

			break;
		}
	}

	return 0;
}
示例#28
0
	SQLerror DoQuery(SQLrequest &req)
	{
		if((status == WREAD) || (status == WWRITE))
		{
			if(!qinprog)
			{
				/* Parse the command string and dispatch it */

				/* Pointer to the buffer we screw around with substitution in */
				char* query;
				/* Pointer to the current end of query, where we append new stuff */
				char* queryend;

				/* Total length of the unescaped parameters */
				unsigned long maxparamlen, paramcount;

				/* The length of the longest parameter */
				maxparamlen = 0;

				for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
				{
					if (i->size() > maxparamlen)
						maxparamlen = i->size();
				}

				/* How many params are there in the query? */
				paramcount = count(req.query.q.c_str(), '?');

				/* This stores copy of params to be inserted with using numbered params 1;3B*/
				ParamL paramscopy(req.query.p);

				/* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
				 * sizeofquery + (maxtotalparamlength*2) + 1
				 *
				 * The +1 is for null-terminating the string for PQsendQuery()
				 */

				query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
				queryend = query;

				/* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
				 * the parameters into it...
				 */

				for(unsigned int i = 0; i < req.query.q.length(); i++)
				{
					if(req.query.q[i] == '?')
					{
						/* We found a place to substitute..what fun.
						 * Use the PgSQL calls to escape and write the
						 * escaped string onto the end of our query buffer,
						 * then we "just" need to make sure queryend is
						 * pointing at the right place.
						 */

						/* Is it numbered parameter?
						 */

						bool numbered;
						numbered = false;

						/* Numbered parameter number :|
						 */
						unsigned int paramnum;
						paramnum = 0;

						/* Let's check if it's a numbered param. And also calculate it's number.
						 */

						while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
						{
							numbered = true;
							++i;
							paramnum = paramnum * 10 + req.query.q[i] - '0';
						}

						if (paramnum > paramscopy.size() - 1)
						{
							/* index is out of range!
							 */
							numbered = false;
						}

						if (numbered)
						{
							int error = 0;
							size_t len = 0;

#ifdef PGSQL_HAS_ESCAPECONN
							len = PQescapeStringConn(sql, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length(), &error);
#else
							len = PQescapeString         (queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
#endif
							if (error)
							{
								ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
							}

							/* Incremenet queryend to the end of the newly escaped parameter */
							queryend += len;
						}
						else if (req.query.p.size())
						{
							int error = 0;
							size_t len = 0;

#ifdef PGSQL_HAS_ESCAPECONN
							len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
#else
							len = PQescapeString         (queryend, req.query.p.front().c_str(), req.query.p.front().length());
#endif
							if(error)
							{
								ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
							}

							/* Incremenet queryend to the end of the newly escaped parameter */
							queryend += len;

							/* Remove the parameter we just substituted in */
							req.query.p.pop_front();
						}
						else
						{
							ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Found a substitution location but no parameter to substitute :|");
							break;
						}
					}
					else
					{
						*queryend = req.query.q[i];
						queryend++;
					}
				}

				/* Null-terminate the query */
				*queryend = 0;
				req.query.q = query;

				if(PQsendQuery(sql, query))
				{
					qinprog = true;
					delete[] query;
					return SQLerror();
				}
				else
				{
					delete[] query;
					return SQLerror(SQL_QSEND_FAIL, PQerrorMessage(sql));
				}
			}
		}
		return SQLerror(SQL_BAD_CONN, "Can't query until connection is complete");
	}
示例#29
0
QString QgsShapeFile::getFeatureClass()
{
  // scan the whole layer to try to determine the geometry
  // type.
  qApp->processEvents();
  isMulti = scanGeometries();
  OGRFeatureH feat;
  // skip features without geometry
  while (( feat = OGR_L_GetNextFeature( ogrLayer ) ) != NULL )
  {
    if ( OGR_F_GetGeometryRef( feat ) )
      break;
  }
  if ( feat )
  {
    OGRGeometryH geom = OGR_F_GetGeometryRef( feat );
    if ( geom )
    {
      /* OGR doesn't appear to report geometry type properly
       * for a layer containing both polygon and multipolygon
       * entities
       *
      // get the feature type from the layer
      OGRFeatureDefn * gDef = ogrLayer->GetLayerDefn();
      OGRwkbGeometryType gType = gDef->GetGeomType();
      geom_type = QGis::qgisFeatureTypes[gType];
      */
      //geom_type = QString(geom->getGeometryName());
      //geom_type = "GEOMETRY";
      QgsDebugMsg( "Preparing to escape " + geom_type );
      char * esc_str = new char[geom_type.length()*2+1];
      PQescapeString( esc_str, geom_type.toUtf8(), geom_type.length() );
      geom_type = QString( esc_str );
      QgsDebugMsg( "After escaping, geom_type is : " + geom_type );
      delete[] esc_str;

      QString file( fileName );
      file.replace( file.length() - 3, 3, "dbf" );
      // open the dbf file
      std::ifstream dbf( file.toUtf8(), std::ios::in | std::ios::binary );
      // read header
      DbaseHeader dbh;
      dbf.read(( char * )&dbh, sizeof( dbh ) );
      // Check byte order
      if ( htonl( 1 ) == 1 )
      {
        /* DbaseHeader is stored in little-endian format.
         * The num_recs, size_hdr and size_rec fields must be byte-swapped when read
         * on a big-endian processor. Currently only size_hdr is used.
         */
        unsigned char *byte = reinterpret_cast<unsigned char *>( &dbh.size_hdr );
        unsigned char t = *byte; *byte = *( byte + 1 ); *( byte + 1 ) = t;
      }

      Fda fda;
      QString str_type = "varchar(";
      for ( int field_count = 0, bytes_read = sizeof( dbh ); bytes_read < dbh.size_hdr - 1; field_count++, bytes_read += sizeof( fda ) )
      {
        dbf.read(( char * )&fda, sizeof( fda ) );
        switch ( fda.field_type )
        {
          case 'N':
            if (( int )fda.field_decimal > 0 )
              column_types.push_back( "float" );
            else
              column_types.push_back( "int" );
            break;
          case 'F': column_types.push_back( "float" );
            break;
          case 'D': column_types.push_back( "date" );
            break;
          case 'C':
            str_type = QString( "varchar(%1)" ).arg( fda.field_length );
            column_types.push_back( str_type );
            break;
          case 'L': column_types.push_back( "boolean" );
            break;
          default:
            column_types.push_back( "varchar(256)" );
            break;
        }
      }
      dbf.close();
      int numFields = OGR_F_GetFieldCount( feat );
      for ( int n = 0; n < numFields; n++ )
      {
        QString s = codec->toUnicode( OGR_Fld_GetNameRef( OGR_F_GetFieldDefnRef( feat, n ) ) );
        column_names.push_back( s );
      }

    }
    else valid = false;
    OGR_F_Destroy( feat );
  }
  else valid = false;

  OGR_L_ResetReading( ogrLayer );
  return valid ? geom_type : QString::null;
}
示例#30
0
bool QgsShapeFile::insertLayer(QString dbname, QString schema, QString geom_col, QString srid, PGconn * conn, QProgressDialog * pro, bool &fin){
  connect(pro, SIGNAL(cancelled()), this, SLOT(cancelImport()));
  import_cancelled = false;
  bool result = true;

  QString query = "CREATE TABLE "+schema+"."+table_name+"(gid int4 PRIMARY KEY, ";
  for(int n=0; n<column_names.size() && result; n++){
    if(!column_names[n][0].isLetter())
      result = false;
		char * esc_str = new char[column_names[n].length()*2+1];
		PQescapeString(esc_str, (const char *)column_names[n].lower(), column_names[n].length());
    query += esc_str;
    query += " ";
    query += column_types[n];
    if(n<column_names.size()-1)
      query += ", ";
		delete[] esc_str;
  }
  query += " )";
  
  PGresult *res = PQexec(conn, (const char *)query);
  qWarning(query);
  if(PQresultStatus(res)!=PGRES_COMMAND_OK){
    // flag error and send query and error message to stdout on debug
    result = false;
    qWarning(PQresultErrorMessage(res));
  }
  else {
    PQclear(res);
  }
	
  query = "SELECT AddGeometryColumn(\'" + dbname + "\', \'" + table_name + "\', \'"+geom_col+"\', " + srid +
    ", \'" + geom_type + "\', 2)";            
  if(result) res = PQexec(conn, (const char *)query);
  if(PQresultStatus(res)!=PGRES_TUPLES_OK){
    result = false;    
  }
  else{
  	qWarning(query);
  	qWarning(PQresultErrorMessage(res));
  	PQclear(res);
  }

  //adding the data into the table
  for(int m=0;m<features && result; m++){
    if(import_cancelled){
      fin = true;
      break;
    }
    
    OGRFeature *feat = ogrLayer->GetNextFeature();
    if(feat){
      OGRGeometry *geom = feat->GetGeometryRef();
      if(geom){
        query = "INSERT INTO "+schema+"."+table_name+QString(" VALUES( %1, ").arg(m);
        
        int num = geom->WkbSize();
        char * geo_temp = new char[num*3];
        geom->exportToWkt(&geo_temp);
        QString geometry(geo_temp);

        QString quotes;
        for(int n=0; n<column_types.size(); n++){
          if(column_types[n] == "int" || column_types[n] == "float")
            quotes = " ";
          else
            quotes = "\'";
          query += quotes;
          
          // escape the string value
          QString val = feat->GetFieldAsString(n);
					char * esc_str = new char[val.length()*2+1];
					PQescapeString(esc_str, (const char *)val.lower(), val.length());
          
          // add escaped value to the query 
          query += esc_str;
          query += QString(quotes + ", ");
					
					delete[] esc_str;
        }
        query += QString("GeometryFromText(\'")+geometry+QString("\', ")+srid+QString("))");
        
        if(result)
          res = PQexec(conn, (const char *)query);
        if(PQresultStatus(res)!=PGRES_COMMAND_OK){
          // flag error and send query and error message to stdout on debug
          result = false;
          qWarning(PQresultErrorMessage(res));
        }
        else {
           PQclear(res);
        }
        
        pro->setProgress(pro->progress()+1);
        qApp->processEvents();
        delete[] geo_temp;
      }
      delete feat;
    }
  }
  ogrLayer->ResetReading();
  return result;
}