Пример #1
0
PyObject *PyObject_FromPROPVARIANT( PROPVARIANT *pVar )
{
	switch (pVar->vt) {
		case VT_EMPTY:
		case VT_NULL:
		case VT_ILLEGAL:
			Py_INCREF(Py_None);
			return Py_None;
		case VT_I1:
			return PyInt_FromLong(pVar->cVal);
		case VT_I1|VT_VECTOR:
			return VectorToSeq(pVar->cac.pElems, pVar->cac.cElems, PyWinObject_FromCHAR);
		case VT_UI1:
			return PyInt_FromLong(pVar->bVal);
		case VT_UI1|VT_VECTOR:
			return VectorToSeq(pVar->caub.pElems, pVar->caub.cElems, PyWinObject_FromUCHAR);
		case VT_I2:
			return PyInt_FromLong(pVar->iVal);
		case VT_I2|VT_VECTOR:
			return VectorToSeq(pVar->cai.pElems, pVar->cai.cElems, PyWinObject_FromSHORT);
		case VT_UI2:
			return PyInt_FromLong(pVar->uiVal);
		case VT_UI2|VT_VECTOR:
			return VectorToSeq(pVar->caui.pElems, pVar->caui.cElems, PyWinObject_FromUSHORT);
		case VT_I4:
			return PyInt_FromLong(pVar->lVal);
		case VT_I4|VT_VECTOR:
			return VectorToSeq(pVar->cal.pElems, pVar->cal.cElems, PyInt_FromLong);
		case VT_INT:
			return PyInt_FromLong(pVar->intVal);
		case VT_UI4:
			return PyLong_FromUnsignedLong(pVar->ulVal);
		case VT_UI4|VT_VECTOR:
			return VectorToSeq(pVar->caul.pElems, pVar->caul.cElems, PyLong_FromUnsignedLong);
		case VT_UINT:
			return PyLong_FromUnsignedLong(pVar->uintVal);
		case VT_I8:
			return PyWinObject_FromLARGE_INTEGER(pVar->hVal);
		case VT_I8|VT_VECTOR:
			return VectorToSeq<LARGE_INTEGER>(pVar->cah.pElems, pVar->cah.cElems, PyWinObject_FromLARGE_INTEGER);
		case VT_UI8:
			return PyWinObject_FromULARGE_INTEGER(pVar->uhVal);
		case VT_UI8|VT_VECTOR:
			return VectorToSeq<ULARGE_INTEGER>(pVar->cauh.pElems, pVar->cauh.cElems, PyWinObject_FromULARGE_INTEGER);
		case VT_R4:
			return PyFloat_FromDouble(pVar->fltVal);
		case VT_R4|VT_VECTOR:
			return VectorToSeq(pVar->caflt.pElems, pVar->caflt.cElems, PyWinObject_FromFLOAT);
		case VT_R8:
			return PyFloat_FromDouble(pVar->dblVal);
		case VT_R8|VT_VECTOR:
			return VectorToSeq(pVar->cadbl.pElems, pVar->cadbl.cElems, PyFloat_FromDouble);
		case VT_CY:
			return PyObject_FromCurrency(pVar->cyVal);
		case VT_CY|VT_VECTOR:
			return VectorToSeq<CY>(pVar->cacy.pElems, pVar->cacy.cElems, PyObject_FromCurrency);
		case VT_DATE:
			return PyWinObject_FromDATE(pVar->date);
		case VT_DATE|VT_VECTOR:
			return VectorToSeq(pVar->cadate.pElems, pVar->cadate.cElems, PyWinObject_FromDATE);
		case VT_BSTR:
			return PyWinObject_FromBstr(pVar->bstrVal);
		case VT_BSTR|VT_VECTOR:
			return VectorToSeq(pVar->cabstr.pElems, pVar->cabstr.cElems, PyWinObject_FromVT_BSTR);
		case VT_BOOL:
			return PyWinObject_FromVARIANT_BOOL(pVar->boolVal);
		case VT_BOOL|VT_VECTOR:
			return VectorToSeq(pVar->cabool.pElems, pVar->cabool.cElems, PyWinObject_FromVARIANT_BOOL);
		case VT_ERROR:
			return PyInt_FromLong(pVar->scode);
		case VT_ERROR|VT_VECTOR:
			return VectorToSeq(pVar->cascode.pElems, pVar->cascode.cElems, PyInt_FromLong);
		case VT_FILETIME:
			return PyWinObject_FromFILETIME(pVar->filetime);
		case VT_FILETIME|VT_VECTOR:
			return VectorToSeq<FILETIME>(pVar->cafiletime.pElems, pVar->cafiletime.cElems, PyWinObject_FromFILETIME);
		case VT_LPSTR:
			if (pVar->pszVal == NULL) {
				Py_INCREF(Py_None);
				return Py_None;
			}
			return PyWinCoreString_FromString(pVar->pszVal);
		case VT_LPSTR|VT_VECTOR:
			{
				PyObject *ret = PyList_New(pVar->calpstr.cElems);
				if (ret==NULL) return NULL;
				for (ULONG i=0; i<pVar->calpstr.cElems;i++){
					PyObject *elem=PyWinCoreString_FromString(pVar->calpstr.pElems[i]);
					if (elem==NULL){
						Py_DECREF(ret);
						return NULL;
						}
					PyList_SET_ITEM(ret, i, elem);
					}
				return ret;
			}
		case VT_LPWSTR:
			return PyWinObject_FromOLECHAR(pVar->pwszVal);
		case VT_LPWSTR|VT_VECTOR:
			{
				PyObject *ret = PyList_New(pVar->calpwstr.cElems);
				if (ret==NULL) return NULL;
				for (ULONG i=0; i<pVar->calpwstr.cElems;i++){
					PyObject *elem=PyWinObject_FromWCHAR(pVar->calpwstr.pElems[i]);
					if (elem==NULL){
						Py_DECREF(ret);
						return NULL;
						}
					PyList_SET_ITEM(ret, i, elem);
					}
				return ret;
			}
		case VT_CLSID:
			return PyWinObject_FromIID(*pVar->puuid);
		case VT_CLSID|VT_VECTOR:
			return VectorToSeq<CLSID>(pVar->cauuid.pElems, pVar->cauuid.cElems, PyWinObject_FromIID);
		case VT_STREAM:
		case VT_STREAMED_OBJECT:
			return PyCom_PyObjectFromIUnknown(pVar->pStream, IID_IStream, TRUE);
		case VT_STORAGE:
		case VT_STORED_OBJECT:
			return PyCom_PyObjectFromIUnknown(pVar->pStorage, IID_IStorage, TRUE);
		case VT_VECTOR | VT_VARIANT:
			return PyObject_FromPROPVARIANTs(pVar->capropvar.pElems, pVar->capropvar.cElems);
		case VT_BLOB:
		case VT_BLOB_OBJECT:
			return PyString_FromStringAndSize((const char *)pVar->blob.pBlobData,
			                                  pVar->blob.cbSize);
//		case VT_UNKNOWN:
//			return PyCom_PyObjectFromIUnknown(pVar->punkVal, IID_IUnknown, TRUE);
//		case VT_DISPATCH:
//			return PyCom_PyObjectFromIUnknown(pVar->pdispVal, IID_IDispatch, TRUE);

/*
// Want to get VT_CF and VT_BLOB working with a test case first!
		case VT_CF: { // special "clipboard format"
			// cbSize is the size of the buffer pointed to 
			// by pClipData, plus sizeof(ulClipFmt)
			// XXX - in that case, shouldn't we pass
			// pClipData + sizeof(DWORD) to Py_BuildValue??
			ULONG cb = CBPCLIPDATA(*pVar->pclipdata);
			return Py_BuildValue("is#",
			                     pVar->pclipdata->ulClipFmt,
			                     pVar->pclipdata->pClipData,
			                     (int)cb);
			}
*/
		default:
			PyErr_Format(PyExc_TypeError, "Unsupported property type 0x%x", pVar->vt);
			return NULL;
	}
}
Пример #2
0
static PyObject *
PyZlib_flush(compobject *self, PyObject *args)
{
    int err, length = DEFAULTALLOC;
    PyObject *RetVal;
    int flushmode = Z_FINISH;
    unsigned long start_total_out;

    if (!PyArg_ParseTuple(args, "|i:flush", &flushmode))
	return NULL;

    /* Flushing with Z_NO_FLUSH is a no-op, so there's no point in
       doing any work at all; just return an empty string. */
    if (flushmode == Z_NO_FLUSH) {
	return PyString_FromStringAndSize(NULL, 0);
    }

    if (!(RetVal = PyString_FromStringAndSize(NULL, length)))
	return NULL;

    ENTER_ZLIB

    start_total_out = self->zst.total_out;
    self->zst.avail_in = 0;
    self->zst.avail_out = length;
    self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal);

    Py_BEGIN_ALLOW_THREADS
    err = deflate(&(self->zst), flushmode);
    Py_END_ALLOW_THREADS

    /* while Z_OK and the output buffer is full, there might be more output,
       so extend the output buffer and try again */
    while (err == Z_OK && self->zst.avail_out == 0) {
	if (_PyString_Resize(&RetVal, length << 1) < 0)
	    goto error;
	self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
	    + length;
	self->zst.avail_out = length;
	length = length << 1;

	Py_BEGIN_ALLOW_THREADS
	err = deflate(&(self->zst), flushmode);
	Py_END_ALLOW_THREADS
    }

    /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free
       various data structures. Note we should only get Z_STREAM_END when
       flushmode is Z_FINISH, but checking both for safety*/
    if (err == Z_STREAM_END && flushmode == Z_FINISH) {
	err = deflateEnd(&(self->zst));
	if (err != Z_OK) {
	    zlib_error(self->zst, err, "from deflateEnd()");
	    Py_DECREF(RetVal);
	    RetVal = NULL;
	    goto error;
	}
	else
	    self->is_initialised = 0;

	/* We will only get Z_BUF_ERROR if the output buffer was full
	   but there wasn't more output when we tried again, so it is
	   not an error condition.
	*/
    } else if (err!=Z_OK && err!=Z_BUF_ERROR) {
	zlib_error(self->zst, err, "while flushing");
	Py_DECREF(RetVal);
	RetVal = NULL;
	goto error;
    }

    _PyString_Resize(&RetVal, self->zst.total_out - start_total_out);

 error:
    LEAVE_ZLIB

    return RetVal;
}
PyObject *Client_gets(PyClient *self, PyObject *args)
{
    //[ ] def gets(self, key, default = None):

    char *pKey;
    size_t cbKey;
    char *pData;
    size_t cbData;
    UINT64 cas;
    int flags;

    if (!PyArg_ParseTuple (args, "s#", &pKey, &cbKey))
    {
        return NULL;
    }

    self->client->getsBegin();

    self->client->getKeyWrite(pKey, cbKey);
    self->client->getFlush();

    bool bError = false;

    if (!self->client->getReadNext(&pKey, &cbKey, &pData, &cbData, &flags, &cas, &bError))
    {
        if (bError)
        {
            if (!PyErr_Occurred())
            {
                return PyErr_Format(PyExc_RuntimeError, "umemcached: %s", self->client->getError());
            }
            return NULL;
        }

        Py_RETURN_NONE;
    }



    PyObject *otuple = PyTuple_New(3);
    PyObject *ovalue = PyString_FromStringAndSize(pData, cbData);
    PyObject *oflags = PyInt_FromLong(flags);
    PyObject *ocas = PyLong_FromUnsignedLongLong(cas);

    PyTuple_SET_ITEM(otuple, 0, ovalue);
    PyTuple_SET_ITEM(otuple, 1, oflags);
    PyTuple_SET_ITEM(otuple, 2, ocas);

    while (self->client->getReadNext(&pKey, &cbKey, &pData, &cbData, &flags, &cas, &bError));

    if (bError)
    {
        Py_DECREF(otuple);

        if (!PyErr_Occurred())
        {
            return PyErr_Format(PyExc_RuntimeError, "umemcached: %s", self->client->getError());
        }

        return NULL;
    }

    return otuple;
}
Пример #4
0
static void
fixup_ulcase(void)
{
    PyObject *mods, *strop, *string, *ulo;
    unsigned char ul[256];
    int n, c;

    /* find the string and strop modules */
    mods = PyImport_GetModuleDict();
    if (!mods)
        return;
    string = PyDict_GetItemString(mods, "string");
    if (string)
        string = PyModule_GetDict(string);
    strop=PyDict_GetItemString(mods, "strop");
    if (strop)
        strop = PyModule_GetDict(strop);
    if (!string && !strop)
        return;

    /* create uppercase map string */
    n = 0;
    for (c = 0; c < 256; c++) {
        if (isupper(c))
            ul[n++] = c;
    }
    ulo = PyString_FromStringAndSize((const char *)ul, n);
    if (!ulo)
        return;
    if (string)
        PyDict_SetItemString(string, "uppercase", ulo);
    if (strop)
        PyDict_SetItemString(strop, "uppercase", ulo);
    Py_DECREF(ulo);

    /* create lowercase string */
    n = 0;
    for (c = 0; c < 256; c++) {
        if (islower(c))
            ul[n++] = c;
    }
    ulo = PyString_FromStringAndSize((const char *)ul, n);
    if (!ulo)
        return;
    if (string)
        PyDict_SetItemString(string, "lowercase", ulo);
    if (strop)
        PyDict_SetItemString(strop, "lowercase", ulo);
    Py_DECREF(ulo);

    /* create letters string */
    n = 0;
    for (c = 0; c < 256; c++) {
        if (isalpha(c))
            ul[n++] = c;
    }
    ulo = PyString_FromStringAndSize((const char *)ul, n);
    if (!ulo)
        return;
    if (string)
        PyDict_SetItemString(string, "letters", ulo);
    Py_DECREF(ulo);
}
Пример #5
0
static PyObject *
PyZlib_decompress(PyObject *self, PyObject *args)
{
    PyObject *result_str;
    Byte *input;
    int length, err;
    int wsize=DEF_WBITS, r_strlen=DEFAULTALLOC;
    z_stream zst;

    if (!PyArg_ParseTuple(args, "s#|ii:decompress",
			  &input, &length, &wsize, &r_strlen))
	return NULL;

    if (r_strlen <= 0)
	r_strlen = 1;

    zst.avail_in = length;
    zst.avail_out = r_strlen;

    if (!(result_str = PyString_FromStringAndSize(NULL, r_strlen)))
	return NULL;

    zst.zalloc = (alloc_func)NULL;
    zst.zfree = (free_func)Z_NULL;
    zst.next_out = (Byte *)PyString_AS_STRING(result_str);
    zst.next_in = (Byte *)input;
    err = inflateInit2(&zst, wsize);

    switch(err) {
    case(Z_OK):
	break;
    case(Z_MEM_ERROR):
	PyErr_SetString(PyExc_MemoryError,
			"Out of memory while decompressing data");
	goto error;
    default:
        inflateEnd(&zst);
	zlib_error(zst, err, "while preparing to decompress data");
	goto error;
    }

    do {
	Py_BEGIN_ALLOW_THREADS
	err=inflate(&zst, Z_FINISH);
	Py_END_ALLOW_THREADS

	switch(err) {
	case(Z_STREAM_END):
	    break;
	case(Z_BUF_ERROR):
	    /*
	     * If there is at least 1 byte of room according to zst.avail_out
	     * and we get this error, assume that it means zlib cannot
	     * process the inflate call() due to an error in the data.
	     */
	    if (zst.avail_out > 0) {
		PyErr_Format(ZlibError, "Error %i while decompressing data",
			     err);
		inflateEnd(&zst);
		goto error;
	    }
	    /* fall through */
	case(Z_OK):
	    /* need more memory */
	    if (_PyString_Resize(&result_str, r_strlen << 1) < 0) {
		inflateEnd(&zst);
		goto error;
	    }
	    zst.next_out = (unsigned char *)PyString_AS_STRING(result_str) \
		+ r_strlen;
	    zst.avail_out = r_strlen;
	    r_strlen = r_strlen << 1;
	    break;
	default:
	    inflateEnd(&zst);
	    zlib_error(zst, err, "while decompressing data");
	    goto error;
	}
    } while (err != Z_STREAM_END);

    err = inflateEnd(&zst);
    if (err != Z_OK) {
	zlib_error(zst, err, "while finishing data decompression");
	goto error;
    }

    _PyString_Resize(&result_str, zst.total_out);
    return result_str;

 error:
    Py_XDECREF(result_str);
    return NULL;
}
Пример #6
0
static int parse_multi_line_message(Request* request, const char* data, const size_t data_len){  
    char *newline = NULL;
    int pos = 0, ok;
    long long ll;
    int partialdone = 0;

    if (request->parse_phase == RDS_PHASE_CONNECT){
        if (request->multibulklen == 0) {        
            newline = strchr(data,'\r');
            if (newline == NULL) {
                // if (sdslen(c->querybuf) > REDIS_INLINE_MAX_SIZE) {
                //     addReplyError(c,"Protocol error: too big mbulk count string");
                //     setProtocolError(c,0);
                // }

                // we will come back here,                
                return -1;
            }

            ok = string2ll(data+1, newline-(data+1), &ll);
            if (!ok || ll > 1024*1024) {
                puts("couldnt find data length... ");
                return -2;
            }
            pos = (newline - data)+2;

            if (ll <= 0) {
                // TODO: handle *-1\r\n ?
                // c->querybuf = sdsrange(c->querybuf,pos,-1);
                return true;
            }        

            request->cmd_list = PyList_New(ll);

            request->multibulklen = ll;     
            request->arg_cnt = 0;   
            request->parse_phase = RDS_PHASE_START;
            // now send the remainder to start line...
            request->lastpos = pos;                        
        }
    }    
    

    while (request->multibulklen){        
        // since we found the start line, here we parse it...
        if (request->parse_phase == RDS_PHASE_START){      
              if (data[request->lastpos] == '$'){
                      // 
                      newline = strchr(data+request->lastpos,'\r');
                      if (!newline){
                        return -1;
                      }

                      ok = string2ll(data+request->lastpos+1, newline - (data+ request->lastpos+1),&ll);
                      if (!ok || ll < 0 || ll > 512*1024*1024) {
                          return -2;
                      }

                        // now parse data line...            
                        pos = (newline - data)+2;

                        if (ll < 0) {
                            // handle $-1\r\n ?
                            // protocol error !!!
                            // c->querybuf = sdsrange(c->querybuf,pos,-1);                
                            return -2;
                        }

                        // now send the remainder to start line...
                        request->lastpos = pos;                
                        request->parse_phase = RDS_PHASE_DATA;
                        request->bulklen = ll;
              } else {
                puts("ERR: protocol error");
                return -2;
              }
          }
          // 
          if (request->parse_phase == RDS_PHASE_DATA){      

                if ((int)(data_len - request->lastpos) < 0){
                  return -1;
                }

                // do we have enough data ???
                if ( (int)(data_len - request->lastpos) < (int)(request->bulklen+2)) {
                    /* Not enough data (+2 == trailing \r\n) */                    
                    return -1;
                    break;
                } else {                                        
                    char *str2 = malloc(request->bulklen + 1);
                    memcpy(str2, data + request->lastpos, request->bulklen);                  
                    str2[request->bulklen] = '\0';

                    PyObject* str = PyString_FromStringAndSize(str2, request->bulklen);                  
                    PyList_SetItem(request->cmd_list, request->arg_cnt++, str);                   
                    // NOTE: as far as i understand, PyList_SetItem doesnt incref
                    // http://stackoverflow.com/questions/3512414/does-this-pylist-appendlist-py-buildvalue-leak
                    // Py_DECREF(str); <- TODO: why ? if i do this weird things happen
                    free(str2);                  
                }                                

              
              request->lastpos = request->lastpos + request->bulklen + 2;
              request->parse_phase = RDS_PHASE_START;              
              request->multibulklen--;                              
          
          } // if RDS_PHASE_DATA
    } // while bulklen

    if (request->multibulklen == 0){      
        return 1;
    }
    
    return -1;
}
Пример #7
0
static PyObject *py_parse_tree(PyObject *self, PyObject *args, PyObject *kw)
{
	char *text, *start, *end;
	int len, namelen, strict;
	PyObject *ret, *item, *name, *sha, *py_strict = NULL;
	static char *kwlist[] = {"text", "strict", NULL};

	if (!PyArg_ParseTupleAndKeywords(args, kw, "s#|O", kwlist,
	                                 &text, &len, &py_strict))
		return NULL;
	strict = py_strict ?  PyObject_IsTrue(py_strict) : 0;
	/* TODO: currently this returns a list; if memory usage is a concern,
	 * consider rewriting as a custom iterator object */
	ret = PyList_New(0);
	if (ret == NULL) {
		return NULL;
	}
	start = text;
	end = text + len;
	while (text < end) {
		long mode;
		if (strict && text[0] == '0') {
			PyErr_SetString(object_format_exception_cls,
			                "Illegal leading zero on mode");
			Py_DECREF(ret);
			return NULL;
		}
		mode = strtol(text, &text, 8);
		if (*text != ' ') {
			PyErr_SetString(PyExc_ValueError, "Expected space");
			Py_DECREF(ret);
			return NULL;
		}
		text++;
		namelen = strnlen(text, len - (text - start));
		name = PyString_FromStringAndSize(text, namelen);
		if (name == NULL) {
			Py_DECREF(ret);
			return NULL;
		}
		if (text + namelen + 20 >= end) {
			PyErr_SetString(PyExc_ValueError, "SHA truncated");
			Py_DECREF(ret);
			Py_DECREF(name);
			return NULL;
		}
		sha = sha_to_pyhex((unsigned char *)text+namelen+1);
		if (sha == NULL) {
			Py_DECREF(ret);
			Py_DECREF(name);
			return NULL;
		}
		item = Py_BuildValue("(NlN)", name, mode, sha);
		if (item == NULL) {
			Py_DECREF(ret);
			Py_DECREF(sha);
			Py_DECREF(name);
			return NULL;
		}
		if (PyList_Append(ret, item) == -1) {
			Py_DECREF(ret);
			Py_DECREF(item);
			return NULL;
		}
		Py_DECREF(item);
		text += namelen+21;
	}
	return ret;
}
Пример #8
0
static void*
tns_parse_string(const tns_ops *ops, const char *data, size_t len)
{
  return PyString_FromStringAndSize(data, len);
}
Пример #9
0
PyObject *build_property( const unicap_property_t *property )
{
   PyObject *obj = NULL;
   PyObject *tmp = NULL;
   
   // name: string, category: string, unit: string, (value: float)|(menu_item: string), 
   // (range: (float,float))|(values:[float,..])|(menu:[string,..]), flags: [string], capabilities: [string]

   obj = Py_BuildValue( "{s:s,s:s}", 
			"identifier", property->identifier, 
			"category", property->category );
   if( !obj )
   {
      return NULL;
   }
   
   if( strlen( property->unit ) > 0 )
   {
      if( PyDict_SetItemString( obj, "unit", Py_BuildValue( "s", property->unit ) ) != 0 )
	 goto err;
   }

   switch( property->type )
   {
      case UNICAP_PROPERTY_TYPE_RANGE:
      {
	 if( PyDict_SetItemString( obj, "value", Py_BuildValue( "d", property->value ) ) != 0 )
	    goto err;
	 if( PyDict_SetItemString( obj, "range", Py_BuildValue( "(d,d)", property->range.min, property->range.max ) ) != 0 )
	    goto err;
      }
      break;
      case UNICAP_PROPERTY_TYPE_VALUE_LIST:
      {
	 int i;
/* 	 if( !property->value_list ) */
/* 	    goto err; */

	 if( PyDict_SetItemString( obj, "value", Py_BuildValue( "d", property->value ) ) != 0 )
	    goto err;
	 tmp = PyList_New(0);
	 if( !tmp )
	    goto err;
	 for( i = 0; i < property->value_list.value_count; i++ )
	 {
	    if( PyList_Append( tmp, Py_BuildValue( "d", property->value_list.values[i] ) ) != 0 )
	       goto err;
	 }
	 if( PyDict_SetItemString( obj, "values", tmp ) )
	    goto err;

	 tmp = NULL;
      }
      break;
      
      case UNICAP_PROPERTY_TYPE_MENU:
      {
	 int i;
	 if( PyDict_SetItemString( obj, "menu_item", Py_BuildValue( "s", property->menu_item ) ) != 0 )
	    goto err;
	 
	 tmp = PyList_New(0);
	 if( !tmp) 
	    goto err;
	 
	 for( i = 0; i < property->menu.menu_item_count; i++ )
	 {
	    if( PyList_Append( tmp, Py_BuildValue( "s", property->menu.menu_items[i] ) ) != 0 )
	       goto err;
	 }
	 if( PyDict_SetItemString( obj, "menu_items", tmp ) )
	    goto err;

	 tmp = NULL;
      }
      break;

   case UNICAP_PROPERTY_TYPE_DATA:
   {
      PyObject *data = PyString_FromStringAndSize( (char*)property->property_data, property->property_data_size );
      PyDict_SetItemString( obj, "data", data );
   }
   break;
   
      
      default:
	 break;
   }
   
   tmp = build_property_flags_list( property->flags );
   if( !tmp )
      goto err;
   if( PyDict_SetItemString( obj, "flags", tmp ) != 0 )
      goto err;
   
   tmp = build_property_flags_list( property->flags_mask );
   if( !tmp )
      goto err;
   if( PyDict_SetItemString( obj, "flags_mask", tmp ) != 0 )
      goto err;

   return obj;
   
  err:
   Py_XDECREF(tmp);
   Py_XDECREF( obj );
   return NULL;
}
Пример #10
0
static PyObject *PySilcUser_GetAttr(PyObject *self, PyObject *name)
{
    // expose the following attributes as readonly
    // - char *nickname
    // - char *username
    // - char *hostname
    // - char *server
    // - char *realname
    // - unsigned char *fingerprint;
    //   SilcUInt32 finderprint_len;
    //
    // - 64/160 bit user id
    // - unsigned int mode
    // - (TODO) attrs;
    // - (TODO) public_key;
    // - int status
    // - (TODO) channels
    // - int resolve_cmd_ident;
    
    int result;
    PyObject *temp = NULL, *value = NULL;
    PySilcUser *pyuser = (PySilcUser *)self;
  
    if (!pyuser->silcobj)
        goto cleanup;
  
    // check for nickname
    temp = PyString_FromString("nickname");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        if (pyuser->silcobj->nickname)
            value = PyString_FromString(pyuser->silcobj->nickname);
        else {
            value = Py_None;
            Py_INCREF(value);
        }
        goto cleanup;
    }
  
    // check for username
    Py_DECREF(temp);
    temp = PyString_FromString("username");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        if (pyuser->silcobj->username)
            value = PyString_FromString(pyuser->silcobj->username);
        else {
            value = Py_None;
            Py_INCREF(value);
        }
        goto cleanup;
    }

    // check for hostname
    Py_DECREF(temp);
    temp = PyString_FromString("hostname");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        if (pyuser->silcobj->hostname)
            value = PyString_FromString(pyuser->silcobj->hostname);
        else {
            value = Py_None;
            Py_INCREF(value);
        }
        goto cleanup;
    }
    
    // check for server
    Py_DECREF(temp);
    temp = PyString_FromString("server");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        if (pyuser->silcobj->server)
            value = PyString_FromString(pyuser->silcobj->server);
        else {
            value = Py_None;
            Py_INCREF(value);
        }
        goto cleanup;
    }    
  
    // check for realname
    Py_DECREF(temp);
    temp = PyString_FromString("realname");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        if (pyuser->silcobj->realname)
            value = PyString_FromString(pyuser->silcobj->realname);
        else {
            value = Py_None;
            Py_INCREF(value);
        }
        goto cleanup;
    }
    
    // check for fingerprint
    Py_DECREF(temp);
    temp = PyString_FromString("fingerprint");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        if (pyuser->silcobj->fingerprint)
            value = PyString_FromStringAndSize(pyuser->silcobj->fingerprint, pyuser->silcobj->fingerprint_len);
        else {
            value = Py_None;
            Py_INCREF(value);
        }
        goto cleanup;
    }
  
    // check for user id
    Py_DECREF(temp);
    temp = PyString_FromString("user_id");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        char buf[224];
        memcpy(&buf, (pyuser->silcobj->id), 224);
        value = PyString_FromStringAndSize(buf, 224);
        goto cleanup;
    }
    
    // check for mode
    Py_DECREF(temp);
    temp = PyString_FromString("mode");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        value = PyInt_FromLong(pyuser->silcobj->mode);
        goto cleanup;
    }
    
    // check for status
    Py_DECREF(temp);
    temp = PyString_FromString("status");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        value = PyInt_FromLong(pyuser->silcobj->status);
        goto cleanup;
    }
    
    // check for resolve_cmd_ident
    Py_DECREF(temp);
    temp = PyString_FromString("resolve_cmd_ident");
    if (PyObject_Cmp(temp, name, &result) == -1)
        goto cleanup;
    if (result == 0) {
        value = PyInt_FromLong(pyuser->silcobj->resolve_cmd_ident);
        goto cleanup;
    }
    
cleanup:
    Py_XDECREF(temp);
    if (value)
        return value;
    else
        return PyObject_GenericGetAttr(self, name);    
}
Пример #11
0
static PyObject *texture_sample(PyObject *self, PyObject *args)
{
/*
  sample part of texture, args:
  whole texture as string, width and height
  output texture width and height
  upper lext and lower right corbers of rectangle from whole texture to be sampled into output texture
  
*/
  long int textureWidth, textureHeight;
  long int screenWidth, screenHeight;
  int i;
  int textureLen;
  char *texture;
  char *result;
  int resultSize;
  char *resPtr;
  double x1,y1,x2,y2;
  double dx,dy;
  double texturey,texturex;
  int y,x,posy,posx;
  PyObject *pyRes;
  if (!PyArg_ParseTuple(args, "s#lllldddd",
                        &texture, &textureLen,
                        &textureWidth, &textureHeight,
                        &screenWidth, &screenHeight,
                        &x1, &y1, &x2, &y2))
    return NULL;
  resultSize = screenWidth*screenHeight*3;
/*
  printf("%li, %li, %li, %li, %g, %g, %g, %g (%i)\n",
         textureWidth, textureHeight,
         screenWidth, screenHeight,
         x1,y1,x2,y2,
         resultSize);
*/
  resPtr = result = malloc(resultSize);
  if(!resPtr) return NULL;
  dx = (x2-x1)/screenWidth;
  dy = (y2-y1)/screenHeight;
  //printf("d: %g,%g\n", dx,dy);
  texturey = y1;
  for(y=0; y<screenHeight; y++, texturey+=dy) {
    if(texturey<0.0 || texturey>=textureHeight) {
      for(x=0; x<screenWidth*3; x++, resPtr++) {
        *resPtr = -1;
      }
    } else {
      posy = (int)texturey * textureWidth*3;
      texturex = x1;
      for(x=0; x<screenWidth; x++, texturex+=dx) {
        if(texturex<0.0 || texturex>=textureWidth) {
          for(i=0; i<3; i++, resPtr++) *resPtr = -1;
        } else {
          posx = posy + (int)texturex*3;
          for(i=0; i<3; i++, resPtr++) {
            *resPtr = texture[posx+i];
            //printf("%i,%i %g,%g: %i\n", y,x, texturey, texturex, (int)texture[posx+i]);
          }
        }
      }
    }
  }
  //printf("...done\n");
  
  pyRes = PyString_FromStringAndSize(result, resultSize);
  free(result);
  return pyRes;
}
Пример #12
0
PyObject *
captureObject_next(captureObject *self)
{
    u_char *packet = NULL;
    struct pcap_pkthdr header;
    PyObject *ethernet = NULL;
    PyObject *result = NULL;
    PyObject *resultTuple = NULL;
    ethernet_t *eth_header = NULL;
    char buffer[255];
    double packetTime;
    int packet_offset = 0;
    PyObject *remaining = NULL;
    int offset[5] = {
        0, 0, 0, 0, 0
    };
    

    packet = (u_char *) pcap_next(self->pcap, &header);
    if (! packet)
    {
        Py_INCREF(Py_None);
        return Py_None;

        //        PyErr_SetString(ErrorObject, "No data available before timeout");
        //        return NULL;
    }
    sprintf(buffer, "%ld.%ld", (long) header.ts.tv_sec, (long) header.ts.tv_usec);
    packetTime = strtod(buffer, NULL);
    result = PyList_New(0);
    switch (pcap_datalink(self->pcap))
    {
        case DLT_EN10MB:
        {
            eth_header = (ethernet_t *) packet;
            ethernet = (PyObject *) PyProtocol_newEthernetObjectFromPacket(eth_header, &packet_offset);
            offset[0] = packet_offset;
            PyList_Append(result, ethernet);
            Py_DECREF(ethernet);

            switch (ntohs(eth_header->ether_type))
            {
                case ETHERTYPE_IP:
                {
                    if (! parseIP(result, header, packet, &packet_offset))
                    {
                        Py_DECREF(result);
                        return NULL;
                    }
                    offset[1] = packet_offset;
                    break;
                }
                case ETHERTYPE_ARP:
                    if (! parseARP(result, header, packet, &packet_offset))
                    {
                        Py_DECREF(result);
                        return NULL;
                    }
                    offset[2] = packet_offset;
                    break;
                default:
                {
                    
                }
            }
            break;
        }
        case DLT_NULL:
        {
            packet_offset = 4;
            if (! parseIP(result, header, packet, &packet_offset))
            {
                Py_DECREF(result);
                return NULL;
            }
            offset[3] = packet_offset;
            break;
        }
    }
    if ((int) (header.len) - packet_offset < 0)
    {
        Py_DECREF(result);
        PyErr_Format(ErrorObject, "Parsed parsed end of packet (%d %d %d %d)",
                        offset[0], offset[1], offset[2], offset[3]);
        return NULL;
    }
    remaining = PyString_FromStringAndSize((char *) (packet + packet_offset),
                                                     header.len - packet_offset);
    PyList_Append(result, remaining);
    Py_DECREF(remaining);
    
    
    PyList_Append(result, PyFloat_FromDouble(packetTime));
    resultTuple = PyList_AsTuple(result);
    Py_DECREF(result);
    return resultTuple;
}
Пример #13
0
static PyObject *_filter_read(filterobject *self, PyObject *args, int readline)
{

    apr_bucket *b;
    long bytes_read;
    PyObject *result;
    char *buffer;
    long bufsize;
    int newline = 0;
    long len = -1;
    conn_rec *c = self->request_obj->request_rec->connection;

    if (! PyArg_ParseTuple(args, "|l", &len)) 
        return NULL;

    if (self->closed) {
        PyErr_SetString(PyExc_ValueError, "I/O operation on closed filter");
        return NULL;
    }

    if (self->is_input) {

        /* does the output brigade exist? */
        if (!self->bb_in) {
            self->bb_in = apr_brigade_create(self->f->r->pool, 
                                             c->bucket_alloc);
        }

        Py_BEGIN_ALLOW_THREADS;
        self->rc = ap_get_brigade(self->f->next, self->bb_in, self->mode, 
                                  APR_BLOCK_READ, self->readbytes);
        Py_END_ALLOW_THREADS;

        if (!APR_STATUS_IS_EAGAIN(self->rc) && !(self->rc == APR_SUCCESS)) {
            PyErr_SetObject(PyExc_IOError, 
                            PyString_FromString("Input filter read error"));
            return NULL;
        }
    }

    /* 
     * loop through the brigade reading buckets into the string 
     */

    b = APR_BRIGADE_FIRST(self->bb_in);

    if (b == APR_BRIGADE_SENTINEL(self->bb_in))
        return PyString_FromString("");

    /* reached eos ? */
    if (APR_BUCKET_IS_EOS(b)) {
        apr_bucket_delete(b);
        Py_INCREF(Py_None);
        return Py_None;
    }

    bufsize = len < 0 ? HUGE_STRING_LEN : len;
    /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ 
    result = PyString_FromStringAndSize(NULL, bufsize);

    /* possibly no more memory */
    if (result == NULL) 
        return PyErr_NoMemory();
    
    buffer = PyString_AS_STRING((PyStringObject *) result);

    bytes_read = 0;

    while ((bytes_read < len || len == -1) && 
           !(APR_BUCKET_IS_EOS(b) || APR_BUCKET_IS_FLUSH(b) ||
             b == APR_BRIGADE_SENTINEL(self->bb_in))) {

        const char *data;
        apr_size_t size;
        apr_bucket *old;
        int i;

        if (apr_bucket_read(b, &data, &size, APR_BLOCK_READ) != APR_SUCCESS) {
            PyErr_SetObject(PyExc_IOError, 
                            PyString_FromString("Filter read error"));
            return NULL;
        }

        if (bytes_read + size > bufsize) {
            apr_bucket_split(b, bufsize - bytes_read);
            size = bufsize - bytes_read;
            /* now the bucket is the exact size we need */
        }

        if (readline) {

            /* scan for newline */
            for (i=0; i<size; i++) {
                if (data[i] == '\n') {
                    if (i+1 != size) {   /* (no need to split if we're at end of bucket) */
                        
                        /* split after newline */
                        apr_bucket_split(b, i+1);   
                        size = i + 1;
                    }
                    newline = 1;
                    break;
                }
            }
        }

        memcpy(buffer, data, size);
        buffer += size;
        bytes_read += size;

        /* time to grow destination string? */
        if (newline == 0 && len < 0 && bytes_read == bufsize) {

            /* PYTHON 2.5: '_PyString_Resize' uses Py_ssize_t for input parameters */
            _PyString_Resize(&result, bufsize + HUGE_STRING_LEN);
            buffer = PyString_AS_STRING((PyStringObject *) result);
            buffer += bytes_read;

            bufsize += HUGE_STRING_LEN;
        }

        if (readline && newline) {
            apr_bucket_delete(b);
            break;
        }

        old = b;
        b = APR_BUCKET_NEXT(b);
        apr_bucket_delete(old);
        
/*         if (self->is_input) { */

/*             if (b == APR_BRIGADE_SENTINEL(self->bb_in)) { */
/*                 /\* brigade ended, but no EOS - get another */
/*                    brigade *\/ */

/*                 Py_BEGIN_ALLOW_THREADS; */
/*                 self->rc = ap_get_brigade(self->f->next, self->bb_in, self->mode,  */
/*                                           APR_BLOCK_READ, self->readbytes); */
/*                 Py_END_ALLOW_THREADS; */

/*                 if (! APR_STATUS_IS_SUCCESS(self->rc)) { */
/*                     PyErr_SetObject(PyExc_IOError,  */
/*                                     PyString_FromString("Input filter read error")); */
/*                     return NULL; */
/*                 } */
/*                 b = APR_BRIGADE_FIRST(self->bb_in); */
/*             } */
/*         }  */
    }

    /* resize if necessary */
    if (bytes_read < len || len < 0) 
        /* PYTHON 2.5: '_PyString_Resize' uses Py_ssize_t for input parameters */
        if(_PyString_Resize(&result, bytes_read))
            return NULL;

    return result;
}
Пример #14
0
PyObject *
PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names,
                PyObject *lineno_obj)
{
    Py_ssize_t i, j, codelen;
    int nops, h, adj;
    int tgt, tgttgt, opcode;
    unsigned char *codestr = NULL;
    unsigned char *lineno;
    int *addrmap = NULL;
    int new_line, cum_orig_line, last_line, tabsiz;
    int cumlc=0, lastlc=0;      /* Count runs of consecutive LOAD_CONSTs */
    unsigned int *blocks = NULL;
    char *name;

    /* Bail out if an exception is set */
    if (PyErr_Occurred())
        goto exitError;

    /* Bypass optimization when the lineno table is too complex */
    assert(PyString_Check(lineno_obj));
    lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
    tabsiz = PyString_GET_SIZE(lineno_obj);
    if (memchr(lineno, 255, tabsiz) != NULL)
        goto exitUnchanged;

    /* Avoid situations where jump retargeting could overflow */
    assert(PyString_Check(code));
    codelen = PyString_GET_SIZE(code);
    if (codelen > 32700)
        goto exitUnchanged;

    /* Make a modifiable copy of the code string */
    codestr = (unsigned char *)PyMem_Malloc(codelen);
    if (codestr == NULL)
        goto exitError;
    codestr = (unsigned char *)memcpy(codestr,
                                      PyString_AS_STRING(code), codelen);

    /* Verify that RETURN_VALUE terminates the codestring.      This allows
       the various transformation patterns to look ahead several
       instructions without additional checks to make sure they are not
       looking beyond the end of the code string.
    */
    if (codestr[codelen-1] != RETURN_VALUE)
        goto exitUnchanged;

    /* Mapping to new jump targets after NOPs are removed */
    addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
    if (addrmap == NULL)
        goto exitError;

    blocks = markblocks(codestr, codelen);
    if (blocks == NULL)
        goto exitError;
    assert(PyList_Check(consts));

    for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
      reoptimize_current:
        opcode = codestr[i];

        lastlc = cumlc;
        cumlc = 0;

        switch (opcode) {
            /* Replace UNARY_NOT POP_JUMP_IF_FALSE
               with    POP_JUMP_IF_TRUE */
            case UNARY_NOT:
                if (codestr[i+1] != POP_JUMP_IF_FALSE
                    || !ISBASICBLOCK(blocks,i,4))
                    continue;
                j = GETARG(codestr, i+1);
                codestr[i] = POP_JUMP_IF_TRUE;
                SETARG(codestr, i, j);
                codestr[i+3] = NOP;
                goto reoptimize_current;

                /* not a is b -->  a is not b
                   not a in b -->  a not in b
                   not a is not b -->  a is b
                   not a not in b -->  a in b
                */
            case COMPARE_OP:
                j = GETARG(codestr, i);
                if (j < 6  ||  j > 9  ||
                    codestr[i+3] != UNARY_NOT  ||
                    !ISBASICBLOCK(blocks,i,4))
                    continue;
                SETARG(codestr, i, (j^1));
                codestr[i+3] = NOP;
                break;

                /* Replace LOAD_GLOBAL/LOAD_NAME None
                   with LOAD_CONST None */
            case LOAD_NAME:
            case LOAD_GLOBAL:
                j = GETARG(codestr, i);
                name = PyString_AsString(PyTuple_GET_ITEM(names, j));
                if (name == NULL  ||  strcmp(name, "None") != 0)
                    continue;
                for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
                    if (PyList_GET_ITEM(consts, j) == Py_None)
                        break;
                }
                if (j == PyList_GET_SIZE(consts)) {
                    if (PyList_Append(consts, Py_None) == -1)
                        goto exitError;
                }
                assert(PyList_GET_ITEM(consts, j) == Py_None);
                codestr[i] = LOAD_CONST;
                SETARG(codestr, i, j);
                cumlc = lastlc + 1;
                break;

                /* Skip over LOAD_CONST trueconst
                   POP_JUMP_IF_FALSE xx. This improves
                   "while 1" performance. */
            case LOAD_CONST:
                cumlc = lastlc + 1;
                j = GETARG(codestr, i);
                if (codestr[i+3] != POP_JUMP_IF_FALSE  ||
                    !ISBASICBLOCK(blocks,i,6)  ||
                    !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
                    continue;
                memset(codestr+i, NOP, 6);
                cumlc = 0;
                break;

                /* Try to fold tuples of constants (includes a case for lists
                   which are only used for "in" and "not in" tests).
                   Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
                   Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
                   Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
            case BUILD_TUPLE:
            case BUILD_LIST:
                j = GETARG(codestr, i);
                h = i - 3 * j;
                if (h >= 0  &&
                    j <= lastlc                  &&
                    ((opcode == BUILD_TUPLE &&
                      ISBASICBLOCK(blocks, h, 3*(j+1))) ||
                     (opcode == BUILD_LIST &&
                      codestr[i+3]==COMPARE_OP &&
                      ISBASICBLOCK(blocks, h, 3*(j+2)) &&
                      (GETARG(codestr,i+3)==6 ||
                       GETARG(codestr,i+3)==7))) &&
                    tuple_of_constants(&codestr[h], j, consts)) {
                    assert(codestr[i] == LOAD_CONST);
                    cumlc = 1;
                    break;
                }
                if (codestr[i+3] != UNPACK_SEQUENCE  ||
                    !ISBASICBLOCK(blocks,i,6) ||
                    j != GETARG(codestr, i+3))
                    continue;
                if (j == 1) {
                    memset(codestr+i, NOP, 6);
                } else if (j == 2) {
                    codestr[i] = ROT_TWO;
                    memset(codestr+i+1, NOP, 5);
                } else if (j == 3) {
                    codestr[i] = ROT_THREE;
                    codestr[i+1] = ROT_TWO;
                    memset(codestr+i+2, NOP, 4);
                }
                break;

                /* Fold binary ops on constants.
                   LOAD_CONST c1 LOAD_CONST c2 BINOP -->  LOAD_CONST binop(c1,c2) */
            case BINARY_POWER:
            case BINARY_MULTIPLY:
            case BINARY_TRUE_DIVIDE:
            case BINARY_FLOOR_DIVIDE:
            case BINARY_MODULO:
            case BINARY_ADD:
            case BINARY_SUBTRACT:
            case BINARY_SUBSCR:
            case BINARY_LSHIFT:
            case BINARY_RSHIFT:
            case BINARY_AND:
            case BINARY_XOR:
            case BINARY_OR:
                if (lastlc >= 2                  &&
                    ISBASICBLOCK(blocks, i-6, 7)  &&
                    fold_binops_on_constants(&codestr[i-6], consts)) {
                    i -= 2;
                    assert(codestr[i] == LOAD_CONST);
                    cumlc = 1;
                }
                break;

                /* Fold unary ops on constants.
                   LOAD_CONST c1  UNARY_OP -->                  LOAD_CONST unary_op(c) */
            case UNARY_NEGATIVE:
            case UNARY_CONVERT:
            case UNARY_INVERT:
                if (lastlc >= 1                  &&
                    ISBASICBLOCK(blocks, i-3, 4)  &&
                    fold_unaryops_on_constants(&codestr[i-3], consts))                  {
                    i -= 2;
                    assert(codestr[i] == LOAD_CONST);
                    cumlc = 1;
                }
                break;

                /* Simplify conditional jump to conditional jump where the
                   result of the first test implies the success of a similar
                   test or the failure of the opposite test.
                   Arises in code like:
                   "if a and b:"
                   "if a or b:"
                   "a and b or c"
                   "(a and b) and c"
                   x:JUMP_IF_FALSE_OR_POP y   y:JUMP_IF_FALSE_OR_POP z
                      -->  x:JUMP_IF_FALSE_OR_POP z
                   x:JUMP_IF_FALSE_OR_POP y   y:JUMP_IF_TRUE_OR_POP z
                      -->  x:POP_JUMP_IF_FALSE y+3
                   where y+3 is the instruction following the second test.
                */
            case JUMP_IF_FALSE_OR_POP:
            case JUMP_IF_TRUE_OR_POP:
                tgt = GETJUMPTGT(codestr, i);
                j = codestr[tgt];
                if (CONDITIONAL_JUMP(j)) {
                    /* NOTE: all possible jumps here are
                       absolute! */
                    if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) {
                        /* The second jump will be
                           taken iff the first is. */
                        tgttgt = GETJUMPTGT(codestr, tgt);
                        /* The current opcode inherits
                           its target's stack behaviour */
                        codestr[i] = j;
                        SETARG(codestr, i, tgttgt);
                        goto reoptimize_current;
                    } else {
                        /* The second jump is not taken
                           if the first is (so jump past
                           it), and all conditional
                           jumps pop their argument when
                           they're not taken (so change
                           the first jump to pop its
                           argument when it's taken). */
                        if (JUMPS_ON_TRUE(opcode))
                            codestr[i] = POP_JUMP_IF_TRUE;
                        else
                            codestr[i] = POP_JUMP_IF_FALSE;
                        SETARG(codestr, i, (tgt + 3));
                        goto reoptimize_current;
                    }
                }
                /* Intentional fallthrough */

                /* Replace jumps to unconditional jumps */
            case POP_JUMP_IF_FALSE:
            case POP_JUMP_IF_TRUE:
            case FOR_ITER:
            case JUMP_FORWARD:
            case JUMP_ABSOLUTE:
            case CONTINUE_LOOP:
            case SETUP_LOOP:
            case SETUP_EXCEPT:
            case SETUP_FINALLY:
            case SETUP_WITH:
                tgt = GETJUMPTGT(codestr, i);
                /* Replace JUMP_* to a RETURN into just a RETURN */
                if (UNCONDITIONAL_JUMP(opcode) &&
                    codestr[tgt] == RETURN_VALUE) {
                    codestr[i] = RETURN_VALUE;
                    memset(codestr+i+1, NOP, 2);
                    continue;
                }
                if (!UNCONDITIONAL_JUMP(codestr[tgt]))
                    continue;
                tgttgt = GETJUMPTGT(codestr, tgt);
                if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
                    opcode = JUMP_ABSOLUTE;
                if (!ABSOLUTE_JUMP(opcode))
                    tgttgt -= i + 3;     /* Calc relative jump addr */
                if (tgttgt < 0)                           /* No backward relative jumps */
                    continue;
                codestr[i] = opcode;
                SETARG(codestr, i, tgttgt);
                break;

            case EXTENDED_ARG:
                goto exitUnchanged;

                /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
                /* Remove unreachable JUMPs after RETURN */
            case RETURN_VALUE:
                if (i+4 >= codelen)
                    continue;
                if (codestr[i+4] == RETURN_VALUE &&
                    ISBASICBLOCK(blocks,i,5))
                    memset(codestr+i+1, NOP, 4);
                else if (UNCONDITIONAL_JUMP(codestr[i+1]) &&
                         ISBASICBLOCK(blocks,i,4))
                    memset(codestr+i+1, NOP, 3);
                break;
        }
    }

    /* Fixup linenotab */
    for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
        addrmap[i] = i - nops;
        if (codestr[i] == NOP)
            nops++;
    }
    cum_orig_line = 0;
    last_line = 0;
    for (i=0 ; i < tabsiz ; i+=2) {
        cum_orig_line += lineno[i];
        new_line = addrmap[cum_orig_line];
        assert (new_line - last_line < 255);
        lineno[i] =((unsigned char)(new_line - last_line));
        last_line = new_line;
    }

    /* Remove NOPs and fixup jump targets */
    for (i=0, h=0 ; i<codelen ; ) {
        opcode = codestr[i];
        switch (opcode) {
            case NOP:
                i++;
                continue;

            case JUMP_ABSOLUTE:
            case CONTINUE_LOOP:
            case POP_JUMP_IF_FALSE:
            case POP_JUMP_IF_TRUE:
            case JUMP_IF_FALSE_OR_POP:
            case JUMP_IF_TRUE_OR_POP:
                j = addrmap[GETARG(codestr, i)];
                SETARG(codestr, i, j);
                break;

            case FOR_ITER:
            case JUMP_FORWARD:
            case SETUP_LOOP:
            case SETUP_EXCEPT:
            case SETUP_FINALLY:
            case SETUP_WITH:
                j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
                SETARG(codestr, i, j);
                break;
        }
        adj = CODESIZE(opcode);
        while (adj--)
            codestr[h++] = codestr[i++];
    }
    assert(h + nops == codelen);

    code = PyString_FromStringAndSize((char *)codestr, h);
    PyMem_Free(addrmap);
    PyMem_Free(codestr);
    PyMem_Free(blocks);
    return code;

 exitError:
    code = NULL;

 exitUnchanged:
    if (blocks != NULL)
        PyMem_Free(blocks);
    if (addrmap != NULL)
        PyMem_Free(addrmap);
    if (codestr != NULL)
        PyMem_Free(codestr);
    Py_XINCREF(code);
    return code;
}
Пример #15
0
// This function is fairly complex because it can either save its output to a
// file, or return it as a Python string.
PyObject *scribus_renderfont(PyObject* /*self*/, PyObject* args, PyObject* kw)
{
	char *Name = const_cast<char*>("");
	char *FileName = const_cast<char*>("");
	char *Sample = const_cast<char*>("");
	char *format = NULL;
	int Size;
	bool ret = false;
	char *kwargs[] = {const_cast<char*>("fontname"),
					  const_cast<char*>("filename"),
					  const_cast<char*>("sample"),
					  const_cast<char*>("size"),
					  const_cast<char*>("format"),
					  NULL};
	if (!PyArg_ParseTupleAndKeywords(args, kw, "esesesi|es", kwargs,
				"utf-8", &Name, "utf-8", &FileName, "utf-8", &Sample, &Size, "ascii", &format))
		return NULL;
	if (!PrefsManager::instance()->appPrefs.AvailFonts.contains(QString::fromUtf8(Name)))
	{
		PyErr_SetString(NotFoundError, QObject::tr("Font not found.","python error").toLocal8Bit().constData());
		return NULL;
	}
	QString ts = QString::fromUtf8(Sample);
	if (ts.isEmpty())
	{
		PyErr_SetString(PyExc_ValueError, QObject::tr("Cannot render an empty sample.","python error").toLocal8Bit().constData());
		return NULL;
	}
	if (!format)
		// User specified no format, so use the historical default of PPM format.
		format =  const_cast<char*>("PPM");
	QPixmap pm = FontSample(PrefsManager::instance()->appPrefs.AvailFonts[QString::fromUtf8(Name)], Size, ts, Qt::white);
	// If the user specified an empty filename, return the image data as
	// a string. Otherwise, save it to disk.
	if (QString::fromUtf8(FileName).isEmpty())
	{
		QByteArray buffer_string = "";
		QBuffer buffer(&buffer_string);
		buffer.open(QIODevice::WriteOnly);
		bool ret = pm.save(&buffer, format);
		if (!ret)
		{
			PyErr_SetString(ScribusException, QObject::tr("Unable to save pixmap","scripter error").toLocal8Bit().constData());
			return NULL;
		}
		int bufferSize = buffer.size();
		buffer.close();
		// Now make a Python string from the data we generated
		PyObject* stringPython = PyString_FromStringAndSize(buffer_string,bufferSize);
		// Return even if the result is NULL (error) since an exception will have been
		// set in that case.
		return stringPython;
	}
	else
	// Save the pixmap to a file, since the filename is non-empty
	{
		ret = pm.save(QString::fromUtf8(FileName), format);
		if (!ret)
		{
			PyErr_SetString(PyExc_Exception, QObject::tr("Unable to save pixmap","scripter error").toLocal8Bit().constData());
			return NULL;
		}
		// For historical reasons, we need to return true on success.
//		Py_INCREF(Py_True);
//		return Py_True;
//		Py_RETURN_TRUE;
		return PyBool_FromLong(static_cast<long>(true));
	}
}
Пример #16
0
static PyObject*
decode_string(JSONData *jsondata)
{
    PyObject *object;
    int c, escaping, has_unicode, string_escape;
    Py_ssize_t len;
    char *ptr;

    // look for the closing quote
    escaping = has_unicode = string_escape = False;
    ptr = jsondata->ptr + 1;
    while (True) {
        c = *ptr;
        if (c == 0) {
            PyErr_Format(JSON_DecodeError,
                         "unterminated string starting at position " SSIZE_T_F,
                         (Py_ssize_t)(jsondata->ptr - jsondata->str));
            return NULL;
        }
        if (!escaping) {
            if (c == '\\') {
                escaping = True;
            } else if (c == '"') {
                break;
            } else if (!isascii(c)) {
                has_unicode = True;
            }
        } else {
            switch(c) {
            case 'u':
                has_unicode = True;
                break;
            case '"':
            case 'r':
            case 'n':
            case 't':
            case 'b':
            case 'f':
            case '\\':
                string_escape = True;
                break;
            }
            escaping = False;
        }
        ptr++;
    }

    len = ptr - jsondata->ptr - 1;

    if (has_unicode || jsondata->all_unicode)
        object = PyUnicode_DecodeUnicodeEscape(jsondata->ptr+1, len, NULL);
    else if (string_escape)
        object = PyString_DecodeEscape(jsondata->ptr+1, len, NULL, 0, NULL);
    else
        object = PyString_FromStringAndSize(jsondata->ptr+1, len);

    if (object == NULL) {
        PyObject *type, *value, *tb, *reason;

        PyErr_Fetch(&type, &value, &tb);
        if (type == NULL) {
            PyErr_Format(JSON_DecodeError,
                         "invalid string starting at position " SSIZE_T_F,
                         (Py_ssize_t)(jsondata->ptr - jsondata->str));
        } else {
            if (PyErr_GivenExceptionMatches(type, PyExc_UnicodeDecodeError)) {
                reason = PyObject_GetAttrString(value, "reason");
                PyErr_Format(JSON_DecodeError, "cannot decode string starting"
                             " at position " SSIZE_T_F ": %s",
                             (Py_ssize_t)(jsondata->ptr - jsondata->str),
                             reason ? PyString_AsString(reason) : "bad format");
                Py_XDECREF(reason);
            } else {
                PyErr_Format(JSON_DecodeError,
                             "invalid string starting at position " SSIZE_T_F,
                             (Py_ssize_t)(jsondata->ptr - jsondata->str));
            }
        }
        Py_XDECREF(type);
        Py_XDECREF(value);
        Py_XDECREF(tb);
    } else {
        jsondata->ptr = ptr+1;
    }

    return object;
}
Пример #17
0
int
csl_execute(char *code, size_t size, const char *func_name, struct pack *pak, char **resptr, int *reslen)
{
	PyObject *pCode, *pModule, *pDict, *pFunc, *pValue, *pStr;
	PyObject *pArgs, *pkArgs;
	PyMethodDef *meth;
	node *n;

	pModule = PyImport_AddModule("__builtin__");
	pDict = PyModule_GetDict(pModule);
	for (meth = methods; meth->ml_name; meth++) {
		pCode = PyCFunction_New(meth, NULL);
		PyDict_SetItemString(pDict, meth->ml_name, pCode);
	}

	if (size == 0) {
		n = PyParser_SimpleParseString(code, Py_file_input);
		if (!n) {
			log_exception();
			return CSL_BADCODE;
		}
		pCode = (PyObject *) PyNode_Compile(n, "lala");
		PyNode_Free(n);
		if (!pCode) {
			log_exception();
			return CSL_BADCODE;
		}
	} else {
		pCode = PyMarshal_ReadObjectFromString(code, size);
		if (!pCode) {
			log_exception();
			return CSL_BADCODE;
		}
	}
	pModule = PyImport_ExecCodeModule("csl", pCode);
	Py_DECREF(pCode);

	if (!pModule || !PyModule_Check(pModule)) {
		return CSL_BADCODE;
	}

	pDict = PyModule_GetDict(pModule);
	if (!pDict) {
		Py_DECREF(pModule);
		return CSL_BADCODE;
	}

	pFunc = PyDict_GetItemString(pDict, func_name);
	if (!pFunc || !PyCallable_Check(pFunc)) {
		Py_DECREF(pModule);
		return CSL_NOFUNC;
	}

	pArgs = NULL;
	pkArgs = PyDict_New();
	while (pak) {
		PyObject *p;
		char *t, *t2;
		size_t sz;
		if (pack_get(pak, &t, &sz) == 0) break;
		if (pack_get(pak, &t2, &sz) == 0) {
			pArgs = PyTuple_New(1);
			PyTuple_SetItem(pArgs, 0, PyString_FromString(t));
			Py_DECREF(pkArgs);
			break;
		}
		p = PyString_FromStringAndSize(t2, sz);
		PyDict_SetItemString(pkArgs, t, p);
	}
	if (!pArgs) pArgs = PyTuple_New(0);

	pValue = PyObject_Call(pFunc, pArgs, pkArgs);
	if (!pValue) {
		log_exception();
		Py_DECREF(pModule);
		return CSL_FUNCERR;
	}

	pStr = PyObject_Str(pValue);

	Py_DECREF(pValue);
	Py_DECREF(pModule);

	// is return value asked?
	if (resptr == NULL) return 0;

	*reslen = PyString_Size(pStr);
	*resptr = malloc((*reslen) + 1);
	if (!*resptr) {
		Py_DECREF(pStr);
		return CSL_NOMEM;
	}
	memcpy(*resptr, PyString_AsString(pStr), *reslen);
	(*resptr)[*reslen] = '\0';

	return 0;
}
Пример #18
0
static PyObject*
decode_number(JSONData *jsondata)
{
    PyObject *object, *str;
    int c, is_float, should_stop;
    char *ptr;

    // check if we got a floating point number
    ptr = jsondata->ptr;
    is_float = should_stop = False;
    while (True) {
        c = *ptr;
        if (c == 0)
            break;
        switch(c) {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '-':
            case '+':
                break;
            case '.':
            case 'e':
            case 'E':
                is_float = True;
                break;
            default:
                should_stop = True;
        }
        if (should_stop) {
            break;
        }
        ptr++;
    }

    str = PyString_FromStringAndSize(jsondata->ptr, ptr - jsondata->ptr);
    if (str == NULL)
        return NULL;

    if (is_float) {
        object = PyFloat_FromString(str, NULL);
    } else {
        object = PyInt_FromString(PyString_AS_STRING(str), NULL, 10);
    }

    Py_DECREF(str);

    if (object == NULL) {
        PyErr_Format(JSON_DecodeError, "invalid number starting at position "
                     SSIZE_T_F, (Py_ssize_t)(jsondata->ptr - jsondata->str));
    } else {
        jsondata->ptr = ptr;
    }

    return object;
}
/* Writes a buffer to the file object
 * Make sure to hold the GIL state before calling this function
 * Returns the number of bytes written if successful, or -1 on error
 */
ssize_t pyewf_file_object_write_buffer(
         PyObject *file_object,
         const uint8_t *buffer,
         size_t size,
         libcerror_error_t **error )
{
	PyObject *argument_string     = NULL;
	PyObject *exception_string    = NULL;
	PyObject *exception_traceback = NULL;
	PyObject *exception_type      = NULL;
	PyObject *exception_value     = NULL;
	PyObject *method_name         = NULL;
	PyObject *method_result       = NULL;
	char *error_string            = NULL;
	static char *function         = "pyewf_file_object_write_buffer";

	if( file_object == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid file object.",
		 function );

		return( -1 );
	}
	if( buffer == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid buffer.",
		 function );

		return( -1 );
	}
#if SIZEOF_SIZE_T > SIZEOF_INT
	if( size > (size_t) INT_MAX )
#else
	if( size > (size_t) SSIZE_MAX )
#endif
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
		 "%s: invalid size value exceeds maximum.",
		 function );

		return( -1 );
	}
	if( size > 0 )
	{
		method_name = PyString_FromString(
			       "write" );

		argument_string = PyString_FromStringAndSize(
		                   (char *) buffer,
		                   size );

		PyErr_Clear();

		method_result = PyObject_CallMethodObjArgs(
				 file_object,
				 method_name,
				 argument_string,
				 NULL );

		if( PyErr_Occurred() )
		{
			PyErr_Fetch(
			 &exception_type,
			 &exception_value,
			 &exception_traceback );

			exception_string = PyObject_Repr(
					    exception_value );

			error_string = PyString_AsString(
					exception_string );

			if( error_string != NULL )
			{
				libcerror_error_set(
				 error,
				 LIBCERROR_ERROR_DOMAIN_IO,
				 LIBCERROR_IO_ERROR_WRITE_FAILED,
				 "%s: unable to write from file object with error: %s.",
				 function,
				 error_string );
			}
			else
			{
				libcerror_error_set(
				 error,
				 LIBCERROR_ERROR_DOMAIN_IO,
				 LIBCERROR_IO_ERROR_WRITE_FAILED,
				 "%s: unable to write from file object.",
				 function );
			}
			Py_DecRef(
			 exception_string );

			goto on_error;
		}
		Py_DecRef(
		 method_result );

		Py_DecRef(
		 argument_string );

		Py_DecRef(
		 method_name );
	}
	return( (ssize_t) size );

on_error:
	if( method_result != NULL )
	{
		Py_DecRef(
		 method_result );
	}
	if( argument_string != NULL )
	{
		Py_DecRef(
		 argument_string );
	}
	if( method_name != NULL )
	{
		Py_DecRef(
		 method_name );
	}
	return( -1 );
}
Пример #20
0
/*
 * This function is an almost verbatim copy of unicodeescape_string() from
 * Python's unicodeobject.c with the following differences:
 *
 * - it always quotes the output using double quotes.
 * - it uses \u00hh instead of \xhh in output.
 * - it also quotes \b and \f
 */
static PyObject*
encode_unicode(PyObject *unicode)
{
    PyObject *repr;
    Py_UNICODE *s;
    Py_ssize_t size;
    char *p;

    static const char *hexdigit = "0123456789abcdef";

    s = PyUnicode_AS_UNICODE(unicode);
    size = PyUnicode_GET_SIZE(unicode);

    if (size > (PY_SSIZE_T_MAX-2-1)/6) {
        PyErr_SetString(PyExc_OverflowError,
                        "unicode object is too large to make repr");
        return NULL;
    }

    repr = PyString_FromStringAndSize(NULL, 2 + 6*size + 1);
    if (repr == NULL)
        return NULL;

    p = PyString_AS_STRING(repr);

    *p++ = '"';

    while (size-- > 0) {
        Py_UNICODE ch = *s++;

        /* Escape quotes */
        if ((ch == (Py_UNICODE) PyString_AS_STRING(repr)[0] || ch == '\\')) {
            *p++ = '\\';
            *p++ = (char) ch;
            continue;
        }

#ifdef Py_UNICODE_WIDE
        /* Map 21-bit characters to '\U00xxxxxx' */
        else if (ch >= 0x10000) {
            int offset = p - PyString_AS_STRING(repr);

            /* Resize the string if necessary */
            if (offset + 12 > PyString_GET_SIZE(repr)) {
                if (_PyString_Resize(&repr, PyString_GET_SIZE(repr) + 100))
                    return NULL;
                p = PyString_AS_STRING(repr) + offset;
            }

            *p++ = '\\';
            *p++ = 'U';
            *p++ = hexdigit[(ch >> 28) & 0x0000000F];
            *p++ = hexdigit[(ch >> 24) & 0x0000000F];
            *p++ = hexdigit[(ch >> 20) & 0x0000000F];
            *p++ = hexdigit[(ch >> 16) & 0x0000000F];
            *p++ = hexdigit[(ch >> 12) & 0x0000000F];
            *p++ = hexdigit[(ch >> 8) & 0x0000000F];
            *p++ = hexdigit[(ch >> 4) & 0x0000000F];
            *p++ = hexdigit[ch & 0x0000000F];
            continue;
        }
#endif
        /* Map UTF-16 surrogate pairs to Unicode \UXXXXXXXX escapes */
        else if (ch >= 0xD800 && ch < 0xDC00) {
/* Writes a buffer to the file object
 * Make sure to hold the GIL state before calling this function
 * Returns the number of bytes written if successful, or -1 on error
 */
ssize_t pysmraw_file_object_write_buffer(
         PyObject *file_object,
         const uint8_t *buffer,
         size_t size,
         libcerror_error_t **error )
{
	PyObject *argument_string = NULL;
	PyObject *method_name     = NULL;
	PyObject *method_result   = NULL;
	static char *function     = "pysmraw_file_object_write_buffer";

	if( file_object == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid file object.",
		 function );

		return( -1 );
	}
	if( buffer == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid buffer.",
		 function );

		return( -1 );
	}
#if SIZEOF_SIZE_T > SIZEOF_INT
	if( size > (size_t) INT_MAX )
#else
	if( size > (size_t) SSIZE_MAX )
#endif
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
		 "%s: invalid size value exceeds maximum.",
		 function );

		return( -1 );
	}
	if( size > 0 )
	{
#if PY_MAJOR_VERSION >= 3
		method_name = PyUnicode_FromString(
			       "write" );
#else
		method_name = PyString_FromString(
			       "write" );
#endif
#if PY_MAJOR_VERSION >= 3
		argument_string = PyBytes_FromStringAndSize(
		                   (char *) buffer,
		                   size );
#else
		argument_string = PyString_FromStringAndSize(
		                   (char *) buffer,
		                   size );
#endif
		PyErr_Clear();

		method_result = PyObject_CallMethodObjArgs(
				 file_object,
				 method_name,
				 argument_string,
				 NULL );

		if( PyErr_Occurred() )
		{
			pysmraw_error_fetch(
			 error,
			 LIBCERROR_ERROR_DOMAIN_IO,
			 LIBCERROR_IO_ERROR_WRITE_FAILED,
			 "%s: unable to write to file object.",
			 function );

			goto on_error;
		}
		if( method_result == NULL )
		{
			libcerror_error_set(
			 error,
			 LIBCERROR_ERROR_DOMAIN_RUNTIME,
			 LIBCERROR_RUNTIME_ERROR_VALUE_MISSING,
			 "%s: missing method result.",
			 function );

			goto on_error;
		}
		Py_DecRef(
		 method_result );

		Py_DecRef(
		 argument_string );

		Py_DecRef(
		 method_name );
	}
	return( (ssize_t) size );

on_error:
	if( method_result != NULL )
	{
		Py_DecRef(
		 method_result );
	}
	if( argument_string != NULL )
	{
		Py_DecRef(
		 argument_string );
	}
	if( method_name != NULL )
	{
		Py_DecRef(
		 method_name );
	}
	return( -1 );
}
Пример #22
0
// get(key, flag=DB_KEYFIRST)
PyObject* XDBC_get(XDBC *self, PyObject *args)
{
    PyObject *keyobj = NULL;
    int flag = DB_NEXT;

	PyArg_ParseTuple(args, "Oi", &keyobj, &flag);

    DBT key;
    DBT val;
    memset(&key, 0, sizeof(DBT));
    memset(&val, 0, sizeof(DBT));

	char *ptr;
	Py_ssize_t len;
    if (keyobj != NULL && keyobj != Py_None)
    {
		PyString_AsStringAndSize(keyobj, &ptr, &len);
		key.data = ptr;
		key.size = len;
	}

    if (flag & XDB_NOT_RETRIEVE_VAL)
    {
        val.flags = DB_DBT_PARTIAL|DB_DBT_USERMEM;
        flag &= ~XDB_NOT_RETRIEVE_VAL;
    }

	if (self->dbc->c_get(self->dbc, &key, &val, flag) == 0)
	{

#ifdef XDB_ZIP

		if (val.size > 0)
		{
			uLong unzipsize = self->buffer_size;
			int err = uncompress((Bytef*)self->buffer, &unzipsize, (Bytef*)val.data, val.size);
			if (err != Z_OK)
			{
				while (err == Z_BUF_ERROR) 
				{
					XDBC_adjust_buffer(self, self->buffer_size*2);
					unzipsize = self->buffer_size;
					err = uncompress((Bytef*)self->buffer, &unzipsize, (Bytef*)val.data, val.size);
				}

				if (err != 0)
				{
					PyErr_Format(PyExc_TypeError, "DBC::get uncompress error!");
					return NULL;
				}
			}

			val.size = unzipsize;
			val.data = self->buffer;
		}
#endif

        PyObject *result = PyTuple_New(2);
		PyTuple_SET_ITEM(result, 0, PyString_FromStringAndSize((char*)key.data, key.size));
		PyTuple_SET_ITEM(result, 1, PyString_FromStringAndSize((char*)val.data, val.size));
        return result;
	}
    else
    {
        Py_INCREF(Py_None);
        return Py_None;
    }
}
Пример #23
0
static PyObject *
PyZlib_compress(PyObject *self, PyObject *args)
{
    PyObject *ReturnVal = NULL;
    Byte *input, *output;
    int length, level=Z_DEFAULT_COMPRESSION, err;
    z_stream zst;

    /* require Python string object, optional 'level' arg */
    if (!PyArg_ParseTuple(args, "s#|i:compress", &input, &length, &level))
	return NULL;

    zst.avail_out = length + length/1000 + 12 + 1;

    output = (Byte*)malloc(zst.avail_out);
    if (output == NULL) {
	PyErr_SetString(PyExc_MemoryError,
			"Can't allocate memory to compress data");
	return NULL;
    }

    /* Past the point of no return.  From here on out, we need to make sure
       we clean up mallocs & INCREFs. */

    zst.zalloc = (alloc_func)NULL;
    zst.zfree = (free_func)Z_NULL;
    zst.next_out = (Byte *)output;
    zst.next_in = (Byte *)input;
    zst.avail_in = length;
    err = deflateInit(&zst, level);

    switch(err) {
    case(Z_OK):
	break;
    case(Z_MEM_ERROR):
	PyErr_SetString(PyExc_MemoryError,
			"Out of memory while compressing data");
	goto error;
    case(Z_STREAM_ERROR):
	PyErr_SetString(ZlibError,
			"Bad compression level");
	goto error;
    default:
        deflateEnd(&zst);
	zlib_error(zst, err, "while compressing data");
	goto error;
    }

    Py_BEGIN_ALLOW_THREADS;
    err = deflate(&zst, Z_FINISH);
    Py_END_ALLOW_THREADS;

    if (err != Z_STREAM_END) {
	zlib_error(zst, err, "while compressing data");
	deflateEnd(&zst);
	goto error;
    }

    err=deflateEnd(&zst);
    if (err == Z_OK)
	ReturnVal = PyString_FromStringAndSize((char *)output,
					       zst.total_out);
    else
	zlib_error(zst, err, "while finishing compression");

 error:
    free(output);

    return ReturnVal;
}
Пример #24
0
/* Writes a buffer of media data to EWF file(s)
 * Returns a Python object holding the data if successful or NULL on error
 */
PyObject *pyewf_handle_write_buffer(
           pyewf_handle_t *pyewf_handle,
           PyObject *arguments,
           PyObject *keywords )
{
	char error_string[ PYEWF_ERROR_STRING_SIZE ];

	liberror_error_t *error     = NULL;
	PyObject *result_data       = NULL;
	static char *function       = "pyewf_handle_write_buffer";
	static char *keyword_list[] = { "size", NULL };
	ssize_t write_count         = 0;
	int write_size              = -1;

	if( pyewf_handle == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid pyewf handle.",
		 function );

		return( NULL );
	}
	if( pyewf_handle->handle == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid pyewf handle - missing libewf handle.",
		 function );

		return( NULL );
	}
	if( PyArg_ParseTupleAndKeywords(
	     arguments,
	     keywords,
	     "|i",
	     keyword_list,
	     &write_size ) == 0 )
	{
		return( NULL );
	}
	if( write_size < 0 )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid argument read size value less than zero.",
		 function );

		return( NULL );
	}
	/* Make sure the data fits into a memory buffer
	 */
	if( write_size > INT_MAX )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid argument read size value exceeds maximum.",
		 function );

		return( NULL );
	}
	result_data = PyString_FromStringAndSize(
	               NULL,
	               write_size );

	write_count = libewf_handle_write_buffer(
	               pyewf_handle->handle,
	               PyString_AsString(
	                result_data ),
	               (size_t) write_size,
	               &error );

	if( write_count != (ssize_t) write_size )
	{
		if( liberror_error_backtrace_sprint(
		     error,
		     error_string,
		     PYEWF_ERROR_STRING_SIZE ) == -1 )
		{
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to write data.",
			 function );
		}
		else
		{
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to write data.\n%s",
			 function,
			 error_string );
		}
		liberror_error_free(
		 &error );

		return( NULL );
	}
	return( result_data );
}
Пример #25
0
static PyObject *
PyZlib_objdecompress(compobject *self, PyObject *args)
{
    int err, inplen, old_length, length = DEFAULTALLOC;
    int max_length = 0;
    PyObject *RetVal;
    Byte *input;
    unsigned long start_total_out;

    if (!PyArg_ParseTuple(args, "s#|i:decompress", &input,
			  &inplen, &max_length))
	return NULL;
    if (max_length < 0) {
	PyErr_SetString(PyExc_ValueError,
			"max_length must be greater than zero");
	return NULL;
    }

    /* limit amount of data allocated to max_length */
    if (max_length && length > max_length)
	length = max_length;
    if (!(RetVal = PyString_FromStringAndSize(NULL, length)))
	return NULL;

    ENTER_ZLIB

    start_total_out = self->zst.total_out;
    self->zst.avail_in = inplen;
    self->zst.next_in = input;
    self->zst.avail_out = length;
    self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal);

    Py_BEGIN_ALLOW_THREADS
    err = inflate(&(self->zst), Z_SYNC_FLUSH);
    Py_END_ALLOW_THREADS

    /* While Z_OK and the output buffer is full, there might be more output.
       So extend the output buffer and try again.
    */
    while (err == Z_OK && self->zst.avail_out == 0) {
	/* If max_length set, don't continue decompressing if we've already
	   reached the limit.
	*/
	if (max_length && length >= max_length)
	    break;

	/* otherwise, ... */
	old_length = length;
	length = length << 1;
	if (max_length && length > max_length)
	    length = max_length;

	if (_PyString_Resize(&RetVal, length) < 0)
	    goto error;
	self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
	    + old_length;
	self->zst.avail_out = length - old_length;

	Py_BEGIN_ALLOW_THREADS
	err = inflate(&(self->zst), Z_SYNC_FLUSH);
	Py_END_ALLOW_THREADS
    }

    /* Not all of the compressed data could be accommodated in the output buffer
       of specified size. Return the unconsumed tail in an attribute.*/
    if(max_length) {
	Py_DECREF(self->unconsumed_tail);
	self->unconsumed_tail = PyString_FromStringAndSize((char *)self->zst.next_in,
							   self->zst.avail_in);
	if(!self->unconsumed_tail) {
	    Py_DECREF(RetVal);
	    RetVal = NULL;
	    goto error;
	}
    }

    /* The end of the compressed data has been reached, so set the
       unused_data attribute to a string containing the remainder of the
       data in the string.  Note that this is also a logical place to call
       inflateEnd, but the old behaviour of only calling it on flush() is
       preserved.
    */
    if (err == Z_STREAM_END) {
	Py_XDECREF(self->unused_data);  /* Free original empty string */
	self->unused_data = PyString_FromStringAndSize(
	    (char *)self->zst.next_in, self->zst.avail_in);
	if (self->unused_data == NULL) {
	    Py_DECREF(RetVal);
	    goto error;
	}
	/* We will only get Z_BUF_ERROR if the output buffer was full
	   but there wasn't more output when we tried again, so it is
	   not an error condition.
	*/
    } else if (err != Z_OK && err != Z_BUF_ERROR) {
	zlib_error(self->zst, err, "while decompressing");
	Py_DECREF(RetVal);
	RetVal = NULL;
	goto error;
    }

    _PyString_Resize(&RetVal, self->zst.total_out - start_total_out);

 error:
    LEAVE_ZLIB

    return RetVal;
}
static PyObject *
time_strftime(PyObject *self, PyObject *args)
{
    PyObject *tup = NULL;
    struct tm buf;
    const char *fmt;
    size_t fmtlen, buflen;
    char *outbuf = 0;
    size_t i;

    memset((void *) &buf, '\0', sizeof(buf));

    if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup))
        return NULL;

    if (tup == NULL) {
        time_t tt = time(NULL);
        buf = *localtime(&tt);
    } else if (!gettmarg(tup, &buf))
        return NULL;

    /* Checks added to make sure strftime() does not crash Python by
        indexing blindly into some array for a textual representation
        by some bad index (fixes bug #897625).

        Also support values of zero from Python code for arguments in which
        that is out of range by forcing that value to the lowest value that
        is valid (fixed bug #1520914).

        Valid ranges based on what is allowed in struct tm:

        - tm_year: [0, max(int)] (1)
        - tm_mon: [0, 11] (2)
        - tm_mday: [1, 31]
        - tm_hour: [0, 23]
        - tm_min: [0, 59]
        - tm_sec: [0, 60]
        - tm_wday: [0, 6] (1)
        - tm_yday: [0, 365] (2)
        - tm_isdst: [-max(int), max(int)]

        (1) gettmarg() handles bounds-checking.
        (2) Python's acceptable range is one greater than the range in C,
        thus need to check against automatic decrement by gettmarg().
    */
    if (buf.tm_mon == -1)
        buf.tm_mon = 0;
    else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
        PyErr_SetString(PyExc_ValueError, "month out of range");
                    return NULL;
    }
    if (buf.tm_mday == 0)
        buf.tm_mday = 1;
    else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
        PyErr_SetString(PyExc_ValueError, "day of month out of range");
                    return NULL;
    }
    if (buf.tm_hour < 0 || buf.tm_hour > 23) {
        PyErr_SetString(PyExc_ValueError, "hour out of range");
        return NULL;
    }
    if (buf.tm_min < 0 || buf.tm_min > 59) {
        PyErr_SetString(PyExc_ValueError, "minute out of range");
        return NULL;
    }
    if (buf.tm_sec < 0 || buf.tm_sec > 61) {
        PyErr_SetString(PyExc_ValueError, "seconds out of range");
        return NULL;
    }
    /* tm_wday does not need checking of its upper-bound since taking
    ``% 7`` in gettmarg() automatically restricts the range. */
    if (buf.tm_wday < 0) {
        PyErr_SetString(PyExc_ValueError, "day of week out of range");
        return NULL;
    }
    if (buf.tm_yday == -1)
        buf.tm_yday = 0;
    else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
        PyErr_SetString(PyExc_ValueError, "day of year out of range");
        return NULL;
    }
    if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
        PyErr_SetString(PyExc_ValueError,
                        "daylight savings flag out of range");
        return NULL;
    }

    fmtlen = strlen(fmt);

    /* I hate these functions that presume you know how big the output
     * will be ahead of time...
     */
    for (i = 1024; ; i += i) {
        outbuf = (char *)malloc(i);
        if (outbuf == NULL) {
            return PyErr_NoMemory();
        }
        buflen = strftime(outbuf, i, fmt, &buf);
        if (buflen > 0 || i >= 256 * fmtlen) {
            /* If the buffer is 256 times as long as the format,
               it's probably not failing for lack of room!
               More likely, the format yields an empty result,
               e.g. an empty format, or %Z when the timezone
               is unknown. */
            PyObject *ret;
            ret = PyString_FromStringAndSize(outbuf, buflen);
            free(outbuf);
            return ret;
        }
        free(outbuf);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        /* VisualStudio .NET 2005 does this properly */
        if (buflen == 0 && errno == EINVAL) {
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
            return 0;
        }
#endif

    }
}
Пример #27
0
PyObject *
PyString_FromString(const char *s)
{
	return PyString_FromStringAndSize(s, -1);
}
Пример #28
0
PyObject *
PyErr_NewException(char *name, PyObject *base, PyObject *dict)
{
	char *dot;
	PyObject *modulename = NULL;
	PyObject *classname = NULL;
	PyObject *mydict = NULL;
	PyObject *bases = NULL;
	PyObject *result = NULL;
	dot = strrchr(name, '.');
	if (dot == NULL) {
		PyErr_SetString(PyExc_SystemError,
			"PyErr_NewException: name must be module.class");
		return NULL;
	}
	if (base == NULL)
		base = PyExc_Exception;
	if (dict == NULL) {
		dict = mydict = PyDict_New();
		if (dict == NULL)
			goto failure;
	}
	if (PyDict_GetItemString(dict, "__module__") == NULL) {
		modulename = PyString_FromStringAndSize(name,
											 (Py_ssize_t)(dot-name));
		if (modulename == NULL)
			goto failure;
		if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
			goto failure;
	}
	//JyNI note: if ob_type is NULL, we assume that base is a Type object that was
	//not initialized because of our use-on-demand philosophy regarding PyType_Ready.
	if (base->ob_type == NULL)// && PyType_Check(base))
		PyType_Ready((PyTypeObject*) base);
	if (PyTuple_Check(base)) {
		bases = base;
		/* INCREF as we create a new ref in the else branch */
		Py_INCREF(bases);
	} else {
		bases = PyTuple_Pack(1, base);
		if (bases == NULL)
			goto failure;
	}
	//puts("enter JNI part of exception creation...");
	/* Create a real new-style class. */
	//TODO clean this up. There should be a method to create objects like is done below.
	env(NULL);
	jobject jbases = (*env)->NewObjectArray(env,
			PyTuple_GET_SIZE(bases),
			pyObjectClass, NULL);
	if ((*env)->ExceptionCheck(env))
	{
		jputs("Exception on creating jbases call:");
		jobject exc = (*env)->ExceptionOccurred(env);
		JyNI_jprintJ(exc);
		(*env)->ExceptionClear(env);
	}
	int i;
	for (i = 0; i < PyTuple_GET_SIZE(bases); ++i)
		(*env)->SetObjectArrayElement(env, jbases, i, JyNI_JythonPyObject_FromPyObject(PyTuple_GET_ITEM(bases, i)));
	if ((*env)->ExceptionCheck(env))
	{
		jputs("Exception on storing in jbases call:");
		jobject exc = (*env)->ExceptionOccurred(env);
		JyNI_jprintJ(exc);
		(*env)->ExceptionClear(env);
	}
//	jputs("PyErrNewException:");
//	if (name) jputs(name);
//	else jputs("name is NULL");
	jobject jres = (*env)->CallStaticObjectMethod(env, pyPyClass, pyPyMakeClass,
		(*env)->NewStringUTF(env, name), jbases, JyNI_JythonPyObject_FromPyObject(dict));
	if ((*env)->ExceptionCheck(env))
	{
		jputs("Exception on makeClass call:");
		jobject exc = (*env)->ExceptionOccurred(env);
		JyNI_jprintJ(exc);
		(*env)->ExceptionClear(env);
	}
	//result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO", dot+1, bases, dict);
	result = JyNI_PyObject_FromJythonPyObject(jres);
//	jputs("control name");
//	jputs(((PyTypeObject*) result)->tp_name);

  failure:
	Py_XDECREF(bases);
	Py_XDECREF(mydict);
	Py_XDECREF(classname);
	Py_XDECREF(modulename);
//	if (result == NULL) puts("exception result is NULL");
//	else puts("exception result is not NULL");
	return result;
}
PyObject *Client_gets_multi(PyClient *self, PyObject *okeys)
{
    //[ ] def gets_multi(self, keys):

    char *pKey;
    size_t cbKey;
    char *pData;
    size_t cbData;
    UINT64 cas;
    int flags;

    self->client->getBegin();

    PyObject *iterator = PyObject_GetIter(okeys);

    if (iterator == NULL)
    {
        return NULL;
    }

    PyObject *arg;

    while ( (arg = PyIter_Next(iterator)))
    {
        PyObject *ostr;

        if (PyString_Check(arg))
        {
            ostr = arg;
        }
        else
        {
            ostr = PyObject_Str(arg);
        }

        self->client->getKeyWrite(PyString_AS_STRING(ostr), PyString_GET_SIZE(ostr));
        if (ostr != arg)
        {
            Py_DECREF(ostr);
        }

        Py_DECREF(arg);
    }

    Py_DECREF(iterator);
    self->client->getFlush();

    PyObject *odict = PyDict_New();

    bool bError = false;

    while (self->client->getReadNext(&pKey, &cbKey, &pData, &cbData, &flags, &cas, &bError))
    {
        PyObject *okey  = PyString_FromStringAndSize(pKey, cbKey);
        PyObject *otuple = PyTuple_New(3);
        PyObject *ovalue = PyString_FromStringAndSize(pData, cbData);
        PyObject *oflags = PyInt_FromLong(flags);
        PyObject *ocas = PyLong_FromUnsignedLongLong(cas);

        PyTuple_SET_ITEM(otuple, 0, ovalue);
        PyTuple_SET_ITEM(otuple, 1, oflags);
        PyTuple_SET_ITEM(otuple, 2, ocas);
        PyDict_SetItem (odict, okey, otuple);

        Py_DECREF(otuple);
        Py_DECREF(okey);
    }

    if (bError)
    {
        Py_DECREF(odict);

        if (!PyErr_Occurred())
        {
            return PyErr_Format(PyExc_RuntimeError, "umemcached: %s", self->client->getError());
        }

        return NULL;
    }

    return odict;
}
Пример #30
0
// ----------------------------------------------------------------
static PyObject *
acstring_str(PyACStringObject *self)
{
	return PyString_FromStringAndSize(self->pData, self->iLen);
}