Ejemplo n.º 1
0
void
INITMODULE (void)
{
  PyObject *m, *d, *c;

  UNLESS (sort_str=PyString_FromString("sort")) return;
  UNLESS (reverse_str=PyString_FromString("reverse")) return;
  UNLESS (items_str=PyString_FromString("items")) return;
  UNLESS (__setstate___str=PyString_FromString("__setstate__")) return;

  UNLESS (PyExtensionClassCAPI=PyCObject_Import("ExtensionClass","CAPI"))
      return;

#ifdef PERSISTENT
  if ((cPersistenceCAPI=PyCObject_Import("cPersistence","CAPI")))
    {
	BucketType.methods.link=cPersistenceCAPI->methods;
	BucketType.tp_getattro=cPersistenceCAPI->getattro;
	BucketType.tp_setattro=cPersistenceCAPI->setattro;

	SetType.methods.link=cPersistenceCAPI->methods;
	SetType.tp_getattro=cPersistenceCAPI->getattro;
	SetType.tp_setattro=cPersistenceCAPI->setattro;

	BTreeType.methods.link=cPersistenceCAPI->methods;
	BTreeType.tp_getattro=cPersistenceCAPI->getattro;
	BTreeType.tp_setattro=cPersistenceCAPI->setattro;

	TreeSetType.methods.link=cPersistenceCAPI->methods;
	TreeSetType.tp_getattro=cPersistenceCAPI->getattro;
	TreeSetType.tp_setattro=cPersistenceCAPI->setattro;
    }
  else return;

  /* Grab the ConflictError class */

  m = PyImport_ImportModule("ZODB.POSException");

  if (m != NULL) {
  	c = PyObject_GetAttrString(m, "BTreesConflictError");
  	if (c != NULL)
  		ConflictError = c;
	Py_DECREF(m);
  }

  if (ConflictError == NULL) {
  	Py_INCREF(PyExc_ValueError);
	ConflictError=PyExc_ValueError;
  }

#else
  BTreeType.tp_getattro=PyExtensionClassCAPI->getattro;
  BucketType.tp_getattro=PyExtensionClassCAPI->getattro;
  SetType.tp_getattro=PyExtensionClassCAPI->getattro;
  TreeSetType.tp_getattro=PyExtensionClassCAPI->getattro;
#endif

  BTreeItemsType.ob_type=&PyType_Type;

#ifdef INTSET_H
  UNLESS(d = PyImport_ImportModule("intSet")) return;
  UNLESS(intSetType = PyObject_GetAttrString (d, "intSet")) return;
  Py_DECREF (d);
#endif

  /* Create the module and add the functions */
  m = Py_InitModule4("_" MOD_NAME_PREFIX "BTree", module_methods,
		     BTree_module_documentation,
		     (PyObject*)NULL,PYTHON_API_VERSION);

  /* Add some symbolic constants to the module */
  d = PyModule_GetDict(m);

  PyExtensionClass_Export(d,MOD_NAME_PREFIX "Bucket", BucketType);
  PyExtensionClass_Export(d,MOD_NAME_PREFIX "BTree", BTreeType);
  PyExtensionClass_Export(d,MOD_NAME_PREFIX "Set", SetType);
  PyExtensionClass_Export(d,MOD_NAME_PREFIX "TreeSet", TreeSetType);
}
Ejemplo n.º 2
0
PyObject *session_connect(PyObject *self, PyObject *args) {
#ifdef DEBUG
    fprintf(stderr, "> entering session_connect\n");
#endif
    sp_session_config config;
    PyObject *client;
    sp_session *session;
    sp_error error;
    PyObject *uobj, *pobj;
    char *username, *password;

    if(!PyArg_ParseTuple(args, "O", &client))
	return NULL;

    PyEval_InitThreads();
    config.api_version = SPOTIFY_API_VERSION;
    config.userdata = (void *)client;
    config.callbacks = &g_callbacks;
    config.user_agent = "unset";

#ifdef DEBUG
    fprintf(stderr, "Config mark 1\n");
#endif
    PyObject *cache_location = PyObject_GetAttr(client, PyString_FromString("cache_location"));
#ifdef DEBUG
    fprintf(stderr, "Cache location is '%s'\n", PyString_AsString(cache_location));
#endif
    if(cache_location == NULL) {
	PyErr_SetString(SpotifyError, "Client did not provide a cache_location");
        return NULL;
    }
#ifdef DEBUG
    fprintf(stderr, "Config mark 1.1\n");
#endif
    config.cache_location = copystring(cache_location);

#ifdef DEBUG
    fprintf(stderr, "Config mark 2\n");
#endif
    PyObject *settings_location = PyObject_GetAttr(client, PyString_FromString("settings_location"));
    if(settings_location == NULL) {
	PyErr_SetString(SpotifyError, "Client did not provide a settings_location");
        return NULL;
    }
    config.settings_location = copystring(settings_location);

#ifdef DEBUG
    fprintf(stderr, "Config mark 3\n");
#endif
    PyObject *application_key = PyObject_GetAttr(client, PyString_FromString("application_key"));
    if(application_key == NULL) {
	PyErr_SetString(SpotifyError, "Client did not provide an application_key");
        return NULL;
    }
    char *s_appkey;
    Py_ssize_t l_appkey;
    PyString_AsStringAndSize(application_key, &s_appkey, &l_appkey);
    config.application_key_size = l_appkey;
    config.application_key = PyMem_Malloc(l_appkey);
    memcpy(config.application_key, s_appkey, l_appkey);

#ifdef DEBUG
    fprintf(stderr, "Config mark 4\n");
#endif
    PyObject *user_agent = PyObject_GetAttr(client, PyString_FromString("user_agent"));
    if(user_agent == NULL) {
	PyErr_SetString(SpotifyError, "Client did not provide a user_agent");
        return NULL;
    }
    config.user_agent = copystring(user_agent);

#ifdef DEBUG
    fprintf(stderr, "Config mark 5\n");
#endif
    uobj = PyObject_GetAttr(client, PyString_FromString("username"));
    if(uobj == NULL) {
	PyErr_SetString(SpotifyError, "Client did not provide a username");
	return NULL;
    }
    username = copystring(uobj);

    pobj = PyObject_GetAttr(client, PyString_FromString("password"));
    if(pobj == NULL) {
	PyErr_SetString(SpotifyError, "Client did not provide a password");
	return NULL;
    }
    password = copystring(pobj);

    Py_BEGIN_ALLOW_THREADS
#ifdef DEBUG
    fprintf(stderr, "Calling sp_session_init\n");
#endif
    error = sp_session_init(&config, &session);
#ifdef DEBUG
    fprintf(stderr, "Returned from sp_session_init\n");
#endif
    Py_END_ALLOW_THREADS
    session_constructed = 1;
    if(error != SP_ERROR_OK) {
	PyErr_SetString(SpotifyError, sp_error_message(error));
        return NULL;
    }
    Py_BEGIN_ALLOW_THREADS
    error = sp_session_login(session, username, password);
    Py_END_ALLOW_THREADS
    if(error != SP_ERROR_OK) {
	PyErr_SetString(SpotifyError, sp_error_message(error));
        return NULL;
    }
    Session *psession = (Session *)PyObject_CallObject((PyObject *)&SessionType, NULL);
    Py_INCREF(psession);
    psession->_session = session;
    return (PyObject *)psession;
}
Ejemplo n.º 3
0
static PyObject* mod_connect(PyObject* self, PyObject* args, PyObject* kwargs)
{
    UNUSED(self);

    Object pConnectString = 0;
    int fAutoCommit = 0;
    int fAnsi = 0;              // force ansi
    int fUnicodeResults = 0;
    int fReadOnly = 0;
    long timeout = 0;

    Object attrs_before; // Optional connect attrs set before connecting

    Py_ssize_t size = args ? PyTuple_Size(args) : 0;

    if (size > 1)
    {
        PyErr_SetString(PyExc_TypeError, "function takes at most 1 non-keyword argument");
        return 0;
    }

    if (size == 1)
    {
        if (!PyString_Check(PyTuple_GET_ITEM(args, 0)) && !PyUnicode_Check(PyTuple_GET_ITEM(args, 0)))
            return PyErr_Format(PyExc_TypeError, "argument 1 must be a string or unicode object");

        pConnectString.Attach(PyUnicode_FromObject(PyTuple_GetItem(args, 0)));
        if (!pConnectString.IsValid())
            return 0;
    }

    if (kwargs && PyDict_Size(kwargs) > 0)
    {
        Object partsdict(PyDict_New());
        if (!partsdict.IsValid())
            return 0;

        Py_ssize_t pos = 0;
        PyObject* key = 0;
        PyObject* value = 0;

        Object okey; // in case we need to allocate a new key

        while (PyDict_Next(kwargs, &pos, &key, &value))
        {
            if (!Text_Check(key))
                return PyErr_Format(PyExc_TypeError, "Dictionary keys passed to connect must be strings");

            // // Note: key and value are *borrowed*.
            //
            // // Check for the two non-connection string keywords we accept.  (If we get many more of these, create something
            // // table driven.  Are we sure there isn't a Python function to parse keywords but leave those it doesn't know?)
            // const char* szKey = PyString_AsString(key);

            if (Text_EqualsI(key, "autocommit"))
            {
                fAutoCommit = PyObject_IsTrue(value);
                continue;
            }
            if (Text_EqualsI(key, "ansi"))
            {
                fAnsi = PyObject_IsTrue(value);
                continue;
            }
#if PY_MAJOR_VERSION < 3
            if (Text_EqualsI(key, "unicode_results"))
            {
                fUnicodeResults = PyObject_IsTrue(value);
                continue;
            }
#endif
            if (Text_EqualsI(key, "timeout"))
            {
                timeout = PyInt_AsLong(value);
                if (PyErr_Occurred())
                    return 0;
                continue;
            }
            if (Text_EqualsI(key, "readonly"))
            {
                fReadOnly = PyObject_IsTrue(value);
                continue;
            }
            if (Text_EqualsI(key, "attrs_before"))
            {
                attrs_before = _CheckAttrsDict(value);
                if (PyErr_Occurred())
                    return 0;
                continue;
            }

            // Map DB API recommended names to ODBC names (e.g. user --> uid).

            for (size_t i = 0; i < _countof(keywordmaps); i++)
            {
                if (Text_EqualsI(key, keywordmaps[i].oldname))
                {
                    if (keywordmaps[i].newnameObject == 0)
                    {
                        keywordmaps[i].newnameObject = PyString_FromString(keywordmaps[i].newname);
                        if (keywordmaps[i].newnameObject == 0)
                            return 0;
                    }

                    key = keywordmaps[i].newnameObject;
                    break;
                }
            }

            PyObject* str = PyObject_Str(value); // convert if necessary
            if (!str)
                return 0;

            if (PyDict_SetItem(partsdict.Get(), key, str) == -1)
            {
                Py_XDECREF(str);
                return 0;
            }

            Py_XDECREF(str);
        }

        if (PyDict_Size(partsdict.Get()))
            pConnectString.Attach(MakeConnectionString(pConnectString.Get(), partsdict));
    }

    if (!pConnectString.IsValid())
        return PyErr_Format(PyExc_TypeError, "no connection information was passed");

    if (henv == SQL_NULL_HANDLE)
    {
        if (!AllocateEnv())
            return 0;
    }

    return (PyObject*)Connection_New(pConnectString.Get(), fAutoCommit != 0, fAnsi != 0, fUnicodeResults != 0, timeout,
                                     fReadOnly != 0, attrs_before);
}
Ejemplo n.º 4
0
JSTrapStatus doi_check_sc_hs(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval,void *closure)
{
    JSOp opcode = 0;
    JSStackFrame * fp = NULL;
    jsval r_val = 0;
    size_t l_val = 0;
    const JSCodeSpec *cs;
    char *updatetype = "R";
    
    opcode = (JSOp)*pc;//JS_GetTrapOpcode(cx, script, pc);//in 1.8.0, use this
    cs = &js_CodeSpec[opcode];
    //fprintf(stderr, "DEBUG:now  %s\n", cs->name);

    fp = NULL;
    JS_FrameIterator(cx,&fp);
    r_val = l_val = 0;
    switch(opcode)
    {
        case JSOP_SETNAME:
        case JSOP_SETPROP:
        {
            r_val = FETCH_OPND(-1);
            l_val = get_opcode_arg(cx,script,pc);
            updatetype = "R";
            break;
        }
        case JSOP_SETGVAR:
        {
            r_val = FETCH_OPND(-1);
            l_val = (size_t)&(fp->vars[GET_VARNO(pc)]); // TODO: FIXIT this is not l_val, setgvar is more than that
            updatetype = "R";
            break;
        }
        case JSOP_SETELEM:
        {
            r_val = FETCH_OPND(-1);
            l_val = FETCH_OPND(-3);
            updatetype = "A";
            break;
        }
        case JSOP_SETVAR:
        {
            r_val = FETCH_OPND(-1);
            l_val = (size_t)&(fp->vars[GET_VARNO(pc)]); // TODO: FIXIT
            updatetype = "R";
            break;
        }
        case JSOP_SETLOCALPOP:
        case JSOP_SETLOCAL:
        {
            r_val = FETCH_OPND(-1);
            l_val = (size_t)&(fp->spbase[GET_UINT16(pc)]);
            updatetype = "R";
            break;
        }
        case JSOP_SETARG:
        {
            r_val = FETCH_OPND(-1);
            l_val = (size_t)&(fp->argv[GET_ARGNO(pc)]); // TODO: FIXIT
            updatetype = "R";
            break;
        }
        case JSOP_SETCONST:
        {
            // Errr.... actually i don't know what's the meaning of setconst etc,
            // if you know, please email me :)
            fprintf(stderr, "DEBUG: found %s\n", cs->name);
            r_val = FETCH_OPND(-1);
            l_val = 0;
            updatetype = "R";
            break;
        }
        case JSOP_ENUMELEM:
        case JSOP_ENUMCONSTELEM:
        {
            fprintf(stderr, "DEBUG: found %s\n", cs->name);
            r_val = FETCH_OPND(-3);
            l_val = FETCH_OPND(-2);
            updatetype = "A";
            break;
        }
        case JSOP_SETXMLNAME:
        case JSOP_SETMETHOD:
        {
            l_val = FETCH_OPND(-2);
            r_val = FETCH_OPND(-1);
            updatetype = "R";
            break;
        }
        default:
            if(0&&cs->format & JOF_SET){
                fprintf(stderr, "DEBUG: %s interpreted but not checked\n", cs->name);
            }
            break;
    }
    if(r_val != 0 &&
       JSVAL_IS_STRING(r_val))
    {
        uint32_t length = 0;
        length = JS_GetStringLength(JSVAL_TO_STRING(r_val)) * sizeof(jschar);
        if(length < MIN_STR_LEN_TO_CHECK){
            goto end;
        }
        int r = 0;
        unsigned char *bytes = NULL;
        jschar *jschars = NULL;
        jschars = JS_GetStringChars(JSVAL_TO_STRING(r_val));
        bytes = (unsigned char *)jschars;
        if(length > 65535){
            //Heapspray DETECTED!
            /* fprintf(stderr,"\nDEBUG: HEAPSPRAY DETECTED!\n"); */

            heapspray_info hsinfo;
            hsinfo = check_heapspray(bytes,length);
            PyObject* alert = NULL;
            PyObject* param = NULL;
            Context* pycx = NULL;
            pycx = (Context*) JS_GetContextPrivate(cx);

            size_t uniqueid = (size_t)pycx + (size_t)l_val;
            
            PyObject *str = PyString_FromString("alert_by_uid");
            PyObject *alert_by_uid = NULL;
            if (str == NULL) goto error;
            alert_by_uid = PyObject_GetAttr((PyObject *)HeapsprayAlertType,str);
            Py_DECREF(str);
            str = NULL;
            if (alert_by_uid == NULL) goto error;

            PyObject *pyuid = Py_BuildValue("i",uniqueid);
            if (PyDict_Contains(alert_by_uid,pyuid)){
                alert = PyDict_GetItem(alert_by_uid,pyuid);
                if(alert == NULL) goto error;

                PyObject *raiseret = PyObject_CallMethod(alert,
                                                         "reraise",
                                                         "sdi{s:s#,s:i,s:s#,s:i}",
                                                         "Previous",
                                                         hsinfo.entropy,
                                                         length,
                                                         "sledge_char",
                                                         &(hsinfo.most_char),
                                                         1,
                                                         "sledge_cnt",
                                                         hsinfo.most_char_cnt,
                                                         "sec_char",
                                                         &(hsinfo.sec_char),
                                                         1,
                                                         "sec_char_cnt",
                                                         hsinfo.sec_char_cnt);
                if(raiseret == NULL) goto error;
                Py_DECREF(raiseret);
                raiseret = NULL;                                                         
            }else{            
                param = Py_BuildValue("isdii{s:s#,s:i,s:s#,s:i}s",
                                      -1,
                                      "Heapspray Detected!",
                                      hsinfo.entropy,
                                      length,
                                      uniqueid,
                                      "sledge_char",
                                      &(hsinfo.most_char),
                                      1,
                                      "sledge_cnt",
                                      hsinfo.most_char_cnt,
                                      "sec_char",
                                      &(hsinfo.sec_char),
                                      1,
                                      "sec_char_cnt",
                                      hsinfo.sec_char_cnt,
                                      updatetype);
                if(param == NULL) goto error;
            
                alert = PyObject_CallObject((PyObject*)HeapsprayAlertType,param);
                Py_DECREF(param);
                param = NULL;
                if(alert == NULL) goto error;
                if(PyList_Append(pycx->alertlist,alert) != 0)
                {
                    goto error;
                }
                Py_DECREF(alert);
                alert = NULL;
            }
            Py_DECREF(pyuid);
            pyuid = NULL;
        }else{
            /* FILE *f; */
            /* char path[100]; */
            /* sprintf(path,"debug/%d.sc",l_val); */
            /* f = fopen(path,"wb"); */
            /* fwrite(bytes,length,1,f); */
            /* fclose(f); */
            
            r = check_buffer(bytes,length);
            if(r >= 0)
            {
                //Shellcode DETECTED!
                /* fprintf(stderr,"\nDEBUG: SHELLCODE DETECTED!\n"); */
                PyObject* alert = NULL;
                PyObject* param = NULL;
                Context* pycx = NULL;
                
                param = Py_BuildValue("iss#i",
                                      -1,
                                      "Shellcode Detected!",
                                      bytes,
                                      length,
                                      r);
                if(param == NULL) goto error;
                
                alert = PyObject_CallObject((PyObject*)ShellcodeAlertType,param);
                Py_DECREF(param);
                param = NULL;
                if(alert == NULL) goto error;
                pycx = (Context*) JS_GetContextPrivate(cx);
                
                if(PyList_Append(pycx->alertlist,alert) != 0)
                {
                    goto error;
                }
                Py_DECREF(alert);
                alert = NULL;
                //TODO: FIXME: is it necesary to DECREF alert?
                
                /*         if rt.malvariables.has_key(l_val): */
                /*             alert = rt.malvariables[l_val] */
                /*         else: */
                /*             alert = Alert(0,l_val,"Shellcode Detected",{"hit":0}) */
                /*             rt.malvariables[l_val]=alert */
                /*             rt.alerts.append(alert) */
                /*         alert.misc["hit"]+=1 */
                
                /*         jschars = JS_GetStringChars(JSVAL_TO_STRING(r_val)) */
                /*         bytes = <char *>jschars */
                /*         length = JS_GetStringLength(JSVAL_TO_STRING(r_val)) */
                /*         s = PyString_FromStringAndSize(bytes, length*2)#sizeof(jschar)) */
                /*         alert.misc["contents"] = s */
                /*         alert.misc["offset"] = r */
                /*         #f = open("shellcodes/"+str(l_val)+".sc","w") */
                /*         #f.write(s) */
                /*         #f.close() */
                /*         #print "DEBUG: !!!SC DETECTED at "+str(l_val)+"="+str(r_val)+"size:"+str(length*2) */
            }
        }
    }
end:
    return JSTRAP_CONTINUE;
error:
    return  JSTRAP_ERROR;
}
Ejemplo n.º 5
0
static PyObject *PyRRD_fetch(
    PyObject UNUSED(*self),
    PyObject * args)
{
    PyObject *r;
    rrd_value_t *data, *datai;
    unsigned long step, ds_cnt;
    time_t    start, end;
    int       argc;
    char    **argv, **ds_namv;

    if (create_args("fetch", args, &argc, &argv) < 0)
        return NULL;

    if (rrd_fetch(argc, argv, &start, &end, &step,
                  &ds_cnt, &ds_namv, &data) == -1) {
        PyErr_SetString(ErrorObject, rrd_get_error());
        rrd_clear_error();
        r = NULL;
    } else {
        /* Return :
           ((start, end, step), (name1, name2, ...), [(data1, data2, ..), ...]) */
        PyObject *range_tup, *dsnam_tup, *data_list, *t;
        unsigned long i, j, row;
        rrd_value_t dv;

        row = (end - start) / step;

        r = PyTuple_New(3);
        range_tup = PyTuple_New(3);
        dsnam_tup = PyTuple_New(ds_cnt);
        data_list = PyList_New(row);
        PyTuple_SET_ITEM(r, 0, range_tup);
        PyTuple_SET_ITEM(r, 1, dsnam_tup);
        PyTuple_SET_ITEM(r, 2, data_list);

        datai = data;

        PyTuple_SET_ITEM(range_tup, 0, PyInt_FromLong((long) start));
        PyTuple_SET_ITEM(range_tup, 1, PyInt_FromLong((long) end));
        PyTuple_SET_ITEM(range_tup, 2, PyInt_FromLong((long) step));

        for (i = 0; i < ds_cnt; i++)
            PyTuple_SET_ITEM(dsnam_tup, i, PyString_FromString(ds_namv[i]));

        for (i = 0; i < row; i++) {
            t = PyTuple_New(ds_cnt);
            PyList_SET_ITEM(data_list, i, t);

            for (j = 0; j < ds_cnt; j++) {
                dv = *(datai++);
                if (isnan(dv)) {
                    PyTuple_SET_ITEM(t, j, Py_None);
                    Py_INCREF(Py_None);
                } else {
                    PyTuple_SET_ITEM(t, j, PyFloat_FromDouble((double) dv));
                }
            }
        }

        for (i = 0; i < ds_cnt; i++)
            rrd_freemem(ds_namv[i]);
        rrd_freemem(ds_namv);   /* rrdtool don't use PyMem_Malloc :) */
        rrd_freemem(data);
    }

    destroy_args(&argv);
    return r;
}
Ejemplo n.º 6
0
static PyObject *
meth_get__name__(PyCFunctionObject *m, void *closure)
{
    return PyString_FromString(m->m_ml->ml_name);
}
Ejemplo n.º 7
0
PyObject *
MeshAttributes_str(PyObject *v)
{
    MeshAttributesObject *obj = (MeshAttributesObject *)v;
    return PyString_FromString(PyMeshAttributes_ToString(obj->data,"").c_str());
}
// @doc - This file contains autoduck documentation
// ---------------------------------------------------
//
PyObject *PyObject_FromNOTIFICATION(NOTIFICATION *n)
{
	PyObject *ret = NULL;
	switch (n->ulEventType) {
		case fnevCriticalError: {
			ERROR_NOTIFICATION &err = n->info.err;
			ret = Py_BuildValue("k(s#iiN)",
					    n->ulEventType,
					    err.lpEntryID, err.cbEntryID,
					    err.scode,
					    err.ulFlags,
					    PyObject_FromMAPIERROR(err.lpMAPIError, err.ulFlags&MAPI_UNICODE, FALSE));
			break;
		}
		case fnevExtended: {
			EXTENDED_NOTIFICATION &ext = n->info.ext;
			ret = Py_BuildValue("k(ks#)", n->ulEventType, ext.ulEvent,
					    ext.pbEventParameters, ext.cb);
			break;
		}
		case fnevNewMail: {
			NEWMAIL_NOTIFICATION &newmail = n->info.newmail;
			PyObject *msg_class = newmail.ulFlags&MAPI_UNICODE?
					PyWinObject_FromWCHAR((const WCHAR *)newmail.lpszMessageClass) :
					PyString_FromString((const char *)newmail.lpszMessageClass);
			if (!msg_class)
				return NULL;
			ret = Py_BuildValue("k(s#s#kNk)",
					    n->ulEventType,
					    newmail.lpEntryID, newmail.cbEntryID,
					    newmail.lpParentID, newmail.cbParentID,
					    newmail.ulFlags,
					    msg_class,
					    newmail.ulMessageFlags);
			break;
		}
		case fnevObjectCopied:
		case fnevObjectCreated:
		case fnevObjectDeleted:
		case fnevObjectModified: 
		case fnevObjectMoved:
		case fnevSearchComplete: {
			OBJECT_NOTIFICATION &obj = n->info.obj;
			PyObject *obArray = PyMAPIObject_FromSPropTagArray(obj.lpPropTagArray);
			if (!obArray)
				return NULL;
			ret = Py_BuildValue("k(s#is#s#s#N)",
					    n->ulEventType,
					    obj.lpEntryID, obj.cbEntryID,
					    obj.ulObjType,
					    obj.lpParentID, obj.cbParentID,
					    obj.lpOldID, obj.cbOldID,
					    obj.lpOldParentID, obj.cbOldParentID,
					    obArray);
			break;
		}
		case fnevTableModified: {
			TABLE_NOTIFICATION &tab = n->info.tab;
			ret = Py_BuildValue("k(kiNNN)",
					    n->ulEventType,
					    tab.ulTableEvent,
					    tab.hResult,
					    PyMAPIObject_FromSPropValue(&tab.propIndex),
					    PyMAPIObject_FromSPropValue(&tab.propPrior),
					    PyMAPIObject_FromSRow(&tab.row));
			break;
		}
		case fnevStatusObjectModified: {
			STATUS_OBJECT_NOTIFICATION &statobj = n->info.statobj;
			ret = Py_BuildValue("k(s#N)",
					    n->ulEventType,
					    statobj.lpEntryID, statobj.cbEntryID,
					    PyMAPIObject_FromSPropValueArray(statobj.lpPropVals, statobj.cValues));
			break;
		}
		default: {
			PyCom_LoggerWarning(NULL, "unknown MAPI notification type %x", n->ulEventType);
			ret = Py_BuildValue("k(O)", n->ulEventType, Py_None);
			break;
		}
	}
	return ret;
}
Ejemplo n.º 9
0
static void
ev_io_on_read(struct ev_loop* mainloop, ev_io* watcher, const int events)
{
  static char read_buf[READ_BUFFER_SIZE];

  Request* request = REQUEST_FROM_WATCHER(watcher);
  read_state read_state;

  ssize_t read_bytes = read(
    request->client_fd,
    read_buf,
    READ_BUFFER_SIZE
  );

  GIL_LOCK(0);

  if (read_bytes == 0) {
    /* Client disconnected */
    read_state = aborted;
    DBG_REQ(request, "Client disconnected");
  } else if (read_bytes < 0) {
    /* Would block or error */
    if(errno == EAGAIN || errno == EWOULDBLOCK) {
      read_state = not_yet_done;
    } else {
      read_state = aborted;
      DBG_REQ(request, "Hit errno %d while read()ing", errno);
    }
  } else {
    /* OK, either expect more data or done reading */
    Request_parse(request, read_buf, (size_t)read_bytes);
    if(request->state.error_code) {
      /* HTTP parse error */
      read_state = done;
      DBG_REQ(request, "Parse error");
      request->current_chunk = PyString_FromString(
        http_error_messages[request->state.error_code]);
      assert(request->iterator == NULL);
    } else if(request->state.parse_finished) {
      /* HTTP parse successful */
      read_state = done;
      bool wsgi_ok = wsgi_call_application(request);
      if (!wsgi_ok) {
        /* Response is "HTTP 500 Internal Server Error" */
        DBG_REQ(request, "WSGI app error");
        assert(PyErr_Occurred());
        PyErr_Print();
        assert(!request->state.chunked_response);
        Py_XCLEAR(request->iterator);
        request->current_chunk = PyString_FromString(
          http_error_messages[HTTP_SERVER_ERROR]);
      }
    } else {
      /* Wait for more data */
      read_state = not_yet_done;
    }
  }

  switch (read_state) {
  case not_yet_done:
    break;
  case done:
    DBG_REQ(request, "Stop read watcher, start write watcher");
    ev_io_stop(mainloop, &request->ev_watcher);
    ev_io_init(&request->ev_watcher, &ev_io_on_write,
               request->client_fd, EV_WRITE);
    ev_io_start(mainloop, &request->ev_watcher);
    break;
  case aborted:
    close_connection(mainloop, request);
    break;
  }

  GIL_UNLOCK(0);
}
Ejemplo n.º 10
0
static PyObject *
PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *rv)
{
	TriggerData *tdata = (TriggerData *) fcinfo->context;
	PyObject   *pltname,
			   *pltevent,
			   *pltwhen,
			   *pltlevel,
			   *pltrelid,
			   *plttablename,
			   *plttableschema;
	PyObject   *pltargs,
			   *pytnew,
			   *pytold;
	PyObject   *volatile pltdata = NULL;
	char	   *stroid;

	PG_TRY();
	{
		pltdata = PyDict_New();
		if (!pltdata)
			PLy_elog(ERROR, "could not create new dictionary while building trigger arguments");

		pltname = PyString_FromString(tdata->tg_trigger->tgname);
		PyDict_SetItemString(pltdata, "name", pltname);
		Py_DECREF(pltname);

		stroid = DatumGetCString(DirectFunctionCall1(oidout,
							   ObjectIdGetDatum(tdata->tg_relation->rd_id)));
		pltrelid = PyString_FromString(stroid);
		PyDict_SetItemString(pltdata, "relid", pltrelid);
		Py_DECREF(pltrelid);
		pfree(stroid);

		stroid = SPI_getrelname(tdata->tg_relation);
		plttablename = PyString_FromString(stroid);
		PyDict_SetItemString(pltdata, "table_name", plttablename);
		Py_DECREF(plttablename);
		pfree(stroid);

		stroid = SPI_getnspname(tdata->tg_relation);
		plttableschema = PyString_FromString(stroid);
		PyDict_SetItemString(pltdata, "table_schema", plttableschema);
		Py_DECREF(plttableschema);
		pfree(stroid);

		if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
			pltwhen = PyString_FromString("BEFORE");
		else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
			pltwhen = PyString_FromString("AFTER");
		else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
			pltwhen = PyString_FromString("INSTEAD OF");
		else
		{
			elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
			pltwhen = NULL;		/* keep compiler quiet */
		}
		PyDict_SetItemString(pltdata, "when", pltwhen);
		Py_DECREF(pltwhen);

		if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
		{
			pltlevel = PyString_FromString("ROW");
			PyDict_SetItemString(pltdata, "level", pltlevel);
			Py_DECREF(pltlevel);

			if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
			{
				pltevent = PyString_FromString("INSERT");

				PyDict_SetItemString(pltdata, "old", Py_None);
				pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
										   tdata->tg_relation->rd_att);
				PyDict_SetItemString(pltdata, "new", pytnew);
				Py_DECREF(pytnew);
				*rv = tdata->tg_trigtuple;
			}
			else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
			{
				pltevent = PyString_FromString("DELETE");

				PyDict_SetItemString(pltdata, "new", Py_None);
				pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
										   tdata->tg_relation->rd_att);
				PyDict_SetItemString(pltdata, "old", pytold);
				Py_DECREF(pytold);
				*rv = tdata->tg_trigtuple;
			}
			else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
			{
				pltevent = PyString_FromString("UPDATE");

				pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
										   tdata->tg_relation->rd_att);
				PyDict_SetItemString(pltdata, "new", pytnew);
				Py_DECREF(pytnew);
				pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
										   tdata->tg_relation->rd_att);
				PyDict_SetItemString(pltdata, "old", pytold);
				Py_DECREF(pytold);
				*rv = tdata->tg_newtuple;
			}
			else
			{
				elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
				pltevent = NULL;	/* keep compiler quiet */
			}

			PyDict_SetItemString(pltdata, "event", pltevent);
			Py_DECREF(pltevent);
		}
		else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
		{
			pltlevel = PyString_FromString("STATEMENT");
			PyDict_SetItemString(pltdata, "level", pltlevel);
			Py_DECREF(pltlevel);

			PyDict_SetItemString(pltdata, "old", Py_None);
			PyDict_SetItemString(pltdata, "new", Py_None);
			*rv = NULL;

			if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
				pltevent = PyString_FromString("INSERT");
			else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
				pltevent = PyString_FromString("DELETE");
			else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
				pltevent = PyString_FromString("UPDATE");
			else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
				pltevent = PyString_FromString("TRUNCATE");
			else
			{
				elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
				pltevent = NULL;	/* keep compiler quiet */
			}

			PyDict_SetItemString(pltdata, "event", pltevent);
			Py_DECREF(pltevent);
		}
		else
			elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);

		if (tdata->tg_trigger->tgnargs)
		{
			/*
			 * all strings...
			 */
			int			i;
			PyObject   *pltarg;

			pltargs = PyList_New(tdata->tg_trigger->tgnargs);
			for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
			{
				pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);

				/*
				 * stolen, don't Py_DECREF
				 */
				PyList_SetItem(pltargs, i, pltarg);
			}
		}
		else
		{
			Py_INCREF(Py_None);
			pltargs = Py_None;
		}
		PyDict_SetItemString(pltdata, "args", pltargs);
		Py_DECREF(pltargs);
	}
	PG_CATCH();
	{
		Py_XDECREF(pltdata);
		PG_RE_THROW();
	}
	PG_END_TRY();

	return pltdata;
}
Ejemplo n.º 11
0
PyObject *
FontAttributes_str(PyObject *v)
{
    FontAttributesObject *obj = (FontAttributesObject *)v;
    return PyString_FromString(PyFontAttributes_ToString(obj->data,"").c_str());
}
Ejemplo n.º 12
0
PyObject *_attachsql_get_library_version(PyObject *self, PyObject *unused)
{
  return PyString_FromString(attachsql_get_library_version());
}
Ejemplo n.º 13
0
static PyObject *
get_fork_state(PyObject *self)
{
    (void)self;
    return PyString_FromString(fork_state_name[fork_state]);
}
/*
 * This routine needs to emulate load_package in import.c in
 * python, but from a DataSectionPtr
 */
PyObject* PyResMgrImportLoader::load_package( const std::string& name,
        DataSectionPtr package )
{
    // We don't erase ourselves from the modules_ list, since whatever
    // we call to process our __init__ script will do it for us.
    std::string moduleName = name;
    std::string::size_type dotPos = name.rfind( "." );
    if ( dotPos != std::string::npos )
    {
        moduleName = name.substr( dotPos + 1 );
    }

    PyObject *module = PyImport_AddModule( name.c_str() );
    if ( module == NULL )
    {
        // Propagate the PyErr up
        return NULL;
    }
    PyObject *moduleDict = PyModule_GetDict( module );
    PyObject *file = PyString_FromString( ( path_ + "/" + moduleName).c_str() );
    if ( file == NULL )
    {
        return NULL;
    }
    PyObject *path = Py_BuildValue( "[O]", file );
    if ( path == NULL )
    {
        Py_DECREF( file );
        return NULL;
    }
    int err = PyDict_SetItemString( moduleDict, "__file__", file );
    Py_DECREF( file );

    if ( err != 0 )
    {
        Py_DECREF( path );
        return NULL;
    }
    err = PyDict_SetItemString( moduleDict, "__path__", path );
    Py_DECREF( path );
    if ( err != 0 )
    {
        return NULL;
    }
    err = PyDict_SetItemString( moduleDict, "__loader__", this );
    if ( err != 0 )
    {
        return NULL;
    }

    // This call was tested in find_module_file earlier.
    moduleCacheEntry packageInit = find_module_file( "__init__", package );

//	TRACE_MSG( "PyResMgrImportLoader(%s)::load_package: processing %s\n",
//		path_.c_str(), name.c_str() );

    switch( packageInit.first )
    {
    case PY_OBJECT:
        return load_compiled_module( name,
                                     packageInit.second->asBinary() );
    case PY_SOURCE:
        return load_source_module( name,
                                   packageInit.second->asBinary(),
                                   package );
    case NOT_FOUND:
    case PKG_DIRECTORY:
    case C_EXTENSION:
        break;
    }
    Py_Return;
}
Ejemplo n.º 15
0
static int
pygvfinfo_setattr(PyGnomeVFSFileInfo *self, const gchar *attr, PyObject *value)
{
    GnomeVFSFileInfo *finfo;

    if (!self->finfo)
	self->finfo = gnome_vfs_file_info_new();
    finfo = self->finfo;

    if (!strcmp(attr, "__members__")) {
	PyErr_SetString(PyExc_TypeError, "readonly attribute");
	return -1;

    } else if (!strcmp(attr, "name")) {
        if (!PyString_Check(value)) {
            	PyErr_SetString(PyExc_TypeError,
                                "'name' attribute must be a string");
                return -1;
        }
	if (finfo->name) g_free(finfo->name);
        finfo->name = g_strdup(PyString_AsString(value));
	return 0;

    } else if (!strcmp(attr, "valid_fields")) {
        if (!PyInt_Check(value)) {
            	PyErr_SetString(PyExc_TypeError,
                                "'valid_fields' attribute must be an int");
                return -1;
        }
	finfo->valid_fields = PyInt_AsLong(value);
        return 0;

    } else if (!strcmp(attr, "type")) {
        if (!PyInt_Check(value)) {
            	PyErr_SetString(PyExc_TypeError,
                                "'type' attribute must be an int");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_TYPE;
	finfo->type = PyInt_AsLong(value);
        return 0;

    } else if (!strcmp(attr, "permissions")) {
        if (!PyInt_Check(value)) {
            	PyErr_SetString(PyExc_TypeError,
                                "'permissions' attribute must be an int");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_PERMISSIONS;
	finfo->permissions = PyInt_AsLong(value);
        return 0;

    } else if (!strcmp(attr, "access")) {
        if (!PyInt_Check(value)) {
            	PyErr_SetString(PyExc_TypeError,
                                "'access' attribute must be an int");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_ACCESS;
	finfo->permissions |= PyInt_AsLong(value);
        return 0;

    } else if (!strcmp(attr, "flags")) {
        if (!PyInt_Check(value)) {
            	PyErr_SetString(PyExc_TypeError,
                                "'flags' attribute must be an int");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_FLAGS;
	finfo->flags = PyInt_AsLong(value);
        return 0;

    } else if (!strcmp(attr, "device")) {
        if (!(PyInt_Check(value) || PyLong_Check(value))) {
            	PyErr_SetString(PyExc_TypeError,
                                "'device' attribute must be an int or long");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_DEVICE;
	if (PyInt_Check(value))
	    finfo->device = PyInt_AsLong(value);
	else
	    finfo->device = PyLong_AsUnsignedLongLong(value);
        return 0;

    } else if (!strcmp(attr, "inode")) {
        if (!(PyInt_Check(value) || PyLong_Check(value))) {
            	PyErr_SetString(PyExc_TypeError,
                                "'inode' attribute must be an int or long");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_INODE;
	if (PyInt_Check(value))
	    finfo->inode = PyInt_AsLong(value);
	else
	    finfo->inode = PyLong_AsUnsignedLongLong(value);
        return 0;

    } else if (!strcmp(attr, "link_count")) {
        if (!(PyInt_Check(value) || PyLong_Check(value))) {
            	PyErr_SetString(PyExc_TypeError,
                                "'link_count' attribute must be an int or long");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_LINK_COUNT;
	if (PyInt_Check(value))
	    finfo->link_count = PyInt_AsLong(value);
	else
	    finfo->link_count = PyLong_AsUnsignedLongLong(value);
        return 0;

    } else if (!strcmp(attr, "uid")) {
        if (!(PyInt_Check(value) || PyLong_Check(value))) {
            	PyErr_SetString(PyExc_TypeError,
                                "'uid' attribute must be an int or long");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_IDS;
	if (PyInt_Check(value))
	    finfo->uid = PyInt_AsLong(value);
	else
	    finfo->uid = PyLong_AsUnsignedLongLong(value);
        return 0;

    } else if (!strcmp(attr, "gid")) {
        if (!(PyInt_Check(value) || PyLong_Check(value))) {
            	PyErr_SetString(PyExc_TypeError,
                                "'gid' attribute must be an int or long");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_IDS;
	if (PyInt_Check(value))
	    finfo->gid = PyInt_AsLong(value);
	else
	    finfo->gid = PyLong_AsUnsignedLongLong(value);
        return 0;

    } else if (!strcmp(attr, "size")) {
        if (!(PyInt_Check(value) || PyLong_Check(value))) {
            	PyErr_SetString(PyExc_TypeError,
                                "'size' attribute must be an int or long");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_SIZE;
	if (PyInt_Check(value))
	    finfo->size = PyInt_AsLong(value);
	else
	    finfo->size = PyLong_AsUnsignedLongLong(value);
        return 0;

    } else if (!strcmp(attr, "block_count")) {
        if (!(PyInt_Check(value) || PyLong_Check(value))) {
            	PyErr_SetString(PyExc_TypeError,
                                "'block_count' attribute must be an int or long");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_BLOCK_COUNT;
	if (PyInt_Check(value))
	    finfo->block_count = PyInt_AsLong(value);
	else
	    finfo->block_count = PyLong_AsUnsignedLongLong(value);
        return 0;

    } else if (!strcmp(attr, "io_block_size")) {
        if (!(PyInt_Check(value) || PyLong_Check(value))) {
            	PyErr_SetString(PyExc_TypeError,
                                "'io_block_size' attribute must be an int or long");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_IO_BLOCK_SIZE;
	if (PyInt_Check(value))
	    finfo->io_block_size = PyInt_AsLong(value);
	else
	    finfo->io_block_size = PyLong_AsUnsignedLongLong(value);
        return 0;

    } else if (!strcmp(attr, "atime")) {
        if (!PyLong_Check(value)) {
            	PyErr_SetString(PyExc_TypeError,
                                "'atime' attribute must be a long");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_ATIME;
	finfo->atime = PyLong_AsUnsignedLongLong(value);
        return 0;

    } else if (!strcmp(attr, "mtime")) {
        if (!PyLong_Check(value)) {
            	PyErr_SetString(PyExc_TypeError,
                                "'mtime' attribute must be a long");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MTIME;
	finfo->mtime = PyLong_AsUnsignedLongLong(value);
        return 0;

    } else if (!strcmp(attr, "ctime")) {
        if (!PyLong_Check(value)) {
            	PyErr_SetString(PyExc_TypeError,
                                "'ctime' attribute must be a long");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_CTIME;
	finfo->ctime = PyLong_AsUnsignedLongLong(value);
        return 0;

    } else if (!strcmp(attr, "symlink_name")) {
        if (!PyString_Check(value)) {
            	PyErr_SetString(PyExc_TypeError,
                                "'symlink_name' attribute must be a string");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_SYMLINK_NAME;
	if (finfo->symlink_name) g_free(finfo->symlink_name);
        finfo->symlink_name = g_strdup(PyString_AsString(value));
	return 0;

    } else if (!strcmp(attr, "mime_type")) {
        if (!PyString_Check(value)) {
            	PyErr_SetString(PyExc_TypeError,
                                "'mime_type' attribute must be a string");
                return -1;
        }
	finfo->valid_fields |= GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
	if (finfo->mime_type) g_free(finfo->mime_type);
        finfo->mime_type = g_strdup(PyString_AsString(value));
	return 0;

    } else {
	PyObject *name = PyString_FromString(attr);
	int ret = PyObject_GenericSetAttr((PyObject *)self, name, value);

	Py_DECREF(name);
	return ret;
    }
}
Ejemplo n.º 16
0
/* Helper function for typy_fields which converts a single field to a
   dictionary.  Returns NULL on error.  */
static PyObject *
convert_field (struct type *type, int field)
{
  PyObject *result = field_new ();
  PyObject *arg;

  if (!result)
    return NULL;

  if (!field_is_static (&TYPE_FIELD (type, field)))
    {
      arg = PyLong_FromLong (TYPE_FIELD_BITPOS (type, field));
      if (!arg)
	goto fail;

      if (PyObject_SetAttrString (result, "bitpos", arg) < 0)
	goto failarg;
    }

  if (TYPE_FIELD_NAME (type, field))
    arg = PyString_FromString (TYPE_FIELD_NAME (type, field));
  else
    {
      arg = Py_None;
      Py_INCREF (arg);
    }
  if (!arg)
    goto fail;
  if (PyObject_SetAttrString (result, "name", arg) < 0)
    goto failarg;

  arg = TYPE_FIELD_ARTIFICIAL (type, field) ? Py_True : Py_False;
  Py_INCREF (arg);
  if (PyObject_SetAttrString (result, "artificial", arg) < 0)
    goto failarg;

  if (TYPE_CODE (type) == TYPE_CODE_CLASS)
    arg = field < TYPE_N_BASECLASSES (type) ? Py_True : Py_False;
  else
    arg = Py_False;
  Py_INCREF (arg);
  if (PyObject_SetAttrString (result, "is_base_class", arg) < 0)
    goto failarg;

  arg = PyLong_FromLong (TYPE_FIELD_BITSIZE (type, field));
  if (!arg)
    goto fail;
  if (PyObject_SetAttrString (result, "bitsize", arg) < 0)
    goto failarg;

  /* A field can have a NULL type in some situations.  */
  if (TYPE_FIELD_TYPE (type, field) == NULL)
    {
      arg = Py_None;
      Py_INCREF (arg);
    }
  else
    arg = type_to_type_object (TYPE_FIELD_TYPE (type, field));
  if (!arg)
    goto fail;
  if (PyObject_SetAttrString (result, "type", arg) < 0)
    goto failarg;

  return result;

 failarg:
  Py_DECREF (arg);
 fail:
  Py_DECREF (result);
  return NULL;
}
Ejemplo n.º 17
0
static PyObject *
pygvfinfo_getattr(PyGnomeVFSFileInfo *self, const gchar *attr)
{
    GnomeVFSFileInfo *finfo;

    finfo = self->finfo;
    if (!strcmp(attr, "__members__")) {
	return Py_BuildValue("[ssssssssssssssssss]", "atime", "block_count",
			     "ctime", "device", "flags", "gid", "inode",
			     "io_block_size", "link_count", "mime_type",
			     "mtime", "name", "permissions", "access", "size",
			     "symlink_name", "type", "uid", "valid_fields");
    } else if (!strcmp(attr, "name")) {
	if (finfo->name)
	    return PyString_FromString(finfo->name);
	Py_INCREF(Py_None);
	return Py_None;
    } else if (!strcmp(attr, "valid_fields")) {
	return PyInt_FromLong(finfo->valid_fields);
    } else if (!strcmp(attr, "type")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_TYPE)) {
	    PyErr_SetString(PyExc_ValueError, "type field has no valid value");
	    return NULL;
	}
	return PyInt_FromLong(finfo->type);
    } else if (!strcmp(attr, "permissions")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_PERMISSIONS)) {
	    PyErr_SetString(PyExc_ValueError,
			    "permissions field has no valid value");
	    return NULL;
	}
	return PyInt_FromLong(finfo->permissions & (~PYGNOME_VFS_ACCESS_BITS));
    } else if (!strcmp(attr, "access")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_ACCESS)) {
	    PyErr_SetString(PyExc_ValueError,
			    "access field has no valid value");
	    return NULL;
	}
	return PyInt_FromLong(finfo->permissions & PYGNOME_VFS_ACCESS_BITS);
    } else if (!strcmp(attr, "flags")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_FLAGS)) {
	    PyErr_SetString(PyExc_ValueError,"flags field has no valid value");
	    return NULL;
	}
	return PyInt_FromLong(finfo->flags);
    } else if (!strcmp(attr, "device")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_DEVICE)) {
	    PyErr_SetString(PyExc_ValueError,
			    "device field has no valid value");
	    return NULL;
	}
	if (finfo->device <= G_MAXLONG)
	    return PyInt_FromLong(finfo->device);
	else
	    return PyLong_FromUnsignedLongLong(finfo->device);
    } else if (!strcmp(attr, "inode")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_INODE)) {
	    PyErr_SetString(PyExc_ValueError,"inode field has no valid value");
	    return NULL;
	}
	if (finfo->inode <= G_MAXLONG)
	    return PyInt_FromLong(finfo->inode);
	else
	    return PyLong_FromUnsignedLongLong(finfo->inode);
    } else if (!strcmp(attr, "link_count")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_LINK_COUNT)) {
	    PyErr_SetString(PyExc_ValueError,
			    "link_count field has no valid value");
	    return NULL;
	}
	if (finfo->link_count < G_MAXLONG)
	    return PyInt_FromLong(finfo->link_count);
	else
	    return PyLong_FromUnsignedLong(finfo->link_count);
    } else if (!strcmp(attr, "uid")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_IDS)) {
	    PyErr_SetString(PyExc_ValueError, "uid field has no valid value");
	    return NULL;
	}
	if (finfo->uid < G_MAXLONG)
	    return PyInt_FromLong(finfo->uid);
	else
	    return PyLong_FromUnsignedLong(finfo->uid);
    } else if (!strcmp(attr, "gid")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_IDS)) {
	    PyErr_SetString(PyExc_ValueError, "gid field has no valid value");
	    return NULL;
	}
	if (finfo->gid < G_MAXLONG)
	    return PyInt_FromLong(finfo->gid);
	else
	    return PyLong_FromUnsignedLong(finfo->gid);
    } else if (!strcmp(attr, "size")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_SIZE)) {
	    PyErr_SetString(PyExc_ValueError, "size field has no valid value");
	    return NULL;
	}
	if (finfo->size <= G_MAXLONG)
	    return PyInt_FromLong(finfo->size);
	else
	    return PyLong_FromUnsignedLongLong(finfo->size);
    } else if (!strcmp(attr, "block_count")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_BLOCK_COUNT)) {
	    PyErr_SetString(PyExc_ValueError,
			    "block_count field has no valid value");
	    return NULL;
	}
	if (finfo->block_count <= G_MAXLONG)
	    return PyInt_FromLong(finfo->block_count);
	else
	    return PyLong_FromUnsignedLongLong(finfo->block_count);
    } else if (!strcmp(attr, "io_block_size")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_IO_BLOCK_SIZE)){
	    PyErr_SetString(PyExc_ValueError,
			    "io_block_size field has no valid value");
	    return NULL;
	}
	if (finfo->io_block_size < G_MAXLONG)
	    return PyInt_FromLong(finfo->io_block_size);
	else
	    return PyLong_FromUnsignedLong(finfo->io_block_size);
    } else if (!strcmp(attr, "atime")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_ATIME)) {
	    PyErr_SetString(PyExc_ValueError,"atime field has no valid value");
	    return NULL;
	}
	return PyLong_FromLongLong(finfo->atime);
    } else if (!strcmp(attr, "mtime")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_MTIME)) {
	    PyErr_SetString(PyExc_ValueError,"mtime field has no valid value");
	    return NULL;
	}
	return PyLong_FromLongLong(finfo->mtime);
    } else if (!strcmp(attr, "ctime")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_CTIME)) {
	    PyErr_SetString(PyExc_ValueError,"ctime field has no valid value");
	    return NULL;
	}
	return PyLong_FromLongLong(finfo->ctime);
    } else if (!strcmp(attr, "symlink_name")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_SYMLINK_NAME)) {
	    PyErr_SetString(PyExc_ValueError,
			    "link_name field has no valid value");
	    return NULL;
	}
	if (finfo->symlink_name)
	    return PyString_FromString(finfo->symlink_name);
	Py_INCREF(Py_None);
	return Py_None;
    } else if (!strcmp(attr, "mime_type")) {
	if (!(finfo->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE)) {
	    PyErr_SetString(PyExc_ValueError,
			    "mime_type field has no valid value");
	    return NULL;
	}
	if (finfo->mime_type)
	    return PyString_FromString(finfo->mime_type);
	Py_INCREF(Py_None);
	return Py_None;
    } else {
	PyObject *name = PyString_FromString(attr);
	PyObject *ret = PyObject_GenericGetAttr((PyObject *)self, name);

	Py_DECREF(name);
	return ret;
    }
}
Ejemplo n.º 18
0
static PyObject *
get_line_buffer(PyObject *self, PyObject *noarg)
{
	return PyString_FromString(rl_line_buffer);
}
static PlumaPlugin *
pluma_plugin_loader_iface_load (PlumaPluginLoader *loader,
				PlumaPluginInfo   *info,
				const gchar       *path)
{
	PlumaPluginLoaderPython *pyloader = PLUMA_PLUGIN_LOADER_PYTHON (loader);
	PyObject *main_module, *main_locals, *pytype;
	PyObject *pymodule, *fromlist;
	gchar *module_name;
	PlumaPlugin *result;
	
	if (pyloader->priv->init_failed)
	{
		g_warning ("Cannot load python plugin Python '%s' since pluma was"
		           "not able to initialize the Python interpreter.",
		           pluma_plugin_info_get_name (info));
		return NULL;
	}
	
	/* see if py definition for the plugin is already loaded */
	result = new_plugin_from_info (pyloader, info);
	
	if (result != NULL)
		return result;
	
	main_module = PyImport_AddModule ("pluma.plugins");
	if (main_module == NULL)
	{
		g_warning ("Could not get pluma.plugins.");
		return NULL;
	}
	
	/* If we have a special path, we register it */
	if (path != NULL)
	{
		PyObject *sys_path = PySys_GetObject ("path");
		PyObject *pypath = PyString_FromString (path);

		if (PySequence_Contains (sys_path, pypath) == 0)
			PyList_Insert (sys_path, 0, pypath);

		Py_DECREF (pypath);
	}
	
	main_locals = PyModule_GetDict (main_module);
	
	/* we need a fromlist to be able to import modules with a '.' in the
	   name. */
	fromlist = PyTuple_New(0);
	module_name = g_strdup (pluma_plugin_info_get_module_name (info));
	
	pymodule = PyImport_ImportModuleEx (module_name, 
					    main_locals, 
					    main_locals, 
					    fromlist);
	
	Py_DECREF(fromlist);

	if (!pymodule)
	{
		g_free (module_name);
		PyErr_Print ();
		return NULL;
	}

	PyDict_SetItemString (main_locals, module_name, pymodule);
	g_free (module_name);
	
	pytype = find_python_plugin_type (info, pymodule);
	
	if (pytype)
		return add_python_info (pyloader, info, pymodule, path, pytype);

	return NULL;
}
Ejemplo n.º 20
0
char* sendAndRecieve(const char* url) {
	Py_Initialize();

	PyObject *pArgs, *pValue, *pFunc;
	PyObject *pGlobal = PyDict_New();
	PyObject *pLocal;

	PyRun_SimpleString("import types,sys");

	//create the new module in python
	PyRun_SimpleString("mymod = types.ModuleType(\"mymod\")");

	//add it to the sys modules so that it can be imported by other modules
	PyRun_SimpleString("sys.modules[\"mymod\"] = mymod");

	//import sys so that path will be available in mymod so that other/newly created modules can be imported
	PyRun_SimpleString("exec 'import sys' in mymod.__dict__");

	//import it to the current python interpreter
	PyObject *pNewMod = PyImport_Import(PyString_FromString("mymod"));

	//Get the dictionary object from my module so I can pass this to PyRun_String
	pLocal = PyModule_GetDict(pNewMod);

	//import urllib2 to global namespace
	PyMapping_SetItemString(pGlobal, "urllib2",
			PyImport_ImportModule("urllib2"));

	//Define my function in the newly created module
	pValue =
			PyRun_String("def get(url):\n\treturn urllib2.urlopen(url).read()\n", Py_file_input, pGlobal, pLocal);
	Py_DECREF(pValue);

	//Get a pointer to the function I just defined
	pFunc = PyObject_GetAttrString(pNewMod, "get");
	if (pFunc == NULL) {
#ifdef DEBUG
		PyErr_Print();
#endif
		return NULL;
	}

	//Build a tuple to hold my arguments (just the number 4 in this case)
	pArgs = PyTuple_New(1);
	pValue = PyString_FromString(url);
	PyTuple_SetItem(pArgs, 0, pValue);

	//Call my function, passing it the number four
	pValue = PyObject_CallObject(pFunc, pArgs);
	if (pValue == NULL) {
#ifdef DEBUG
		PyErr_Print();
#endif
		return NULL;
	}

	Py_DECREF(pArgs);
	char* result = PyString_AsString(pValue);
	if (result == NULL) {
#ifdef DEBUG
		PyErr_Print();
#endif
		return NULL;
	}

	Py_DECREF(pValue);
	Py_XDECREF(pFunc);
	Py_DECREF(pNewMod);
	Py_Finalize();

	return result;
}
Ejemplo n.º 21
0
PyObject *eterm_to_py(ETERM * obj) {
	int i;
	int count;
	ETERM *obj2;
	PyObject *eobj = NULL;

	if (obj == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	}

	switch (ERL_TYPE(obj)) {

	case ERL_CONS:
	case ERL_NIL:
		count = erl_length(obj);
		eobj = PyList_New(0);
		for (i = 0; i < count; i++) {
			obj2 = erl_hd(obj);
			PyList_Append(eobj, eterm_to_py(obj2));
			obj = erl_tl(obj);
		}
		break;
	case ERL_TUPLE:
		eobj = PyTuple_New(erl_size(obj));
		for (i = 1; i <= erl_size(obj); i++) {
			obj2 = erl_element(i, obj);
			PyTuple_SetItem(eobj, i - 1, eterm_to_py(obj2));
		}
		break;
	case ERL_ATOM:
		eobj = PyString_FromStringAndSize(ERL_ATOM_PTR(obj), ERL_ATOM_SIZE(obj));
		break;
	case ERL_INTEGER:
		eobj = PyInt_FromLong(ERL_INT_VALUE(obj));
		break;
	case ERL_BINARY:
		fprintf(stderr, "FOUND A BINARY %.*s\n", ERL_BIN_SIZE(obj), ERL_BIN_PTR(obj));
		break;
	case ERL_PID:
		eobj = PyDict_New();
		if (PyDict_SetItemString(eobj, "node", PyString_FromString(ERL_PID_NODE(obj)))) {
			PyErr_Print();
			break;
		}
		if (PyDict_SetItemString(eobj, "number", PyInt_FromLong(ERL_PID_NUMBER(obj)))) {
			PyErr_Print();
			break;
		}
		if (PyDict_SetItemString(eobj, "serial", PyInt_FromLong(ERL_PID_SERIAL(obj)))) {
			PyErr_Print();
			break;
		}
		if (PyDict_SetItemString(eobj, "creation", PyInt_FromLong(ERL_PID_CREATION(obj)))) {
			PyErr_Print();
			break;
		}
	default:
		fprintf(stderr, "UNMANAGED ETERM TYPE: %d\n", ERL_TYPE(obj));
		break;

	}

	if (eobj == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	}

	return eobj;
}
Ejemplo n.º 22
0
PyObject *
LDAP_get_option(LDAPObject *self, int option)
{
    int res;
    int intval;
    struct timeval *tv;
    LDAPAPIInfo apiinfo;
    LDAPControl **lcs;
    LDAPControl *lc;
    char *strval;
    PyObject *extensions, *v, *tup;
    Py_ssize_t i, num_extensions, num_controls;
    LDAP *ld;

    ld = self ? self->ldap : NULL;

    switch(option) {
    case LDAP_OPT_API_INFO:
	    apiinfo.ldapai_info_version = LDAP_API_INFO_VERSION;
	    if (self) LDAP_BEGIN_ALLOW_THREADS(self);
	    res = ldap_get_option( ld, option, &apiinfo );
	    if (self) LDAP_END_ALLOW_THREADS(self);
	    if (res != LDAP_OPT_SUCCESS)
		return option_error(res, "ldap_get_option");
    
	    /* put the extensions into tuple form */
	    num_extensions = 0;
	    while (apiinfo.ldapai_extensions[num_extensions])
		num_extensions++;
	    extensions = PyTuple_New(num_extensions);
	    for (i = 0; i < num_extensions; i++)
		PyTuple_SET_ITEM(extensions, i,
		    PyString_FromString(apiinfo.ldapai_extensions[i]));

	    /* return api info as a dictionary */
	    v = Py_BuildValue("{s:i, s:i, s:i, s:s, s:i, s:O}",
		    "info_version",     apiinfo.ldapai_info_version,
		    "api_version",      apiinfo.ldapai_api_version,
		    "protocol_version", apiinfo.ldapai_protocol_version,
		    "vendor_name",      apiinfo.ldapai_vendor_name,
		    "vendor_version",   apiinfo.ldapai_vendor_version,
		    "extensions",       extensions);

	    if (apiinfo.ldapai_vendor_name)
		ldap_memfree(apiinfo.ldapai_vendor_name);
	    for (i = 0; i < num_extensions; i++)
		ldap_memfree(apiinfo.ldapai_extensions[i]);
	    ldap_memfree(apiinfo.ldapai_extensions);
	    Py_DECREF(extensions);

	    return v;

#ifdef HAVE_SASL
    case LDAP_OPT_X_SASL_SSF:
#endif
    case LDAP_OPT_REFERRALS:
    case LDAP_OPT_RESTART:
    case LDAP_OPT_DEREF:
    case LDAP_OPT_SIZELIMIT:
    case LDAP_OPT_TIMELIMIT:
    case LDAP_OPT_PROTOCOL_VERSION:
    case LDAP_OPT_ERROR_NUMBER:
    case LDAP_OPT_DEBUG_LEVEL:
#ifdef HAVE_TLS
    case LDAP_OPT_X_TLS:
    case LDAP_OPT_X_TLS_REQUIRE_CERT:
#ifdef LDAP_OPT_X_TLS_CRLCHECK
    case LDAP_OPT_X_TLS_CRLCHECK:
#endif
#ifdef LDAP_OPT_X_TLS_PROTOCOL_MIN
    case LDAP_OPT_X_TLS_PROTOCOL_MIN:
#endif
#endif
#ifdef HAVE_SASL
    case LDAP_OPT_X_SASL_SSF_MIN:
    case LDAP_OPT_X_SASL_SSF_MAX:
#endif
#ifdef LDAP_OPT_X_SASL_NOCANON
    case LDAP_OPT_X_SASL_NOCANON:
#endif
#ifdef LDAP_OPT_CONNECT_ASYNC
    case LDAP_OPT_CONNECT_ASYNC:
#endif
#ifdef LDAP_OPT_X_KEEPALIVE_IDLE
    case LDAP_OPT_X_KEEPALIVE_IDLE:
#endif
#ifdef LDAP_OPT_X_KEEPALIVE_PROBES
    case LDAP_OPT_X_KEEPALIVE_PROBES:
#endif
#ifdef LDAP_OPT_X_KEEPALIVE_INTERVAL
    case LDAP_OPT_X_KEEPALIVE_INTERVAL:
#endif
	    /* Integer-valued options */
	    if (self) LDAP_BEGIN_ALLOW_THREADS(self);
	    res = ldap_get_option(ld, option, &intval);
	    if (self) LDAP_END_ALLOW_THREADS(self);
	    if (res != LDAP_OPT_SUCCESS)
		return option_error(res, "ldap_get_option");
	    return PyInt_FromLong(intval);

    case LDAP_OPT_HOST_NAME:
    case LDAP_OPT_URI:
#ifdef LDAP_OPT_DEFBASE
    case LDAP_OPT_DEFBASE:
#endif
    case LDAP_OPT_ERROR_STRING:
    case LDAP_OPT_MATCHED_DN:
#ifdef HAVE_TLS
    case LDAP_OPT_X_TLS_CACERTFILE:
    case LDAP_OPT_X_TLS_CACERTDIR:
    case LDAP_OPT_X_TLS_CERTFILE:
    case LDAP_OPT_X_TLS_KEYFILE:
    case LDAP_OPT_X_TLS_CIPHER_SUITE:
    case LDAP_OPT_X_TLS_RANDOM_FILE:
    case LDAP_OPT_X_TLS_DHFILE:
#ifdef LDAP_OPT_X_TLS_CRLFILE
    case LDAP_OPT_X_TLS_CRLFILE:
#endif
#ifdef LDAP_OPT_X_TLS_PACKAGE
    case LDAP_OPT_X_TLS_PACKAGE:
#endif
#endif
#ifdef HAVE_SASL
    case LDAP_OPT_X_SASL_SECPROPS:
    case LDAP_OPT_X_SASL_MECH:
    case LDAP_OPT_X_SASL_REALM:
    case LDAP_OPT_X_SASL_AUTHCID:
    case LDAP_OPT_X_SASL_AUTHZID:
#ifdef LDAP_OPT_X_SASL_USERNAME
    case LDAP_OPT_X_SASL_USERNAME:
#endif
#endif
	    /* String-valued options */
	    if (self) LDAP_BEGIN_ALLOW_THREADS(self);
	    res = ldap_get_option(ld, option, &strval);
	    if (self) LDAP_END_ALLOW_THREADS(self);
	    if (res != LDAP_OPT_SUCCESS)
		return option_error(res, "ldap_get_option");
	    if (strval == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	    }
	    v = PyString_FromString(strval);
	    ldap_memfree(strval);
	    return v;

    case LDAP_OPT_TIMEOUT:
    case LDAP_OPT_NETWORK_TIMEOUT:
	    /* Double-valued timeval options */
	    if (self) LDAP_BEGIN_ALLOW_THREADS(self);
	    res = ldap_get_option(ld, option, &tv);
	    if (self) LDAP_END_ALLOW_THREADS(self);
	    if (res != LDAP_OPT_SUCCESS)
		return option_error(res, "ldap_get_option");
	    if (tv == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	    }
	    v = PyFloat_FromDouble(
              (double) tv->tv_sec + ( (double) tv->tv_usec / 1000000.0 )
            );
	    ldap_memfree(tv);
	    return v;

    case LDAP_OPT_SERVER_CONTROLS:
    case LDAP_OPT_CLIENT_CONTROLS:
	    if (self) LDAP_BEGIN_ALLOW_THREADS(self);
	    res = ldap_get_option(ld, option, &lcs);
	    if (self) LDAP_END_ALLOW_THREADS(self);

	    if (res != LDAP_OPT_SUCCESS)
		return option_error(res, "ldap_get_option");

            if (lcs == NULL)
                return PyList_New(0);
            
            /* Get the number of controls */
            num_controls = 0;
            while (lcs[num_controls])
                num_controls++;

            /* We'll build a list of controls, with each control a tuple */
            v = PyList_New(num_controls);
            for (i = 0; i < num_controls; i++) {
                lc = lcs[i];
                tup = Py_BuildValue("(sbs)", 
                                    lc->ldctl_oid,
                                    lc->ldctl_iscritical,
                                    lc->ldctl_value.bv_val);
                PyList_SET_ITEM(v, i, tup);
            }
            
            ldap_controls_free(lcs);

            return v;
            
    default:
	    PyErr_Format(PyExc_ValueError, "unknown option %d", option);
	    return NULL;
    }
}
Ejemplo n.º 23
0
// copy current artcle for back compatible use only
// for new coder please use getArticle
static PyObject *qterm_copyArticle(PyObject *, PyObject *args)
{
	long lp;
	if (!PyArg_ParseTuple(args, "l", &lp))
		return NULL;

	Window *pWin=(Window*)lp;

	QStringList strList;
	QString strArticle;
	while(1)
	{
		// check it there is duplicated string
		// it starts from the end in the range of one screen height
		// so this is a non-greedy match
		QString strTemp = pWin->stripWhitespace(
				pWin->m_pBuffer->screen(0)->getText());
		int i=0;
		int start=0;
		for(QStringList::Iterator it=strList.fromLast();
	it!=strList.begin(), i < pWin->m_pBuffer->line()-1; // not exceeeding the last screen
			--it, i++)
		{
			if(*it!=strTemp)
				continue;
			QStringList::Iterator it2 = it;
			bool dup=true;
			// match more to see if its duplicated
			for(int j=0; j<=i; j++, it2++)
			{
				QString str1 = pWin->stripWhitespace(
					pWin->m_pBuffer->screen(j)->getText());
				if(*it2!=str1)
				{
					dup = false;
					break;
				}
			}
			if(dup)
			{
				// set the start point
				start = i+1;
				break;
			}
		}
		// add new lines
		for(i=start;i<pWin->m_pBuffer->line()-1;i++)
			strList+=pWin->stripWhitespace(
			pWin->m_pBuffer->screen(i)->getText());

		// the end of article
		if( pWin->m_pBuffer->screen(
		pWin->m_pBuffer->line()-1)->getText().find("%") == -1 )
			break;
		// continue
		pWin->m_pTelnet->write(" ", 1);
		
		if(!pWin->m_wcWaiting.wait(10000))	// timeout
			break;
	}
	#if defined(_OS_WIN32_) || defined(Q_OS_WIN32)
	strArticle = strList.join("\r\n");
	#else
	strArticle = strList.join("\n");
	#endif
	
	PyObject *py_text = PyString_FromString(strArticle.toLocal8Bit);

	Py_INCREF(py_text);
	return py_text;
}
Ejemplo n.º 24
0
void XBPyThread::Process()
{
  CLog::Log(LOGDEBUG,"Python thread: start processing");

  int m_Py_file_input = Py_file_input;

  // get the global lock
  PyEval_AcquireLock();
  PyThreadState* state = Py_NewInterpreter();
  if (!state)
  {
    PyEval_ReleaseLock();
    CLog::Log(LOGERROR,"Python thread: FAILED to get thread state!");
    return;
  }
  // swap in my thread state
  PyThreadState_Swap(state);

  m_pExecuter->InitializeInterpreter();

  CLog::Log(LOGDEBUG, "%s - The source file to load is %s", __FUNCTION__, m_source);

  // get path from script file name and add python path's
  // this is used for python so it will search modules from script path first
  CStdString scriptDir;
  CUtil::GetDirectory(_P(m_source), scriptDir);
  CUtil::RemoveSlashAtEnd(scriptDir);
  CStdString path = scriptDir;

  // add on any addon modules the user has installed
  ADDON::VECADDONS addons;
  ADDON::CAddonMgr::Get().GetAddons(ADDON::ADDON_SCRIPT_MODULE, addons);
  for (unsigned int i = 0; i < addons.size(); ++i)
    path += PY_PATH_SEP + _P(addons[i]->LibPath());

  // and add on whatever our default path is
  path += PY_PATH_SEP;

#if (defined USE_EXTERNAL_PYTHON)
  {
    // we want to use sys.path so it includes site-packages
    // if this fails, default to using Py_GetPath
    PyObject *sysMod(PyImport_ImportModule("sys")); // must call Py_DECREF when finished
    PyObject *sysModDict(PyModule_GetDict(sysMod)); // borrowed ref, no need to delete
    PyObject *pathObj(PyDict_GetItemString(sysModDict, "path")); // borrowed ref, no need to delete

    if( pathObj && PyList_Check(pathObj) )
    {
      for( int i = 0; i < PyList_Size(pathObj); i++ )
      {
        PyObject *e = PyList_GetItem(pathObj, i); // borrowed ref, no need to delete
        if( e && PyString_Check(e) )
        {
            path += PyString_AsString(e); // returns internal data, don't delete or modify
            path += PY_PATH_SEP;
        }
      }
    }
    else
    {
      path += Py_GetPath();
    }
    Py_DECREF(sysMod); // release ref to sysMod
  }
#else
  path += Py_GetPath();
#endif

  // set current directory and python's path.
  if (m_argv != NULL)
    PySys_SetArgv(m_argc, m_argv);

  CLog::Log(LOGDEBUG, "%s - Setting the Python path to %s", __FUNCTION__, path.c_str());

  PySys_SetPath((char *)path.c_str());

  CLog::Log(LOGDEBUG, "%s - Entering source directory %s", __FUNCTION__, scriptDir.c_str());

  PyObject* module = PyImport_AddModule((char*)"__main__");
  PyObject* moduleDict = PyModule_GetDict(module);

  // when we are done initing we store thread state so we can be aborted
  PyThreadState_Swap(NULL);
  PyEval_ReleaseLock();

  // we need to check if we was asked to abort before we had inited
  bool stopping = false;
  { CSingleLock lock(m_pExecuter->m_critSection);
    m_threadState = state;
    stopping = m_stopping;
  }

  PyEval_AcquireLock();
  PyThreadState_Swap(state);

  xbp_chdir(scriptDir.c_str());

  if (!stopping)
  {
    if (m_type == 'F')
    {
      // run script from file
      FILE *fp = fopen_utf8(_P(m_source).c_str(), "r");
      if (fp)
      {
        PyObject *f = PyString_FromString(_P(m_source).c_str());
        PyDict_SetItemString(moduleDict, "__file__", f);
        Py_DECREF(f);
        PyRun_File(fp, _P(m_source).c_str(), m_Py_file_input, moduleDict, moduleDict);
        fclose(fp);
      }
      else
        CLog::Log(LOGERROR, "%s not found!", m_source);
    }
    else
    {
      //run script
      PyRun_String(m_source, m_Py_file_input, moduleDict, moduleDict);
    }
  }

  if (!PyErr_Occurred())
    CLog::Log(LOGINFO, "Scriptresult: Success");
  else if (PyErr_ExceptionMatches(PyExc_SystemExit))
    CLog::Log(LOGINFO, "Scriptresult: Aborted");
  else
  {
    PyObject* exc_type;
    PyObject* exc_value;
    PyObject* exc_traceback;
    PyObject* pystring;
    pystring = NULL;

    PyErr_Fetch(&exc_type, &exc_value, &exc_traceback);
    if (exc_type == 0 && exc_value == 0 && exc_traceback == 0)
    {
      CLog::Log(LOGINFO, "Strange: No Python exception occured");
    }
    else
    {
      if (exc_type != NULL && (pystring = PyObject_Str(exc_type)) != NULL && (PyString_Check(pystring)))
      {
          PyObject *tracebackModule;

          CLog::Log(LOGINFO, "-->Python script returned the following error<--");
          CLog::Log(LOGERROR, "Error Type: %s", PyString_AsString(PyObject_Str(exc_type)));
          if (PyObject_Str(exc_value))
            CLog::Log(LOGERROR, "Error Contents: %s", PyString_AsString(PyObject_Str(exc_value)));

          tracebackModule = PyImport_ImportModule((char*)"traceback");
          if (tracebackModule != NULL)
          {
            PyObject *tbList, *emptyString, *strRetval;

            tbList = PyObject_CallMethod(tracebackModule, (char*)"format_exception", (char*)"OOO", exc_type, exc_value == NULL ? Py_None : exc_value, exc_traceback == NULL ? Py_None : exc_traceback);
            emptyString = PyString_FromString("");
            strRetval = PyObject_CallMethod(emptyString, (char*)"join", (char*)"O", tbList);

            CLog::Log(LOGERROR, "%s", PyString_AsString(strRetval));

            Py_DECREF(tbList);
            Py_DECREF(emptyString);
            Py_DECREF(strRetval);
            Py_DECREF(tracebackModule);
          }
          CLog::Log(LOGINFO, "-->End of Python script error report<--");
      }
      else
      {
        pystring = NULL;
        CLog::Log(LOGINFO, "<unknown exception type>");
      }

      CGUIDialogKaiToast *pDlgToast = (CGUIDialogKaiToast*)g_windowManager.GetWindow(WINDOW_DIALOG_KAI_TOAST);
      if (pDlgToast)
      {
        CStdString desc;
        CStdString path;
        CStdString script;
        CUtil::Split(m_source, path, script);
        if (script.Equals("default.py"))
        {
          CStdString path2;
          CUtil::RemoveSlashAtEnd(path);
          CUtil::Split(path, path2, script);
        }

        desc.Format(g_localizeStrings.Get(2100), script);
        pDlgToast->QueueNotification(CGUIDialogKaiToast::Error, g_localizeStrings.Get(257), desc);
      }
    }

    Py_XDECREF(exc_type);
    Py_XDECREF(exc_value); // caller owns all 3
    Py_XDECREF(exc_traceback); // already NULL'd out
    Py_XDECREF(pystring);
  }

  PyObject *m = PyImport_AddModule((char*)"xbmc");
  if(!m || PyObject_SetAttrString(m, (char*)"abortRequested", PyBool_FromLong(1)))
    CLog::Log(LOGERROR, "Scriptresult: failed to set abortRequested");

  // make sure all sub threads have finished
  for(PyThreadState* s = state->interp->tstate_head, *old = NULL; s;)
  {
    if(s == state)
    {
      s = s->next;
      continue;
    }
    if(old != s)
    {
      CLog::Log(LOGINFO, "Scriptresult: Waiting on thread %"PRIu64, (uint64_t)s->thread_id);
      old = s;
    }
    Py_BEGIN_ALLOW_THREADS
    Sleep(100);
    Py_END_ALLOW_THREADS
    s = state->interp->tstate_head;
  }

  // pending calls must be cleared out
  PyXBMC_ClearPendingCalls(state);

  PyThreadState_Swap(NULL);
  PyEval_ReleaseLock();

  { CSingleLock lock(m_pExecuter->m_critSection);
    m_threadState = NULL;
  }

  PyEval_AcquireLock();
  PyThreadState_Swap(state);

  m_pExecuter->DeInitializeInterpreter();

  Py_EndInterpreter(state);
  PyThreadState_Swap(NULL);

  PyEval_ReleaseLock();
}
Ejemplo n.º 25
0
static PyObject *PyRRD_xport(
    PyObject UNUSED(*self),
    PyObject * args)
{
    PyObject *r;
    int       argc, xsize;
    char    **argv, **legend_v;
    time_t    start, end;
    unsigned long step, col_cnt;
    rrd_value_t *data, *datai;

    if (create_args("xport", args, &argc, &argv) < 0)
        return NULL;

    if (rrd_xport(argc, argv, &xsize, &start, &end,
                  &step, &col_cnt, &legend_v, &data) == -1) {
        PyErr_SetString(ErrorObject, rrd_get_error());
        rrd_clear_error();
        r = NULL;
    } else {
        PyObject *meta_dict, *data_list, *legend_list, *t;
        unsigned long i, j;
        rrd_value_t dv;

        unsigned long row_cnt = ((end - start) / step);

        r = PyDict_New();
        meta_dict = PyDict_New();
        legend_list = PyList_New(col_cnt);
        data_list = PyList_New(row_cnt);
        PyDict_SetItem(r, PyString_FromString("meta"), meta_dict);
        PyDict_SetItem(r, PyString_FromString("data"), data_list);

        datai = data;

        PyDict_SetItem(meta_dict, PyString_FromString("start"), PyInt_FromLong((long) start));
        PyDict_SetItem(meta_dict, PyString_FromString("end"), PyInt_FromLong((long) end));
        PyDict_SetItem(meta_dict, PyString_FromString("step"), PyInt_FromLong((long) step));
        PyDict_SetItem(meta_dict, PyString_FromString("rows"), PyInt_FromLong((long) row_cnt));
        PyDict_SetItem(meta_dict, PyString_FromString("columns"), PyInt_FromLong((long) col_cnt));
        PyDict_SetItem(meta_dict, PyString_FromString("legend"), legend_list);

        for (i = 0; i < col_cnt; i++) {
            PyList_SET_ITEM(legend_list, i, PyString_FromString(legend_v[i]));
        }

        for (i = 0; i < row_cnt; i++) {
            t = PyTuple_New(col_cnt);
            PyList_SET_ITEM(data_list, i, t);

            for (j = 0; j < col_cnt; j++) {
                dv = *(datai++);
                if (isnan(dv)) {
                    PyTuple_SET_ITEM(t, j, Py_None);
                    Py_INCREF(Py_None);
                } else {
                    PyTuple_SET_ITEM(t, j, PyFloat_FromDouble((double) dv));
                }
            }
        }

        for (i = 0; i < col_cnt; i++) {
            rrd_freemem(legend_v[i]);
        }
        rrd_freemem(legend_v);
        rrd_freemem(data);
    }
    destroy_args(&argv);
    return r;
}
Ejemplo n.º 26
0
static PyObject *
swig_varlink_repr(swig_varlinkobject *v)
{
  v = v;
  return PyString_FromString("<Global variables>");
}