Ejemplo n.º 1
0
static PyObject*
key_name (PyObject* self, PyObject* args)
{
    int key;
	
    if (!PyArg_ParseTuple (args, "i", &key))
        return NULL;

    return Text_FromUTF8 (SDL_GetKeyName (key));	
}
Ejemplo n.º 2
0
static PyObject*
_device_geterror (PyObject* self)
{
    ALCenum error = alcGetError (PyDevice_AsDevice (self));
    switch (error)
    {
    case ALC_INVALID_ENUM:
        return Text_FromUTF8 ("invalid enumeration value");
    case ALC_INVALID_VALUE:
        return Text_FromUTF8 ("invalid value");
    case ALC_INVALID_DEVICE:
        return Text_FromUTF8 ("invalid device");
    case ALC_INVALID_CONTEXT:
        return Text_FromUTF8 ("invalid context");
    case ALC_OUT_OF_MEMORY:
        return Text_FromUTF8 ("insufficient memory");
    default:
        Py_RETURN_NONE;
    }
}
static PyObject *
qstring_get_encoding(qstringObject *self)
{
    const char *encoding = default_encoding;

    if (self->conn) {
        encoding = self->conn->codec;
    }

    return Text_FromUTF8(encoding);
}
Ejemplo n.º 4
0
static PyObject *
psyco_parse_dsn(PyObject *self, PyObject *args, PyObject *kwargs)
{
    char *err = NULL;
    PQconninfoOption *options = NULL, *o;
    PyObject *dict = NULL, *res = NULL, *dsn;

    static char *kwlist[] = {"dsn", NULL};
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O", kwlist, &dsn)) {
        return NULL;
    }

    Py_INCREF(dsn); /* for ensure_bytes */
    if (!(dsn = psycopg_ensure_bytes(dsn))) { goto exit; }

    options = PQconninfoParse(Bytes_AS_STRING(dsn), &err);
    if (options == NULL) {
        if (err != NULL) {
            PyErr_Format(ProgrammingError, "error parsing the dsn: %s", err);
            PQfreemem(err);
        } else {
            PyErr_SetString(OperationalError, "PQconninfoParse() failed");
        }
        goto exit;
    }

    if (!(dict = PyDict_New())) { goto exit; }
    for (o = options; o->keyword != NULL; o++) {
        if (o->val != NULL) {
            PyObject *value;
            if (!(value = Text_FromUTF8(o->val))) { goto exit; }
            if (PyDict_SetItemString(dict, o->keyword, value) != 0) {
                Py_DECREF(value);
                goto exit;
            }
            Py_DECREF(value);
        }
    }

    /* success */
    res = dict;
    dict = NULL;

exit:
    PQconninfoFree(options);    /* safe on null */
    Py_XDECREF(dict);
    Py_XDECREF(dsn);

    return res;
}
Ejemplo n.º 5
0
/* Create a namedtuple for cursor.description items
 *
 * Return None in case of expected errors (e.g. namedtuples not available)
 * NULL in case of errors to propagate.
 */
static PyObject *
psyco_make_description_type(void)
{
    PyObject *coll = NULL;
    PyObject *nt = NULL;
    PyTypeObject *t = NULL;
    PyObject *s = NULL;
    PyObject *rv = NULL;

    /* Try to import collections.namedtuple */
    if (!(coll = PyImport_ImportModule("collections"))) {
        Dprintf("psyco_make_description_type: collections import failed");
        goto error;
    }
    if (!(nt = PyObject_GetAttrString(coll, "namedtuple"))) {
        Dprintf("psyco_make_description_type: no collections.namedtuple");
        goto error;
    }

    /* Build the namedtuple */
    if(!(t = (PyTypeObject *)PyObject_CallFunction(nt, "ss", "Column",
        "name type_code display_size internal_size precision scale null_ok"))) {
        goto exit;
    }

    /* Export the tuple on the extensions module
     * Required to guarantee picklability on Py > 3.3 (see Python issue 21374)
     * for previous Py version the module is psycopg2 anyway but for consistency
     * we'd rather expose it from the extensions module. */
    if (!(s = Text_FromUTF8("psycopg2.extensions"))) { goto exit; }
    if (0 > PyDict_SetItemString(t->tp_dict, "__module__", s)) { goto exit; }

    rv = (PyObject *)t;
    t = NULL;

exit:
    Py_XDECREF(coll);
    Py_XDECREF(nt);
    Py_XDECREF((PyObject *)t);
    Py_XDECREF(s);

    return rv;

error:
    /* controlled error: we will fall back to regular tuples. Return None. */
    PyErr_Clear();
    rv = Py_None;
    Py_INCREF(rv);
    goto exit;
}
Ejemplo n.º 6
0
/* Device getters/setters */
static PyObject*
_device_getname (PyObject* self, void *closure)
{
    const ALCchar *name;

    CLEAR_ALCERROR_STATE ();
    name = alcGetString (PyDevice_AsDevice (self), ALC_DEVICE_SPECIFIER);
    if (!name)
    {
        SetALCErrorException (alcGetError (PyDevice_AsDevice (self)), 1);
        return NULL;
    }
    return Text_FromUTF8 ((const char*)name);
}
Ejemplo n.º 7
0
static PyObject *
xid_repr(xidObject *self)
{
    PyObject *rv = NULL;
    PyObject *format = NULL;
    PyObject *args = NULL;

    if (Py_None == self->format_id) {
        if (!(format = Text_FromUTF8("<Xid: %r (unparsed)>"))) {
            goto exit;
        }
        if (!(args = PyTuple_New(1))) { goto exit; }
        Py_INCREF(self->gtrid);
        PyTuple_SET_ITEM(args, 0, self->gtrid);
    }
    else {
        if (!(format = Text_FromUTF8("<Xid: (%r, %r, %r)>"))) {
            goto exit;
        }
        if (!(args = PyTuple_New(3))) { goto exit; }
        Py_INCREF(self->format_id);
        PyTuple_SET_ITEM(args, 0, self->format_id);
        Py_INCREF(self->gtrid);
        PyTuple_SET_ITEM(args, 1, self->gtrid);
        Py_INCREF(self->bqual);
        PyTuple_SET_ITEM(args, 2, self->bqual);
    }

    rv = Text_Format(format, args);

exit:
    Py_XDECREF(args);
    Py_XDECREF(format);

    return rv;
}
Ejemplo n.º 8
0
RAISES_NEG static int
obscure_password(connectionObject *conn)
{
    PQconninfoOption *options;
    PyObject *d = NULL, *v = NULL, *dsn = NULL;
    char *tmp;
    int rv = -1;

    if (!conn || !conn->dsn) {
        return 0;
    }

    if (!(options = PQconninfoParse(conn->dsn, NULL))) {
        /* unlikely: the dsn was already tested valid */
        return 0;
    }

    if (!(d = psycopg_dict_from_conninfo_options(
            options, /* include_password = */ 1))) {
        goto exit;
    }
    if (NULL == PyDict_GetItemString(d, "password")) {
        /* the dsn doesn't have a password */
        rv = 0;
        goto exit;
    }

    /* scrub the password and put back the connection string together */
    if (!(v = Text_FromUTF8("xxx"))) { goto exit; }
    if (0 > PyDict_SetItemString(d, "password", v)) { goto exit; }
    if (!(dsn = psycopg_make_dsn(Py_None, d))) { goto exit; }
    if (!(dsn = psycopg_ensure_bytes(dsn))) { goto exit; }

    /* Replace the connection string on the connection object */
    tmp = conn->dsn;
    psycopg_strdup(&conn->dsn, Bytes_AS_STRING(dsn), -1);
    PyMem_Free(tmp);

    rv = 0;

exit:
    PQconninfoFree(options);
    Py_XDECREF(v);
    Py_XDECREF(d);
    Py_XDECREF(dsn);

    return rv;
}
Ejemplo n.º 9
0
static PyObject*
_sdl_joygetname (PyObject *self, PyObject *args)
{
    int joy;
    ASSERT_JOYSTICK_INIT(NULL);

    if (!IntFromObj (args, &joy))
        return NULL;

    if (joy < 0 || joy >= SDL_NumJoysticks())
    {
        PyErr_SetString (PyExc_ValueError, "invalid joystick index");
        return NULL;
    }
    return Text_FromUTF8 (SDL_JoystickName (joy));
}
Ejemplo n.º 10
0
static const char *
_psyco_conn_parse_onoff(PyObject *pyval)
{
    int istrue = PyObject_IsTrue(pyval);
    if (-1 == istrue) { return NULL; }
    if (istrue) {
        int cmp;
        PyObject *pydef;
        if (!(pydef = Text_FromUTF8("default"))) { return NULL; }
        cmp = PyObject_RichCompareBool(pyval, pydef, Py_EQ);
        Py_DECREF(pydef);
        if (-1 == cmp) { return NULL; }
        return cmp ? "default" : "on";
    }
    else {
        return "off";
    }
}
Ejemplo n.º 11
0
/* Initialize the encodings table.
 *
 * Return 0 on success, else -1 and set an exception.
 */
static int psyco_encodings_fill(PyObject *dict)
{
    PyObject *value = NULL;
    encodingPair *enc;
    int rv = -1;

    for (enc = encodings; enc->pgenc != NULL; enc++) {
        if (!(value = Text_FromUTF8(enc->pyenc))) { goto exit; }
        if (0 != PyDict_SetItemString(dict, enc->pgenc, value)) { goto exit; }
        Py_CLEAR(value);
    }
    rv = 0;

exit:
    Py_XDECREF(value);

    return rv;
}
Ejemplo n.º 12
0
static int
psyco_errors_init(void)
{
    /* the names of the exceptions here reflect the organization of the
       psycopg2 module and not the fact the the original error objects
       live in _psycopg */

    int i;
    PyObject *dict = NULL;
    PyObject *str = NULL;
    int rv = -1;

    /* 'Error' has been defined elsewhere: only init the other classes */
    Error = (PyObject *)&errorType;

    for (i = 1; exctable[i].name; i++) {
        if (!(dict = PyDict_New())) { goto exit; }

        if (exctable[i].docstr) {
            if (!(str = Text_FromUTF8(exctable[i].docstr))) { goto exit; }
            if (0 != PyDict_SetItemString(dict, "__doc__", str)) { goto exit; }
            Py_CLEAR(str);
        }

        /* can't put PyExc_StandardError in the static exctable:
         * windows build will fail */
        if (!(*exctable[i].exc = PyErr_NewException(
                exctable[i].name,
                exctable[i].base ? *exctable[i].base : PyExc_StandardError,
                dict))) {
            goto exit;
        }
        Py_CLEAR(dict);
    }

    rv = 0;

exit:
    Py_XDECREF(str);
    Py_XDECREF(dict);
    return rv;
}
Ejemplo n.º 13
0
PyObject *
typecast_from_c(typecastObject_initlist *type, PyObject *dict)
{
    PyObject *name = NULL, *values = NULL, *base = NULL;
    typecastObject *obj = NULL;
    Py_ssize_t i, len = 0;

    /* before doing anything else we look for the base */
    if (type->base) {
        /* NOTE: base is a borrowed reference! */
        base = PyDict_GetItemString(dict, type->base);
        if (!base) {
            PyErr_Format(Error, "typecast base not found: %s", type->base);
            goto end;
        }
    }

    name = Text_FromUTF8(type->name);
    if (!name) goto end;

    while (type->values[len] != 0) len++;

    values = PyTuple_New(len);
    if (!values) goto end;

    for (i = 0; i < len ; i++) {
        PyTuple_SET_ITEM(values, i, PyInt_FromLong(type->values[i]));
    }

    obj = (typecastObject *)typecast_new(name, values, NULL, base);

    if (obj) {
        obj->ccast = type->cast;
        obj->pcast = NULL;
    }

 end:
    Py_XDECREF(values);
    Py_XDECREF(name);
    return (PyObject *)obj;
}
Ejemplo n.º 14
0
static void
psyco_errors_init(void)
{
    /* the names of the exceptions here reflect the oranization of the
       psycopg2 module and not the fact the the original error objects
       live in _psycopg */

    int i;
    PyObject *dict;
    PyObject *base;
    PyObject *str;

    for (i=0; exctable[i].name; i++) {
        dict = PyDict_New();

        if (exctable[i].docstr) {
            str = Text_FromUTF8(exctable[i].docstr);
            PyDict_SetItemString(dict, "__doc__", str);
        }

        if (exctable[i].base == 0) {
            #if PY_MAJOR_VERSION < 3
            base = PyExc_StandardError;
            #else
            /* StandardError is gone in 3.0 */
            base = NULL;
            #endif
        }
        else
            base = *exctable[i].base;

        *exctable[i].exc = PyErr_NewException(exctable[i].name, base, dict);
    }

    /* Make pgerror, pgcode and cursor default to None on psycopg
       error objects.  This simplifies error handling code that checks
       these attributes. */
    PyObject_SetAttrString(Error, "pgerror", Py_None);
    PyObject_SetAttrString(Error, "pgcode", Py_None);
    PyObject_SetAttrString(Error, "cursor", Py_None);
}
Ejemplo n.º 15
0
/* Return the PostgreSQL transaction_id for this XA xid.
 *
 * PostgreSQL wants just a string, while the DBAPI supports the XA standard
 * and thus a triple. We use the same conversion algorithm implemented by JDBC
 * in order to allow some form of interoperation.
 *
 * The function must be called while holding the GIL.
 *
 * see also: the pgjdbc implementation
 *   http://cvs.pgfoundry.org/cgi-bin/cvsweb.cgi/jdbc/pgjdbc/org/postgresql/xa/RecoveredXid.java?rev=1.2
 */
PyObject *
xid_get_tid(xidObject *self)
{
    PyObject *rv = NULL;
    PyObject *egtrid = NULL;
    PyObject *ebqual = NULL;
    PyObject *format = NULL;
    PyObject *args = NULL;

    if (Py_None == self->format_id) {
        /* Unparsed xid: return the gtrid. */
        Py_INCREF(self->gtrid);
        rv = self->gtrid;
    }
    else {
        /* XA xid: mash together the components. */
        if (!(egtrid = _xid_encode64(self->gtrid))) { goto exit; }
        if (!(ebqual = _xid_encode64(self->bqual))) { goto exit; }

        /* rv = "%d_%s_%s" % (format_id, egtrid, ebqual) */
        if (!(format = Text_FromUTF8("%d_%s_%s"))) { goto exit; }

        if (!(args = PyTuple_New(3))) { goto exit; }
        Py_INCREF(self->format_id);
        PyTuple_SET_ITEM(args, 0, self->format_id);
        PyTuple_SET_ITEM(args, 1, egtrid); egtrid = NULL;
        PyTuple_SET_ITEM(args, 2, ebqual); ebqual = NULL;

        if (!(rv = Text_Format(format, args))) { goto exit; }
    }

exit:
    Py_XDECREF(args);
    Py_XDECREF(format);
    Py_XDECREF(egtrid);
    Py_XDECREF(ebqual);

    return rv;
}
Ejemplo n.º 16
0
static PyObject*
_font_repr(PyObject *self)
{
    return Text_FromUTF8("<Generic Font>");
}
Ejemplo n.º 17
0
Archivo: base.c Proyecto: Mrhjx2/pygame
static PyObject*
get_error (PyObject* self)
{
    return Text_FromUTF8 (SDL_GetError ());
}
Ejemplo n.º 18
0
static PyObject*
_sources_repr (PyObject *self)
{
    return Text_FromUTF8 ("<Sources>");
}
Ejemplo n.º 19
0
static PyObject*
_event_getname (PyObject *self, void *closure)
{
    switch (((PyEvent*)self)->type)
    {
    case SDL_ACTIVEEVENT:
        return Text_FromUTF8 ("ActiveEvent");
    case SDL_KEYDOWN:
        return Text_FromUTF8 ("KeyDown");
    case SDL_KEYUP:
        return Text_FromUTF8 ("KeyUp");
    case SDL_MOUSEMOTION:
        return Text_FromUTF8 ("MouseMotion");
    case SDL_MOUSEBUTTONDOWN:
        return Text_FromUTF8 ("MouseButtonDown");
    case SDL_MOUSEBUTTONUP:
        return Text_FromUTF8 ("MouseButtonUp");
    case SDL_JOYAXISMOTION:
        return Text_FromUTF8 ("JoyAxisMotion");
    case SDL_JOYBALLMOTION:
        return Text_FromUTF8 ("JoyBallMotion");
    case SDL_JOYHATMOTION:
        return Text_FromUTF8 ("JoyHatMotion");
    case SDL_JOYBUTTONUP:
        return Text_FromUTF8 ("JoyButtonUp");
    case SDL_JOYBUTTONDOWN:
        return Text_FromUTF8 ("JoyButtonDown");
    case SDL_QUIT:
        return Text_FromUTF8 ("Quit");
    case SDL_SYSWMEVENT:
        return Text_FromUTF8 ("SysWMEvent");
    case SDL_VIDEORESIZE:
        return Text_FromUTF8 ("VideoResize");
    case SDL_VIDEOEXPOSE:
        return Text_FromUTF8 ("VideoExpose");
    case SDL_NOEVENT:
        return Text_FromUTF8 ("NoEvent");
    }
    if (((PyEvent*)self)->type >= SDL_USEREVENT &&
            ((PyEvent*)self)->type < SDL_NUMEVENTS)
        return Text_FromUTF8 ("UserEvent");
    return Text_FromUTF8 ("Unknown");
}
Ejemplo n.º 20
0
static PyObject*
_device_getextensions (PyObject *self, void *closure)
{
    ALCchar tmp[4096] = { '\0' };
    int i = 0;
    const ALCchar *dptr;
    PyObject *list, *item;
    const ALCchar *devices;

    CLEAR_ALCERROR_STATE ();
    devices = alcGetString (PyDevice_AsDevice (self), ALC_DEVICE_SPECIFIER);
    if (!devices)
    {
        SetALCErrorException (alcGetError (PyDevice_AsDevice (self)), 1);
        return NULL;
    }
    
    list = PyList_New (0);
    dptr = devices;
    while (*dptr)
    {
        if (*dptr == ' ') /* list entry end */
        {
            item = Text_FromUTF8 ((const char*) tmp);
            if (!item)
            {
                Py_DECREF (list);
                return NULL;
            }
            if (PyList_Append (list, item) == -1)
            {
                Py_DECREF (item);
                Py_DECREF (list);
                return NULL;
            }
            Py_DECREF (item);
            memset (tmp, '\0', (size_t)4096);
            i = 0;
        }
        else if (i < 4096)
        {
            tmp[i] = *dptr;
        }
        dptr++;
        i++;
    }
    /* Sentinel append */
    if (i != 0)
    {
        item = Text_FromUTF8 ((const char*) tmp);
        if (!item)
        {
            Py_DECREF (list);
            return NULL;
        }
        if (PyList_Append (list, item) == -1)
        {
            Py_DECREF (item);
            Py_DECREF (list);
            return NULL;
        }
        Py_DECREF (item);
    }
    return list;
}
Ejemplo n.º 21
0
/* Getters/Setters */
static PyObject*
_cd_getname (PyObject *self, void *closure)
{
    ASSERT_CDROM_INIT(NULL);
    return Text_FromUTF8 (SDL_CDName (((PyCD*)self)->index));
}
Ejemplo n.º 22
0
/* Expose the notices received as Python objects.
 *
 * The function should be called with the connection lock and the GIL.
 */
void
conn_notice_process(connectionObject *self)
{
    struct connectionObject_notice *notice;
    PyObject *msg = NULL;
    PyObject *tmp = NULL;
    static PyObject *append;

    if (NULL == self->notice_pending) {
        return;
    }

    if (!append) {
        if (!(append = Text_FromUTF8("append"))) {
            goto error;
        }
    }

    notice = self->notice_pending;
    while (notice != NULL) {
        Dprintf("conn_notice_process: %s", notice->message);

        if (!(msg = conn_text_from_chars(self, notice->message))) {
            goto error;
        }

        if (!(tmp = PyObject_CallMethodObjArgs(
                        self->notice_list, append, msg, NULL))) {

            goto error;
        }

        Py_DECREF(tmp);
        tmp = NULL;
        Py_DECREF(msg);
        msg = NULL;

        notice = notice->next;
    }

    /* Remove the oldest item if the queue is getting too long. */
    if (PyList_Check(self->notice_list)) {
        Py_ssize_t nnotices;
        nnotices = PyList_GET_SIZE(self->notice_list);
        if (nnotices > CONN_NOTICES_LIMIT) {
            if (-1 == PySequence_DelSlice(self->notice_list,
                                          0, nnotices - CONN_NOTICES_LIMIT)) {
                PyErr_Clear();
            }
        }
    }

    conn_notice_clean(self);
    return;

error:
    Py_XDECREF(tmp);
    Py_XDECREF(msg);
    conn_notice_clean(self);

    /* TODO: the caller doesn't expects errors from us */
    PyErr_Clear();
}
Ejemplo n.º 23
0
static PyObject*
_context_repr (PyObject *self)
{
    /* TODO */
    return Text_FromUTF8 ("<Context>");
}
Ejemplo n.º 24
0
void
conn_notifies_process(connectionObject *self)
{
    PGnotify *pgn = NULL;
    PyObject *notify = NULL;
    PyObject *pid = NULL, *channel = NULL, *payload = NULL;
    PyObject *tmp = NULL;

    static PyObject *append;

    if (!append) {
        if (!(append = Text_FromUTF8("append"))) {
            goto error;
        }
    }

    while ((pgn = PQnotifies(self->pgconn)) != NULL) {

        Dprintf("conn_notifies_process: got NOTIFY from pid %d, msg = %s",
                (int) pgn->be_pid, pgn->relname);

        if (!(pid = PyInt_FromLong((long)pgn->be_pid))) {
            goto error;
        }
        if (!(channel = conn_text_from_chars(self, pgn->relname))) {
            goto error;
        }
        if (!(payload = conn_text_from_chars(self, pgn->extra))) {
            goto error;
        }

        if (!(notify = PyObject_CallFunctionObjArgs((PyObject *)&notifyType,
                       pid, channel, payload, NULL))) {
            goto error;
        }

        Py_DECREF(pid);
        pid = NULL;
        Py_DECREF(channel);
        channel = NULL;
        Py_DECREF(payload);
        payload = NULL;

        if (!(tmp = PyObject_CallMethodObjArgs(
                        self->notifies, append, notify, NULL))) {
            goto error;
        }
        Py_DECREF(tmp);
        tmp = NULL;

        Py_DECREF(notify);
        notify = NULL;
        PQfreemem(pgn);
        pgn = NULL;
    }
    return;  /* no error */

error:
    if (pgn) {
        PQfreemem(pgn);
    }
    Py_XDECREF(tmp);
    Py_XDECREF(notify);
    Py_XDECREF(pid);
    Py_XDECREF(channel);
    Py_XDECREF(payload);

    /* TODO: callers currently don't expect an error from us */
    PyErr_Clear();

}
Ejemplo n.º 25
0
static int
xid_init(XidObject *self, PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = {"format_id", "gtrid", "bqual", NULL};
    int format_id;
    size_t i, gtrid_len, bqual_len;
    const char *gtrid, *bqual;
    PyObject *tmp;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iss", kwlist,
                                     &format_id, &gtrid, &bqual))
        return -1;

    if (format_id < 0 || format_id > 0x7fffffff) {
        PyErr_SetString(PyExc_ValueError,
                        "format_id must be a non-negative 32-bit integer");
        return -1;
    }

    /* make sure that gtrid is no more than 64 characters long and
       made of printable characters (which we're defining as those
       between 0x20 and 0x7f). */
    gtrid_len = strlen(gtrid);
    if (gtrid_len > 64) {
        PyErr_SetString(PyExc_ValueError,
                        "gtrid must be a string no longer than 64 characters");
        return -1;
    }
    for (i = 0; i < gtrid_len; i++) {
        if (gtrid[i] < 0x20 || gtrid[i] >= 0x7f) {
            PyErr_SetString(PyExc_ValueError,
                            "gtrid must contain only printable characters.");
            return -1;
        }
    }
    /* Same for bqual */
    bqual_len = strlen(bqual);
    if (bqual_len > 64) {
        PyErr_SetString(PyExc_ValueError,
                        "bqual must be a string no longer than 64 characters");
        return -1;
    }
    for (i = 0; i < bqual_len; i++) {
        if (bqual[i] < 0x20 || bqual[i] >= 0x7f) {
            PyErr_SetString(PyExc_ValueError,
                            "bqual must contain only printable characters.");
            return -1;
        }
    }

    tmp = self->format_id;
    self->format_id = PyInt_FromLong(format_id);
    Py_XDECREF(tmp);

    tmp = self->gtrid;
    self->gtrid = Text_FromUTF8(gtrid);
    Py_XDECREF(tmp);

    tmp = self->bqual;
    self->bqual = Text_FromUTF8(bqual);
    Py_XDECREF(tmp);

    return 0;
}
Ejemplo n.º 26
0
static PyObject *
psyco_encrypt_password(PyObject *self, PyObject *args, PyObject *kwargs)
{
    char *encrypted = NULL;
    PyObject *password = NULL, *user = NULL;
    PyObject *scope = Py_None, *algorithm = Py_None;
    PyObject *res = NULL;
    connectionObject *conn = NULL;

    static char *kwlist[] = {"password", "user", "scope", "algorithm", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|OO", kwlist,
            &password, &user, &scope, &algorithm)) {
        return NULL;
    }

    /* for ensure_bytes */
    Py_INCREF(user);
    Py_INCREF(password);
    Py_INCREF(algorithm);

    if (scope != Py_None) {
        if (PyObject_TypeCheck(scope, &cursorType)) {
            conn = ((cursorObject*)scope)->conn;
        }
        else if (PyObject_TypeCheck(scope, &connectionType)) {
            conn = (connectionObject*)scope;
        }
        else {
            PyErr_SetString(PyExc_TypeError,
                "the scope must be a connection or a cursor");
            goto exit;
        }
    }

    if (!(user = psycopg_ensure_bytes(user))) { goto exit; }
    if (!(password = psycopg_ensure_bytes(password))) { goto exit; }
    if (algorithm != Py_None) {
        if (!(algorithm = psycopg_ensure_bytes(algorithm))) {
            goto exit;
        }
    }

    /* If we have to encrypt md5 we can use the libpq < 10 API */
    if (algorithm != Py_None &&
            strcmp(Bytes_AS_STRING(algorithm), "md5") == 0) {
        encrypted = PQencryptPassword(
            Bytes_AS_STRING(password), Bytes_AS_STRING(user));
    }

    /* If the algorithm is not md5 we have to use the API available from
     * libpq 10. */
    else {
#if PG_VERSION_NUM >= 100000
        if (!conn) {
            PyErr_SetString(ProgrammingError,
                "password encryption (other than 'md5' algorithm)"
                " requires a connection or cursor");
            goto exit;
        }

        /* TODO: algo = None will block: forbid on async/green conn? */
        encrypted = PQencryptPasswordConn(conn->pgconn,
            Bytes_AS_STRING(password), Bytes_AS_STRING(user),
            algorithm != Py_None ? Bytes_AS_STRING(algorithm) : NULL);
#else
        PyErr_SetString(NotSupportedError,
            "password encryption (other than 'md5' algorithm)"
            " requires libpq 10");
        goto exit;
#endif
    }

    if (encrypted) {
        res = Text_FromUTF8(encrypted);
    }
    else {
        const char *msg = PQerrorMessage(conn->pgconn);
        PyErr_Format(ProgrammingError,
            "password encryption failed: %s", msg ? msg : "no reason given");
        goto exit;
    }

exit:
    if (encrypted) {
        PQfreemem(encrypted);
    }
    Py_XDECREF(user);
    Py_XDECREF(password);
    Py_XDECREF(algorithm);

    return res;
}
Ejemplo n.º 27
0
PyMODINIT_FUNC
INIT_MODULE(_psycopg)(void)
{
#if PY_VERSION_HEX < 0x03020000
    static void *PSYCOPG_API[PSYCOPG_API_pointers];
    PyObject *c_api_object;
#endif

    PyObject *module = NULL, *dict;

#ifdef PSYCOPG_DEBUG
    if (getenv("PSYCOPG_DEBUG"))
        psycopg_debug_enabled = 1;
#endif

    Dprintf("initpsycopg: initializing psycopg %s", PSYCOPG_VERSION);

    /* initialize all the new types and then the module */
    Py_TYPE(&connectionType) = &PyType_Type;
    if (PyType_Ready(&connectionType) == -1) goto exit;

    Py_TYPE(&cursorType) = &PyType_Type;
    if (PyType_Ready(&cursorType) == -1) goto exit;

    Py_TYPE(&typecastType) = &PyType_Type;
    if (PyType_Ready(&typecastType) == -1) goto exit;

    Py_TYPE(&qstringType) = &PyType_Type;
    if (PyType_Ready(&qstringType) == -1) goto exit;

    Py_TYPE(&binaryType) = &PyType_Type;
    if (PyType_Ready(&binaryType) == -1) goto exit;

    Py_TYPE(&isqlquoteType) = &PyType_Type;
    if (PyType_Ready(&isqlquoteType) == -1) goto exit;

    Py_TYPE(&pbooleanType) = &PyType_Type;
    if (PyType_Ready(&pbooleanType) == -1) goto exit;

    Py_TYPE(&pintType) = &PyType_Type;
    if (PyType_Ready(&pintType) == -1) goto exit;

    Py_TYPE(&pfloatType) = &PyType_Type;
    if (PyType_Ready(&pfloatType) == -1) goto exit;

    Py_TYPE(&pdecimalType) = &PyType_Type;
    if (PyType_Ready(&pdecimalType) == -1) goto exit;

    Py_TYPE(&asisType) = &PyType_Type;
    if (PyType_Ready(&asisType) == -1) goto exit;

    Py_TYPE(&listType) = &PyType_Type;
    if (PyType_Ready(&listType) == -1) goto exit;

    Py_TYPE(&chunkType) = &PyType_Type;
    if (PyType_Ready(&chunkType) == -1) goto exit;

    Py_TYPE(&notifyType) = &PyType_Type;
    if (PyType_Ready(&notifyType) == -1) goto exit;

    Py_TYPE(&xidType) = &PyType_Type;
    if (PyType_Ready(&xidType) == -1) goto exit;

    Py_TYPE(&errorType) = &PyType_Type;
    errorType.tp_base = (PyTypeObject *)PyExc_StandardError;
    if (PyType_Ready(&errorType) == -1) goto exit;

    Py_TYPE(&diagnosticsType) = &PyType_Type;
    if (PyType_Ready(&diagnosticsType) == -1) goto exit;

    Py_TYPE(&lobjectType) = &PyType_Type;
    if (PyType_Ready(&lobjectType) == -1) goto exit;

    /* initialize libcrypto threading callbacks */
    psyco_libcrypto_threads_init();

    /* import mx.DateTime module, if necessary */
#ifdef HAVE_MXDATETIME
    Py_TYPE(&mxdatetimeType) = &PyType_Type;
    if (PyType_Ready(&mxdatetimeType) == -1) goto exit;

    if (0 != mxDateTime_ImportModuleAndAPI()) {
        PyErr_Clear();

        /* only fail if the mx typacaster should have been the default */
#ifdef PSYCOPG_DEFAULT_MXDATETIME
        PyErr_SetString(PyExc_ImportError,
            "can't import mx.DateTime module (requested as default adapter)");
        goto exit;
#endif
    }
#endif

    /* import python builtin datetime module, if available */
    pyDateTimeModuleP = PyImport_ImportModule("datetime");
    if (pyDateTimeModuleP == NULL) {
        Dprintf("initpsycopg: can't import datetime module");
        PyErr_SetString(PyExc_ImportError, "can't import datetime module");
        goto exit;
    }

    /* Initialize the PyDateTimeAPI everywhere is used */
    PyDateTime_IMPORT;
    if (psyco_adapter_datetime_init()) { goto exit; }

    Py_TYPE(&pydatetimeType) = &PyType_Type;
    if (PyType_Ready(&pydatetimeType) == -1) goto exit;

    /* initialize the module and grab module's dictionary */
#if PY_MAJOR_VERSION < 3
    module = Py_InitModule("_psycopg", psycopgMethods);
#else
    module = PyModule_Create(&psycopgmodule);
#endif
    if (!module) { goto exit; }

    dict = PyModule_GetDict(module);

    /* initialize all the module's exported functions */
    /* PyBoxer_API[PyBoxer_Fake_NUM] = (void *)PyBoxer_Fake; */

    /* Create a CObject containing the API pointer array's address */
    /* If anybody asks for a PyCapsule we'll deal with it. */
#if PY_VERSION_HEX < 0x03020000
    c_api_object = PyCObject_FromVoidPtr((void *)PSYCOPG_API, NULL);
    if (c_api_object != NULL)
        PyModule_AddObject(module, "_C_API", c_api_object);
#endif

    /* other mixed initializations of module-level variables */
    if (!(psycoEncodings = PyDict_New())) { goto exit; }
    if (0 != psyco_encodings_fill(psycoEncodings)) { goto exit; }
    psyco_null = Bytes_FromString("NULL");
    if (!(psyco_DescriptionType = psyco_make_description_type())) { goto exit; }

    /* set some module's parameters */
    PyModule_AddStringConstant(module, "__version__", PSYCOPG_VERSION);
    PyModule_AddStringConstant(module, "__doc__", "psycopg PostgreSQL driver");
    PyModule_AddIntConstant(module, "__libpq_version__", PG_VERSION_NUM);
    PyModule_AddObject(module, "apilevel", Text_FromUTF8(APILEVEL));
    PyModule_AddObject(module, "threadsafety", PyInt_FromLong(THREADSAFETY));
    PyModule_AddObject(module, "paramstyle", Text_FromUTF8(PARAMSTYLE));

    /* put new types in module dictionary */
    PyModule_AddObject(module, "connection", (PyObject*)&connectionType);
    PyModule_AddObject(module, "cursor", (PyObject*)&cursorType);
    PyModule_AddObject(module, "ISQLQuote", (PyObject*)&isqlquoteType);
    PyModule_AddObject(module, "Notify", (PyObject*)&notifyType);
    PyModule_AddObject(module, "Xid", (PyObject*)&xidType);
    PyModule_AddObject(module, "Diagnostics", (PyObject*)&diagnosticsType);
    PyModule_AddObject(module, "AsIs", (PyObject*)&asisType);
    PyModule_AddObject(module, "Binary", (PyObject*)&binaryType);
    PyModule_AddObject(module, "Boolean", (PyObject*)&pbooleanType);
    PyModule_AddObject(module, "Decimal", (PyObject*)&pdecimalType);
    PyModule_AddObject(module, "Int", (PyObject*)&pintType);
    PyModule_AddObject(module, "Float", (PyObject*)&pfloatType);
    PyModule_AddObject(module, "List", (PyObject*)&listType);
    PyModule_AddObject(module, "QuotedString", (PyObject*)&qstringType);
    PyModule_AddObject(module, "lobject", (PyObject*)&lobjectType);
    PyModule_AddObject(module, "Column", psyco_DescriptionType);

    /* encodings dictionary in module dictionary */
    PyModule_AddObject(module, "encodings", psycoEncodings);

#ifdef HAVE_MXDATETIME
    /* If we can't find mx.DateTime objects at runtime,
     * remove them from the module (and, as consequence, from the adapters). */
    if (0 != psyco_adapter_mxdatetime_init()) {
        PyDict_DelItemString(dict, "DateFromMx");
        PyDict_DelItemString(dict, "TimeFromMx");
        PyDict_DelItemString(dict, "TimestampFromMx");
        PyDict_DelItemString(dict, "IntervalFromMx");
    }
#endif
    /* initialize default set of typecasters */
    if (0 != typecast_init(dict)) { goto exit; }

    /* initialize microprotocols layer */
    microprotocols_init(dict);
    if (0 != psyco_adapters_init(dict)) { goto exit; }

    /* create a standard set of exceptions and add them to the module's dict */
    if (0 != psyco_errors_init()) { goto exit; }
    psyco_errors_fill(dict);

    Dprintf("initpsycopg: module initialization complete");

exit:
#if PY_MAJOR_VERSION > 2
    return module;
#else
    return;
#endif
}
Ejemplo n.º 28
0
static int
psyco_errors_init(void)
{
    /* the names of the exceptions here reflect the oranization of the
       psycopg2 module and not the fact the the original error objects
       live in _psycopg */

    int i;
    PyObject *dict = NULL;
    PyObject *base;
    PyObject *str = NULL;
    PyObject *descr = NULL;
    int rv = -1;

#if PY_VERSION_HEX >= 0x02050000
    static PyMethodDef psyco_error_reduce_ex_def =
        {"__reduce_ex__", psyco_error_reduce_ex, METH_VARARGS, "pickle helper"};
#endif

    for (i=0; exctable[i].name; i++) {
        if (!(dict = PyDict_New())) { goto exit; }

        if (exctable[i].docstr) {
            if (!(str = Text_FromUTF8(exctable[i].docstr))) { goto exit; }
            if (0 != PyDict_SetItemString(dict, "__doc__", str)) { goto exit; }
            Py_CLEAR(str);
        }

        if (exctable[i].base == 0) {
            #if PY_MAJOR_VERSION < 3
            base = PyExc_StandardError;
            #else
            /* StandardError is gone in 3.0 */
            base = NULL;
            #endif
        }
        else
            base = *exctable[i].base;

        if (!(*exctable[i].exc = PyErr_NewException(
                exctable[i].name, base, dict))) {
            goto exit;
        }
        Py_CLEAR(dict);
    }

    /* Make pgerror, pgcode and cursor default to None on psycopg
       error objects.  This simplifies error handling code that checks
       these attributes. */
    PyObject_SetAttrString(Error, "pgerror", Py_None);
    PyObject_SetAttrString(Error, "pgcode", Py_None);
    PyObject_SetAttrString(Error, "cursor", Py_None);

    /* install __reduce_ex__ on Error to make all the subclasses picklable.
     *
     * Don't install it on Py 2.4: it is not used by the pickle
     * protocol, and if called manually fails in an unsettling way,
     * probably because the exceptions were old-style classes. */
#if PY_VERSION_HEX >= 0x02050000
    if (!(descr = PyDescr_NewMethod((PyTypeObject *)Error,
            &psyco_error_reduce_ex_def))) {
        goto exit;
    }
    if (0 != PyObject_SetAttrString(Error,
            psyco_error_reduce_ex_def.ml_name, descr)) {
        goto exit;
    }
#endif

    rv = 0;

exit:
    Py_XDECREF(descr);
    Py_XDECREF(str);
    Py_XDECREF(dict);
    return rv;
}