Exemplo n.º 1
0
// @pymethod |perfmon|UnloadPerfCounterTextStrings|
PyObject *PyUnloadPerfCounterTextStrings(PyObject *self, PyObject *args)
{
	BOOL bQuiet = 1;
	char *cmdLine;
	LONG ( __stdcall * pfnUnloadPerfCounterTextStringsA) (LPSTR   lpServiceName, BOOL bQuietModeArg);
	if (!PyArg_ParseTuple(args, "s|i:UnloadPerfCounterTextStrings", &cmdLine, &bQuiet))
		return NULL;

	HMODULE hMod = LoadLibrary(_T("loadperf.dll"));
	if (hMod==NULL)
		return PyWin_SetAPIError("LoadLibrary('loadperf.dll')");

	FARPROC fp = GetProcAddress(hMod, "UnloadPerfCounterTextStringsA");
	if (fp==NULL) {
		PyErr_SetString(PyExc_RuntimeError, "UnloadPerfCounterTextStringsA was not found in the DLL");
		FreeLibrary(hMod);
		return NULL;
	}
	pfnUnloadPerfCounterTextStringsA = (LONG ( __stdcall *) (LPSTR , BOOL bQuietModeArg))fp;
	LONG rc = (*pfnUnloadPerfCounterTextStringsA)(cmdLine, 1);

	FreeLibrary(hMod);
	if (rc!=ERROR_SUCCESS)
		return PyWin_SetAPIError("UnloadPerfCounterTextStrings", rc);
	Py_INCREF(Py_None);
	return Py_None;
}
Exemplo n.º 2
0
// @pymethod str|PyCRYPTKEY|CryptExportKey|Exports key or key pair as an encrypted blob
// @rdesc Returns a binary blob that can be imported via <om PyCRYPTPROV::CryptImportKey>
PyObject *PyCRYPTKEY::PyCryptExportKey(PyObject *self, PyObject *args, PyObject *kwargs)
{
	static char *keywords[]={"ExpKey", "BlobType", "Flags", NULL};
	DWORD dwFlags=0, dwBlobType=0, dwDataLen=0;
	PyObject *obhcryptkeyexp=NULL, *ret=NULL;
	BYTE *pbData=NULL;
	HCRYPTKEY hcryptkey, hcryptkeyexp;
	hcryptkey=((PyCRYPTKEY *)self)->GetHCRYPTKEY();

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Ok|k:CryptExportKey", keywords,
		&obhcryptkeyexp,	// @pyparm <o PyCRYPTKEY>|ExpKey||Public key or session key of destination user.  Use None if exporting a PUBLICKEYBLOB
		&dwBlobType,		// @pyparm int|BlobType||One of OPAQUEKEYBLOB,PRIVATEKEYBLOB,PUBLICKEYBLOB,SIMPLEBLOB,PLAINTEXTKEYBLOB,SYMMETRICWRAPKEYBLOB 
		&dwFlags))			// @pyparm int|Flags|0|Combination of CRYPT_DESTROYKEY,CRYPT_SSL2_FALLBACK,CRYPT_OAEP or 0
		return NULL;
	if (!PyWinObject_AsHCRYPTKEY(obhcryptkeyexp, &hcryptkeyexp, TRUE))
		return NULL;
	if (!CryptExportKey(hcryptkey, hcryptkeyexp, dwBlobType, dwFlags, NULL, &dwDataLen)){
		PyWin_SetAPIError("CryptExportKey");
		return NULL;
		}
	pbData=(BYTE *)malloc(dwDataLen);
	if (pbData==NULL)
		return PyErr_Format(PyExc_MemoryError, "PyCRYPTKEY::CryptExportKey: Unable to allocate %d bytes", dwDataLen);
	if (CryptExportKey(hcryptkey, hcryptkeyexp, dwBlobType, dwFlags, pbData, &dwDataLen))
		ret=PyString_FromStringAndSize((char *)pbData,dwDataLen);
	else
		PyWin_SetAPIError("CryptExportKey");
	if (pbData != NULL)
		free(pbData);
	return ret;
}
Exemplo n.º 3
0
BOOL DoOpenMap(HANDLE *pHandle, VOID **ppPtr)
{
    if (*pHandle || *ppPtr) {
	ReturnError("DoOpenMap, already open");
	return FALSE;
    }
    Py_BEGIN_ALLOW_THREADS
    *pHandle = CreateFileMapping((HANDLE)-1, &sa, PAGE_READWRITE, 0, BUFFER_SIZE, FixupObjectName(MAP_OBJECT_NAME));
    Py_END_ALLOW_THREADS
    if (*pHandle==NULL) {
        PyWin_SetAPIError("CreateFileMapping");
        return FALSE;
    }
    Py_BEGIN_ALLOW_THREADS
    *ppPtr = MapViewOfFile(*pHandle, FILE_MAP_ALL_ACCESS, 0, 0, BUFFER_SIZE);
    Py_END_ALLOW_THREADS
    if (*ppPtr==NULL) {
        // not allowed to access the interpreter inside
        // Py_BEGIN_ALLOW_THREADS block
        PyWin_SetAPIError("MapViewOfFile");
        CloseHandle(*pHandle);
        return FALSE;
    }
    return TRUE;
}
Exemplo n.º 4
0
// @pymethod |PyACL|AddAuditAccessAceEx|Adds an audit ACE to an Sacl, includes ace flags
PyObject *PyACL::AddAuditAccessAceEx(PyObject *self, PyObject *args)
{
	DWORD accessmask,acerevision, aceflags;
	BOOL  bAuditSuccess, bAuditFailure;
	PyObject *obSID;
	PSID psid;
	PACL psacl;
	PyACL *This = (PyACL *)self;
	psacl = This->GetACL();
	PACL psacl_padded=NULL;
	BOOL bsuccess;
	if (addauditaccessaceex==NULL)
		return PyErr_Format(PyExc_NotImplementedError,"AddAuditAccessAceEx not supported by this version of Windows");

	// @pyparm int|dwAceRevision||Revision of ACL: Must be at least ACL_REVISION_DS
	// @pyparm int|AceFlags||Combination of FAILED_ACCESS_ACE_FLAG,SUCCESSFUL_ACCESS_ACE_FLAG,CONTAINER_INHERIT_ACE,INHERIT_ONLY_ACE,INHERITED_ACE,NO_PROPAGATE_INHERIT_ACE and OBJECT_INHERIT_ACE
    // @pyparm int|dwAccessMask||Bitmask of access types to be audited
	// @pyparm <o PySID>|sid||SID for whom system audit messages will be generated
	// @pyparm int|bAuditSuccess||Set to 1 if access success should be audited, else 0
	// @pyparm int|bAuditFailure||Set to 1 if access failure should be audited, else 0

	if (!PyArg_ParseTuple(args, "lllOii:AddAuditAccessAceEx", &acerevision, &aceflags, &accessmask, &obSID, &bAuditSuccess, &bAuditFailure))
		return NULL;
	if (!PyWinObject_AsSID(obSID, &psid, FALSE))
		return NULL;
	bsuccess=(*addauditaccessaceex)(psacl, acerevision, aceflags, accessmask,  psid, bAuditSuccess, bAuditFailure);
	if (!bsuccess){
		DWORD err=GetLastError();
		if (err != ERROR_ALLOTTED_SPACE_EXCEEDED)
			return PyWin_SetAPIError("AddAuditAccessAceEx", err);
		// resize if acl too small
		unsigned short required_size=psacl->AclSize + sizeof(SYSTEM_AUDIT_ACE) + \
		                             (unsigned short)GetLengthSid(psid);
		psacl_padded = (ACL *)malloc(required_size);
		if (psacl_padded==NULL)
			return PyErr_Format(PyExc_MemoryError, "AddAuditAccessAceEx: unable to allocated %d bytes", required_size);

		ZeroMemory (psacl_padded, required_size);
		memcpy(psacl_padded,psacl,psacl->AclSize);
		psacl_padded->AclSize = required_size;
		bsuccess=(*addauditaccessaceex)(psacl_padded, acerevision, aceflags, accessmask,  
			psid, bAuditSuccess, bAuditFailure);
		if (bsuccess)
			bsuccess=This->SetACL(psacl_padded);
		else
			PyWin_SetAPIError("AddAuditAccessAceEx");
		}

	if (psacl_padded)
		free(psacl_padded);
	if (bsuccess){
		Py_INCREF(Py_None);
		return Py_None;
		}
	return NULL;
}
Exemplo n.º 5
0
// @pymethod object|PyCRYPTKEY|CryptGetKeyParam|Retrieves key parameters
// @rdesc Type of returned object is dependent on the requested attribute
PyObject *PyCRYPTKEY::PyCryptGetKeyParam(PyObject *self, PyObject *args, PyObject *kwargs)
{
	static char *keywords[]={"Param", "Flags", NULL};
	PyObject *ret=NULL;
	DWORD dwFlags=0, dwParam=0, dwDataLen=0;
	BYTE *pbData = NULL;
	HCRYPTKEY hcryptkey=((PyCRYPTKEY *)self)->GetHCRYPTKEY();

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "k|k:CryptGetKeyParam", keywords,
		&dwParam,	// @pyparm int|Param||One of the KP_* constants
		&dwFlags))	// @pyparm int|Flags|0|Reserved, use only 0
		return NULL;
	if (!CryptGetKeyParam(hcryptkey, dwParam, pbData, &dwDataLen, dwFlags))
		return PyWin_SetAPIError("CryptGetKeyParam");

	pbData=(BYTE *)malloc(dwDataLen);
	if (pbData==NULL)
		return PyErr_Format(PyExc_MemoryError, "PyCRYPTKEY::CryptGetKeyParam: Unable to allocate %d bytes", dwDataLen);

	if (!CryptGetKeyParam(hcryptkey, dwParam, pbData, &dwDataLen, dwFlags)){
		PyWin_SetAPIError("CryptGetKeyParam",GetLastError());
		goto done;
		}

	switch (dwParam){
		case KP_ALGID:
		case KP_MODE:
		case KP_MODE_BITS:
		case KP_EFFECTIVE_KEYLEN:
		case KP_BLOCKLEN:
		case KP_PERMISSIONS:
		case KP_PADDING:
		case KP_KEYLEN:
			ret=Py_BuildValue("l",*((DWORD *)pbData));
			break;
		case KP_P:
		case KP_Q:
		case KP_G:
		case KP_IV:
		case KP_SALT:
			ret=PyString_FromStringAndSize((char *)pbData,dwDataLen);
			break;
		default:
			PyErr_SetString(PyExc_NotImplementedError, "The Param specified is not yet supported");
			break;
		}
	done:
	if (pbData != NULL)
		free(pbData);
	return ret;
}
Exemplo n.º 6
0
// @pymethod |PyACL|AddAuditAccessAce|Adds an audit ACE to a Sacl
PyObject *PyACL::AddAuditAccessAce(PyObject *self, PyObject *args)
{
	DWORD accessmask,acerevision;
	BOOL  bAuditSuccess, bAuditFailure;
	PyObject *obSID;
	PSID psid;
	PACL psacl;
	PyACL *This = (PyACL *)self;
	psacl = This->GetACL();
	PACL psacl_padded=NULL;
	BOOL bsuccess;
	// @pyparm int|dwAceRevision||Revision of ACL: Pre-Win2k, must be ACL_REVISION. Win2K on up, can also be ACL_REVISION_DS
    // @pyparm int|dwAccessMask||Bitmask of access types to be audited
	// @pyparm <o PySID>|sid||SID for whom system audit messages will be generated
	// @pyparm int|bAuditSuccess||Set to 1 if access success should be audited, else 0
	// @pyparm int|bAuditFailure||Set to 1 if access failure should be audited, else 0

	if (!PyArg_ParseTuple(args, "llOii:AddAuditAccessAce", &acerevision, &accessmask, &obSID, &bAuditSuccess, &bAuditFailure))
		return NULL;
	if (!PyWinObject_AsSID(obSID, &psid, FALSE))
		return NULL;
	bsuccess=::AddAuditAccessAce(psacl, acerevision, accessmask,  psid, bAuditSuccess, bAuditFailure);
	if (!bsuccess){
		DWORD err=GetLastError();
		if (err != ERROR_ALLOTTED_SPACE_EXCEEDED)
			return PyWin_SetAPIError("AddAuditAccessAce", err);
		// resize if acl too small
		unsigned short required_size=psacl->AclSize + sizeof(SYSTEM_AUDIT_ACE) + \
		                             (unsigned short)GetLengthSid(psid);
		psacl_padded = (ACL *)malloc(required_size);
		if (psacl_padded==NULL)
			return PyErr_Format(PyExc_MemoryError, "AddAuditAccessAce: unable to allocated %d bytes", required_size);

		ZeroMemory (psacl_padded, required_size);
		memcpy(psacl_padded,psacl,psacl->AclSize);
		psacl_padded->AclSize = required_size;
		bsuccess=::AddAuditAccessAce(psacl_padded, acerevision, accessmask,  psid, bAuditSuccess, bAuditFailure);
		if (bsuccess)
			bsuccess=This->SetACL(psacl_padded);
		else
			PyWin_SetAPIError("AddAuditAccessAce");
		}

	if (psacl_padded)
		free(psacl_padded);
	if (bsuccess){
		Py_INCREF(Py_None);
		return Py_None;
		}
	return NULL;
}
Exemplo n.º 7
0
PyObject *PyACL::PyGetExplicitEntriesFromAcl(PyObject *self, PyObject *args)
{
	PyACL *This = (PyACL *)self;
	PyObject *ret=NULL;
	PyObject *obexpl;
	PEXPLICIT_ACCESS_W pList,pListstart = NULL;
	DWORD access_cnt = 0;
	DWORD access_ind, err;
	err = ::GetExplicitEntriesFromAclW(This->GetACL(), &access_cnt, &pListstart);
	if (err != ERROR_SUCCESS)
		return PyWin_SetAPIError("GetExplicitEntriesFromAcl",err);
	ret = PyTuple_New(access_cnt);
	if (!ret)
		goto done;
	pList=pListstart;
	for (access_ind=0; access_ind<access_cnt; access_ind++){
		obexpl = PyWinObject_FromEXPLICIT_ACCESS(pList);
		if (!obexpl){
			Py_DECREF(ret);
			ret=NULL;
			goto done;
			}
		PyTuple_SetItem(ret, access_ind, obexpl);
		pList++;
		}
	done:
	LocalFree(pListstart);
	return ret;
}
// @pymethod |PyIDirectSoundCaptureBuffer|Start|The PyIDirectSoundCaptureBuffer::Start method puts the capture buffer into the capture state and begins capturing data into the buffer. If the capture buffer is already in the capture state then the method has no effect.
PyObject *PyIDirectSoundCaptureBuffer::Start(PyObject *self, PyObject *args)
{
	// @pyparm int|dwFlags|0|Flags that specify the behavior for the capture buffer when capturing sound data. Possible values for dwFlags can be one of the following: 
	// DSCBSTART_LOOPING 

	DWORD dwFlags;
	IDirectSoundCaptureBuffer *pIDSCB = GetI(self);
	if ( pIDSCB == NULL )
		return NULL;
	if ( !PyArg_ParseTuple(args, "i:Start", &dwFlags) )
		return NULL;

	HRESULT hr;
	PY_INTERFACE_PRECALL;
	hr = pIDSCB->Start(dwFlags);
	PY_INTERFACE_POSTCALL;

	if (FAILED(hr)) {
		PyWin_SetAPIError("Start", hr);
		return NULL;
	}

	Py_INCREF(Py_None);
	return Py_None;
}
// @pymethod |PyIDirectSoundCaptureBuffer|GetCurrentPosition|Returns a tuple of the current capture and read position in the buffer. The capture position is ahead of the read position. These positions are not always identical due to possible buffering of captured data either on the physical device or in the host. The data after the read position up to and including the capture position is not necessarily valid data.
PyObject *PyIDirectSoundCaptureBuffer::GetCurrentPosition(PyObject *self, PyObject *args)
{
	IDirectSoundCaptureBuffer *pIDSCB = GetI(self);
	if ( pIDSCB == NULL )
		return NULL;
	if ( !PyArg_ParseTuple(args, ":GetCurrentPosition") )
		return NULL;

	HRESULT hr;
	DWORD dwCapture = 0, dwRead = 0;
	PY_INTERFACE_PRECALL;
	hr = pIDSCB->GetCurrentPosition(&dwCapture, &dwRead);
	PY_INTERFACE_POSTCALL;

	if (FAILED(hr)) {
		PyWin_SetAPIError("GetCurrentPosition", hr);
		return NULL;
	}

	PyObject *result = PyTuple_New(2);
	if (!result)
		return NULL;

	PyTuple_SetItem(result, 0, PyInt_FromLong(dwCapture));
	PyTuple_SetItem(result, 1, PyInt_FromLong(dwRead));

	return result;
}
// @pymethod |PyIDirectSoundCaptureBuffer|Initialize|Not normally used. Used IDirectSoundCapture.CreateCaptureBuffer instead.
PyObject *PyIDirectSoundCaptureBuffer::Initialize(PyObject *self, PyObject *args)
{
	PyObject *obDSCBD = NULL;
	PyObject *obDSC = NULL;
	IDirectSoundCapture *pIDSC = NULL;

	IDirectSoundCaptureBuffer *pIDSCB = GetI(self);
	if ( pIDSCB == NULL )
		return NULL;
	if ( !PyArg_ParseTuple(args, "OO:Initialize", &obDSC, &obDSCBD) )
		return NULL;

	// Todo - check and initialize pIDS

	if (!PyDSCBUFFERDESC_Check(obDSCBD)) {
		PyErr_SetString(PyExc_TypeError, "Argument 2 must be of type DSCBUFFERDESC");
		return NULL;
	}


	HRESULT hr;
	PY_INTERFACE_PRECALL;
	hr = pIDSCB->Initialize(pIDSC, &((PyDSCBUFFERDESC*)obDSCBD)->m_dscbd);
	PY_INTERFACE_POSTCALL;

	if (FAILED(hr)) {
		PyWin_SetAPIError("Initialize", hr);
		return NULL;
	}

	Py_INCREF(Py_None);
	return Py_None;
}
Exemplo n.º 11
0
// @pymethod int|win32ts|WTSSendMessage|Sends a popup message to a terminal services session
// @rdesc Returns one of IDABORT,IDCANCEL,IDIGNORE,IDNO,IDOK,IDRETRY,IDYES,IDASYNC,IDTIMEOUT, 
static PyObject *PyWTSSendMessage(PyObject *self, PyObject *args, PyObject *kwargs)
{
	static char *keywords[]={"Server","SessionId","Title","Message","Style","Timeout","Wait", NULL};
	PyObject *obh=NULL;
	HANDLE h;
	DWORD SessionId, TitleLen, MessageLen, Style, Timeout, Response;
	WCHAR *Title=NULL, *Message=NULL;
	PyObject *obTitle, *obMessage, *ret=NULL;
	BOOL Wait;
	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OkOOkkl:WTSSendMessage", keywords,
		&obh,		// @pyparm <o PyHANDLE>|Server|WTS_CURRENT_SERVER_HANDLE|Handle to a terminal server, or WTS_CURRENT_SERVER_HANDLE
		&SessionId,	// @pyparm int|SessionId||Terminal services session id
		&obTitle,	// @pyparm <o PyUnicode>|Title||Title of dialog
		&obMessage,	// @pyparm <o PyUnicode>|Message||Message to be displayed
		&Style,		// @pyparm int|Style||Usually MB_OK
		&Timeout,	// @pyparm int|Timeout||Seconds to wait before returning (only used if Wait is True)
		&Wait))		// @pyparm boolean|Wait||Specifies if function should wait for user input before returning
		return NULL;
	if (PyWinObject_AsHANDLE(obh, &h)
		&&PyWinObject_AsWCHAR(obTitle, &Title, FALSE, &TitleLen)
		&&PyWinObject_AsWCHAR(obMessage, &Message, FALSE, &MessageLen)){
		if (WTSSendMessage(h, SessionId, Title, TitleLen*sizeof(WCHAR), Message, MessageLen*sizeof(WCHAR), Style, Timeout, &Response, Wait))
			ret=PyLong_FromUnsignedLong(Response);
		else
			PyWin_SetAPIError("WTSSendMessage");
		}
	PyWinObject_FreeWCHAR(Title);
	PyWinObject_FreeWCHAR(Message);
	return ret;
}
Exemplo n.º 12
0
// @pymethod |Pymmapfile|flush|Flushes memory buffer to disk
static PyObject *
mmapfile_flush_method (mmapfile_object * self, PyObject * args)
{
	PyObject *oboffset=Py_None, *obsize=Py_None;
	size_t offset	= 0;
	size_t size	= 0;
	CHECK_VALID;
	if (!PyArg_ParseTuple (args, "|OO", 
		&oboffset,	// @pyparm int|offset|0|Position in buffer at which to flush
		&obsize))	// @pyparm int|size|0|Number of bytes to flush, 0 to flush remainder of buffer past the offset
		return NULL;
	if (oboffset != Py_None){
		offset=PyInt_AsSsize_t(oboffset);
		if (offset==-1 && PyErr_Occurred())
			return NULL;
		}
	if (obsize != Py_None){
		size=PyInt_AsSsize_t(obsize);
		if (size==-1 && PyErr_Occurred())
			return NULL;
		}
	if ((offset + size) > self->size) {
		PyErr_SetString (PyExc_ValueError, "flush values out of range");
		return NULL;
		}
	if (!FlushViewOfFile (self->data+offset, size))
		return PyWin_SetAPIError("FlushViewOfFile");
	// Previously the BOOL result was returned without raising an error, return 1 on success
	return PyInt_FromLong(1);
}
Exemplo n.º 13
0
// @pymethod <o PyDISPLAY_DEVICE>|win32api|EnumDisplayDevices|Obtain information about the display devices in a system
// @comm Accepts keyword arguments
PyObject *PyEnumDisplayDevices(PyObject *self, PyObject *args, PyObject *kwargs)
{
	CHECK_PFN(EnumDisplayDevices);
	static char *keywords[]={"Device", "DevNum", "Flags", NULL};
	TCHAR *Device=NULL;
	PyObject *obDevice = Py_None, *ret=NULL;
	DWORD DevNum=0;
	DWORD Flags=0;
	DISPLAY_DEVICE display_device;

	// @pyparm string|Device|None|Name of device, use None to obtain information for the display adapter(s) on the machine, based on DevNum
	// @pyparm int|DevNum|0|Index of device of interest, starting with zero
	// @pyparm int|Flags|0|Reserved, use 0 if passed in
	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Okk:EnumDisplayDevices", keywords, 
		&obDevice, &DevNum, &Flags))
		return NULL;
	if (!PyWinObject_AsTCHAR(obDevice, &Device, TRUE))
		return NULL;
	ZeroMemory(&display_device,sizeof(DISPLAY_DEVICE));
	display_device.cb=sizeof(DISPLAY_DEVICE);
	if (!(*pfnEnumDisplayDevices)(Device, DevNum, &display_device, Flags))
		PyWin_SetAPIError("EnumDisplayDevices");
	else
		ret = PyWinObject_FromDISPLAY_DEVICE(&display_device);
	PyWinObject_FreeTCHAR(Device);
	return ret;
}
Exemplo n.º 14
0
// @pymethod <o PyDEVMODE>|win32api|EnumDisplaySettingsEx|Lists available modes for a display device, with optional flags
// @comm Accepts keyword arguments
PyObject *PyEnumDisplaySettingsEx(PyObject *self, PyObject *args, PyObject *kwargs)
{
	CHECK_PFN(EnumDisplaySettingsEx);
	static char *keywords[]={"DeviceName","ModeNum","Flags", NULL};
	TCHAR *DeviceName=NULL;
	PyObject *obDeviceName=Py_None, *ret=NULL;
	DWORD ModeNum=0;
	DEVMODE devmode;
	DWORD Flags=0;

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Okk:EnumDisplaySettingsEx", keywords,
		&obDeviceName,	// @pyparm string|DeviceName|None|Name of device as returned by <om win32api.EnumDisplayDevices>. Can be None for default display
		&ModeNum,		// @pyparm int|ModeNum||Index of setting to return, or one of ENUM_CURRENT_SETTINGS, ENUM_REGISTRY_SETTINGS
		&Flags))		// @pyparm int|Flags|0|EDS_RAWMODE (2) is only defined flag
		return NULL;
	if (!PyWinObject_AsTCHAR(obDeviceName, &DeviceName, TRUE))
		return NULL;
	ZeroMemory(&devmode,sizeof(DEVMODE));
	devmode.dmSize=sizeof(DEVMODE);
	if (!(*pfnEnumDisplaySettingsEx)(DeviceName, ModeNum, &devmode, Flags))
		PyWin_SetAPIError("EnumDisplaySettingsEx");
	else
		ret = PyWinObject_FromDEVMODE(&devmode);
	PyWinObject_FreeTCHAR(DeviceName);
	return ret;
}
Exemplo n.º 15
0
// @pymethod tuple|PyACL|GetAce|Gets an Ace from the ACL
// @rdesc Conventional ACE's (types ACCESS_ALLOWED_ACE, ACCESS_DENIED_ACE, SYSTEM_AUDIT_ACE) are returned
// as a tuple of:
// @tupleitem 0|(int, int)|aceType, AceFlags|
// @tupleitem 1|int|Mask|
// @tupleitem 2|<o PySID>|sid|
// <nl>Object ACE's (types ACCESS_ALLOWED_OBJECT_ACE, ACCESS_DENIED_OBJECT_ACE, SYSTEM_AUDIT_OBJECT_ACE)
// are returned as a tuple:
// @tupleitem 0|(int, int)|aceType, AceFlags|
// @tupleitem 1|int|mask|
// @tupleitem 2|<o PyIID>|ObjectType|
// @tupleitem 3|<o PyIID>|InheritedObjectType|
// @tupleitem 4|<o PySID>|sid|
// <nl>For details see the API documentation.
PyObject *PyACL::GetAce(PyObject *self, PyObject *args)
{
	DWORD index;
	ACE_HEADER *pAceHeader;
	LPVOID p;
	PyACL *This = (PyACL *)self;
	// @pyparm int|index||Zero-based index of the ACE to retrieve.
	if (!PyArg_ParseTuple(args, "l:GetAce", &index))
		return NULL;
	if (!::GetAce(This->GetACL(), index, &p))
		return PyWin_SetAPIError("GetAce");
	pAceHeader=(ACE_HEADER *)p;
	switch (pAceHeader->AceType){
		case ACCESS_ALLOWED_ACE_TYPE:
		case ACCESS_DENIED_ACE_TYPE:
		case SYSTEM_AUDIT_ACE_TYPE:
		#ifdef _WIN32_WINNT_LONGHORN
		case SYSTEM_MANDATORY_LABEL_ACE_TYPE:
		#endif
			{
			ACCESS_ALLOWED_ACE *pAce=(ACCESS_ALLOWED_ACE *)p;
			return Py_BuildValue("(ll)lN", pAceHeader->AceType, pAceHeader->AceFlags, pAce->Mask, PyWinObject_FromSID((PSID)(&pAce->SidStart)));
			}
		case ACCESS_ALLOWED_OBJECT_ACE_TYPE:
		case ACCESS_DENIED_OBJECT_ACE_TYPE:
		case SYSTEM_AUDIT_OBJECT_ACE_TYPE:{
			PyObject *obSID, *obObjectType=NULL, *obInheritedObjectType=NULL;
			ACCESS_ALLOWED_OBJECT_ACE *pObjectAce=(ACCESS_ALLOWED_OBJECT_ACE *)p;

			if (!(pObjectAce->Flags&ACE_OBJECT_TYPE_PRESENT)){
				Py_INCREF(Py_None);
				obObjectType=Py_None;
				}
			if (!(pObjectAce->Flags&ACE_INHERITED_OBJECT_TYPE_PRESENT)){
				Py_INCREF(Py_None);
				obInheritedObjectType=Py_None;
				}
			// Struct members float depending on presence of GUIDs !
			if ((obObjectType==Py_None) && (obInheritedObjectType==Py_None))  // neither GUID present, SID will be in first GUID position
				obSID=PyWinObject_FromSID((PSID)&pObjectAce->ObjectType);
			else if ((obObjectType==NULL) && (obInheritedObjectType==NULL)){  // both present, SID in normal place
				obObjectType=PyWinObject_FromIID(pObjectAce->ObjectType);
				obInheritedObjectType=PyWinObject_FromIID(pObjectAce->InheritedObjectType);
				obSID=PyWinObject_FromSID((PSID)&pObjectAce->SidStart);
				}
			else{    // one present in position of first GUID, SID with be in position of second GUID
				obSID=PyWinObject_FromSID((PSID)&pObjectAce->InheritedObjectType);
				if (obObjectType==NULL)
					obObjectType=PyWinObject_FromIID(pObjectAce->ObjectType);
				else
					obInheritedObjectType=PyWinObject_FromIID(pObjectAce->ObjectType);
				}
			return Py_BuildValue("(ll)lNNN", pAceHeader->AceType, pAceHeader->AceFlags, pObjectAce->Mask, 
				obObjectType, obInheritedObjectType, obSID);
			}
		default:
			PyErr_Format(PyExc_NotImplementedError, "Ace type %d is not supported yet", pAceHeader->AceType);
			return NULL;
		}
}
Exemplo n.º 16
0
// @pymethod str|PyCRYPTKEY|CryptDecrypt|Decrypts data
PyObject *PyCRYPTKEY::PyCryptDecrypt(PyObject *self, PyObject *args, PyObject *kwargs)
{
	static char *keywords[]={"Final", "Data", "Hash", "Flags", NULL};
	PyObject *obdata, *ret=NULL, *obcrypthash=Py_None;
	BOOL Final;
	DWORD err=0, bytes_to_decrypt=0, dwFlags=0, dwDataLen=0;
	BYTE *pbData=NULL, *origdata=NULL;
	HCRYPTHASH hcrypthash=NULL;
	HCRYPTKEY hcryptkey=((PyCRYPTKEY *)self)->GetHCRYPTKEY();

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "lO|Ok:CryptDecrypt", keywords,
		&Final,			// @pyparm int|Final||Boolean, use True is this is last (or only) operation
		&obdata,		// @pyparm buffer|Data||Data to be decrypted
		&obcrypthash,	// @pyparm <o PyCRYPTHASH>|Hash|None|Hash to be used in signature verification, can be None
		&dwFlags))		// @pyparm int|Flags|0|Reserved, use only 0
		return NULL;
	if (!PyWinObject_AsHCRYPTHASH(obcrypthash, &hcrypthash, TRUE))
		return NULL;
	if (!PyWinObject_AsReadBuffer(obdata, (void **)&origdata, &bytes_to_decrypt, FALSE))
		return NULL;

	// data buffer is read-write, do not pass in python's buffer
	pbData=(BYTE *)malloc(bytes_to_decrypt);
	if (pbData==NULL)
		return PyErr_NoMemory();
	memcpy(pbData,origdata,bytes_to_decrypt);
	dwDataLen=bytes_to_decrypt;    // read/write - receives length of plaintext
	// Due to padding, should never occur that buffer needed for plaintext is larger than encrypted data
	if (!CryptDecrypt(hcryptkey, hcrypthash, Final, dwFlags, pbData, &dwDataLen))
		PyWin_SetAPIError("CryptDecrypt");
	else
		ret=PyString_FromStringAndSize((char *)pbData, dwDataLen);
	free(pbData);
	return ret;
}
Exemplo n.º 17
0
PyObject * addaceex(addaceexfunc addfunc, CHAR *funcname, PyACL *This,
	DWORD revision, DWORD aceflags, DWORD access, PyObject *obSID)
{
	/* AddAccessAllowedAceEx and AddAccessDeniedAceEx have the same signature and semantics */
	if (addfunc==NULL)
		return PyErr_Format(PyExc_NotImplementedError,"%s not supported by this version of Windows", funcname);
	PSID psid;
	BOOL bsuccess;
	PACL pacl=This->GetACL();
	PACL pacl_padded=NULL;
	if (!PyWinObject_AsSID(obSID, &psid, FALSE))
		return NULL;

	bsuccess=(*addfunc)(pacl, revision, aceflags, access, psid);
	if (bsuccess)
		bsuccess=_ReorderACL(pacl);	
	else{
		DWORD err=GetLastError();
		if (err != ERROR_ALLOTTED_SPACE_EXCEEDED)
			return PyWin_SetAPIError(funcname, err);
		// resize if dacl too small
		unsigned short required_size=pacl->AclSize + sizeof(ACCESS_ALLOWED_ACE) + \
		                             (unsigned short)GetLengthSid(psid);
		pacl_padded = (ACL *)malloc(required_size);
		if (pacl_padded==NULL)
			return PyErr_Format(PyExc_MemoryError, "%s: unable to allocated %d bytes", funcname, required_size);

		ZeroMemory (pacl_padded, required_size);
		memcpy(pacl_padded,pacl,pacl->AclSize);
		pacl_padded->AclSize = required_size;
		bsuccess=(*addfunc)(pacl_padded, revision, aceflags, access, psid);
		if (bsuccess){
			bsuccess=_ReorderACL(pacl_padded);
			if (bsuccess)
				bsuccess=This->SetACL(pacl_padded);
			}
		else
			PyWin_SetAPIError(funcname);
		}
	if (pacl_padded)
		free(pacl_padded);
	if (bsuccess){
		Py_INCREF(Py_None);
		return Py_None;
		}
	return NULL;
}
Exemplo n.º 18
0
// The non-static member functions
BOOL PyNETENUMHANDLE::Close(void)
{
	LONG rc = m_handle ? WNetCloseEnum(m_handle) : ERROR_SUCCESS;
	m_handle = 0;
	if (rc!= ERROR_SUCCESS)
		PyWin_SetAPIError("WNetCloseEnum", rc);
	return rc==ERROR_SUCCESS;
}
Exemplo n.º 19
0
// @pymethod |PyCRYPTMSG|CryptMsgClose|Closes the message handle
PyObject *PyCRYPTMSG::PyCryptMsgClose(PyObject *self, PyObject *args)
{	
	HCRYPTMSG h=((PyCRYPTMSG *)self)->GetHCRYPTMSG();
	if(!CryptMsgClose(h))
		return PyWin_SetAPIError("CryptMsgClose");
	Py_INCREF(Py_None);
	return Py_None;
}
Exemplo n.º 20
0
// @pymethod |PyCRYPTKEY|CryptDestroyKey|Releases the handle to the key (does not delete permanent keys)
PyObject *PyCRYPTKEY::PyCryptDestroyKey(PyObject *self, PyObject *args)
{	
	HCRYPTKEY hcryptkey=((PyCRYPTKEY *)self)->GetHCRYPTKEY();
	if(!CryptDestroyKey(hcryptkey))
		return PyWin_SetAPIError("CryptDestroyKey");
	Py_INCREF(Py_None);
	return Py_None;
}
Exemplo n.º 21
0
BOOL ReleaseMyMutex()
{
    if (!ReleaseMutex(hMutex)) {
	// Danger this is currently called without holding the GIL
        PyWin_SetAPIError("ReleaseMutex", GetLastError());
        return FALSE;
    }
    return TRUE;
}
Exemplo n.º 22
0
PyObject *PyACL::PySetEntriesInAcl(PyObject *self, PyObject *args)
{
	PyObject *ret=NULL;
	PEXPLICIT_ACCESS_W pexpl=NULL, pexpl_start=NULL;
	ACL *new_acl=NULL;
	PyACL *This = (PyACL *)self;
	PyObject *obexpl=NULL, *obexpl_list=NULL;
	Py_ssize_t expl_cnt=0, expl_ind=0;
	DWORD err;
	if (!PyArg_ParseTuple(args, "O:SetEntriesInAcl", &obexpl_list))
		return NULL;
	if (!PySequence_Check(obexpl_list)){
		PyErr_SetString(PyExc_TypeError, "Parm must be a list of EXPLICIT_ACCESS dictionaries");
		return NULL;
		}
	expl_cnt=PySequence_Length(obexpl_list);
	Py_ssize_t bytes_allocated=expl_cnt*sizeof(EXPLICIT_ACCESS_W);
	pexpl_start = (PEXPLICIT_ACCESS_W)malloc(bytes_allocated);
	ZeroMemory(pexpl_start,bytes_allocated);
	if (pexpl_start==NULL){
		PyErr_SetString(PyExc_MemoryError,"SetEntriesInAcl: unable to allocate EXPLICIT_ACCESS_W");
		goto done;
		}
	pexpl=pexpl_start;
	for (expl_ind=0; expl_ind<expl_cnt; expl_ind++){
		obexpl = PySequence_GetItem(obexpl_list,expl_ind);
		if (!PyWinObject_AsEXPLICIT_ACCESS(obexpl,pexpl)){
			Py_DECREF(obexpl);
			goto done;
			}
		Py_DECREF(obexpl);
		pexpl++;
		}
	err = ::SetEntriesInAclW(PyWin_SAFE_DOWNCAST(expl_cnt, Py_ssize_t, ULONG),
	                         pexpl_start,This->GetACL(),&new_acl);
	if (err!=ERROR_SUCCESS){
		PyWin_SetAPIError("SetEntriesInAcl",err);
		goto done;
		}
	if (This->SetACL(new_acl))
		ret=Py_None;
	done:
	// have to free WCHAR name from trustee structures also
	if (pexpl_start!=NULL){
		pexpl=pexpl_start;
		for (expl_ind=0; expl_ind<expl_cnt; expl_ind++){
			PyWinObject_FreeTRUSTEE(&pexpl->Trustee);
			pexpl++;
			}
		free(pexpl_start);
		}
	if (new_acl)
		LocalFree(new_acl);
	Py_XINCREF(ret);
	return ret;
}
Exemplo n.º 23
0
BOOL GetMyMutex()
{
    // Give the mutex 10 seconds before timing out
    if (WaitForSingleObject(hMutex, 10*1000)==WAIT_FAILED) {
	// Danger this is currently called without holding the GIL
        PyWin_SetAPIError("WaitForSingleObject", GetLastError());
        return FALSE;
    }
    return TRUE;
}
Exemplo n.º 24
0
// @pymethod <o PyTime>|pywintypes|DosDateTimeToTime|Converts an MS-DOS Date/Time to a standard Time object.
static PyObject *PyWin_DosDateTimeToTime(PyObject *self, PyObject *args)
{
	WORD wFatDate, wFatTime;
	if (!PyArg_ParseTuple(args, "hh", (WORD *)&wFatDate, (WORD *)&wFatTime))
		return NULL;
	FILETIME fd;
	if (!DosDateTimeToFileTime(wFatDate, wFatTime, &fd))
		return PyWin_SetAPIError("DosDateTimeToFileTime");
	return PyWinObject_FromFILETIME(fd);
}
Exemplo n.º 25
0
// @pymethod object|win32ts|WTSQueryUserConfig|Returns user configuration
// @rdesc The type of the returned value is dependent on the config class requested
static PyObject *PyWTSQueryUserConfig(PyObject *self, PyObject *args, PyObject *kwargs)
{
	static char *keywords[]={"ServerName","UserName","WTSConfigClass",NULL};
	WCHAR *ServerName=NULL, *UserName=NULL;
	PyObject *obServerName, *obUserName, *ret=NULL;
	WTS_CONFIG_CLASS WTSConfigClass;
	LPWSTR buf=NULL;
	DWORD bufsize=0;

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOk:WTSQueryUserConfig", keywords,
		&obServerName,	// @pyparm <o PyUnicode>|ServerName||Name ot terminal server
		&obUserName,	// @pyparm <o PyUnicode>|UserName||Name of user
		&WTSConfigClass))	// @pyparm int|ConfigClass||Type of information to be returned, win32ts.WTSUserConfig*
		return NULL;
	if (PyWinObject_AsWCHAR(obServerName, &ServerName, TRUE)
		&&PyWinObject_AsWCHAR(obUserName, &UserName, FALSE))
		if (!WTSQueryUserConfig(ServerName, UserName, WTSConfigClass, &buf, &bufsize))
			PyWin_SetAPIError("WTSQueryUserConfig");
		else
			switch(WTSConfigClass){
				// @flagh ConfigClass|Returned value
				case WTSUserConfigInitialProgram:				// @flag WTSUserConfigInitialProgram|Unicode string, program to be run when user logs on
				case WTSUserConfigWorkingDirectory:				// @flag WTSUserConfigWorkingDirectory|Unicode string, working dir for initial program
				case WTSUserConfigModemCallbackPhoneNumber:		// @flag WTSUserConfigModemCallbackPhoneNumber|Unicode string
				case WTSUserConfigTerminalServerProfilePath:	// @flag WTSUserConfigTerminalServerProfilePath|Unicode string
				case WTSUserConfigTerminalServerHomeDir:		// @flag WTSUserConfigTerminalServerHomeDir|Unicode string
				case WTSUserConfigTerminalServerHomeDirDrive:	// @flag WTSUserConfigTerminalServerHomeDirDrive|Unicode string
					ret=PyWinObject_FromWCHAR(buf);
					break;
				case WTSUserConfigfInheritInitialProgram:		// @flag WTSUserConfigfInheritInitialProgram|Int
				case WTSUserConfigfAllowLogonTerminalServer:	// @flag WTSUserConfigfAllowLogonTerminalServer|Int, 1 if user can log on thru Terminal Service
				case WTSUserConfigTimeoutSettingsConnections:	// @flag WTSUserConfigTimeoutSettingsConnections |Int, max connection time (ms)
				case WTSUserConfigTimeoutSettingsDisconnections:// @flag WTSUserConfigTimeoutSettingsDisconnections|Int
				case WTSUserConfigTimeoutSettingsIdle:			// @flag WTSUserConfigTimeoutSettingsIdle|Int, max idle time (ms)
				case WTSUserConfigfDeviceClientDrives:			// @flag WTSUserConfigfDeviceClientDrives|Int
				case WTSUserConfigfDeviceClientPrinters:		// @flag WTSUserConfigfDeviceClientPrinters|Int
				case WTSUserConfigfDeviceClientDefaultPrinter:	// @flag WTSUserConfigfDeviceClientDefaultPrinter|Int
				case WTSUserConfigBrokenTimeoutSettings:		// @flag WTSUserConfigBrokenTimeoutSettings|Int
				case WTSUserConfigReconnectSettings:			// @flag WTSUserConfigReconnectSettings|Int
				case WTSUserConfigModemCallbackSettings:		// @flag WTSUserConfigModemCallbackSettings|Int
				case WTSUserConfigShadowingSettings:			// @flag WTSUserConfigShadowingSettings|Int, indicates if user's session my be monitored
				case WTSUserConfigfTerminalServerRemoteHomeDir:	// @flag WTSUserConfigfTerminalServerRemoteHomeDir|Int,
					ret=PyLong_FromUnsignedLong(*(DWORD *)buf);
					break;
				default:
					PyErr_SetString(PyExc_NotImplementedError,"Config class not supported yet");
			}

	PyWinObject_FreeWCHAR(ServerName);
	PyWinObject_FreeWCHAR(UserName);
	if (buf)
		WTSFreeMemory(buf);
	return ret;
}
Exemplo n.º 26
0
// @pymethod |PyACL|Initialize|Initialize the ACL.
// @comm It should not be necessary to call this, as the ACL object
// is initialised by Python.  This method gives you a chance to trap
// any errors that may occur.
PyObject *PyACL::Initialize(PyObject *self, PyObject *args)
{
	PyACL *This = (PyACL *)self;
	PACL pacl=This->GetACL();
	if (!PyArg_ParseTuple(args, ":Initialize"))
		return NULL;
	if (!::InitializeAcl(pacl, pacl->AclSize, pacl->AclRevision))
		return PyWin_SetAPIError("InitializeAcl");
	Py_INCREF(Py_None);
	return Py_None;
}
Exemplo n.º 27
0
// @pymethod int|win32ts|ProcessIdToSessionId|Finds the session under which a process is running
static PyObject *PyProcessIdToSessionId(PyObject *self, PyObject *args, PyObject *kwargs)
{
	CHECK_PFN(ProcessIdToSessionId);
	static char *keywords[]={"ProcessId", NULL};
	DWORD ProcessId, SessionId;
	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "k:ProcessIdToSessionId", keywords,
		&ProcessId))	// @pyparm int|ProcessId||Id of a process as returned by <om win32ts.WTSEnumerateProcesses>
		return NULL;
	if (!(*pfnProcessIdToSessionId)(ProcessId, &SessionId))
		return PyWin_SetAPIError("ProcessIdToSessionId");
	return PyLong_FromUnsignedLong(SessionId);
}
Exemplo n.º 28
0
// @pymethod |PyACL|DeleteAce|Deletes specified Ace from an ACL.
PyObject *PyACL::DeleteAce(PyObject *self, PyObject *args)
{
	DWORD index;
	PyACL *This = (PyACL *)self;
	// @pyparm int|index||Zero-based index of the ACE to delete.
	if (!PyArg_ParseTuple(args, "l:DeleteAce", &index))
		return NULL;
	if (!::DeleteAce(This->GetACL(), index))
		return PyWin_SetAPIError("DeleteAce");
    Py_INCREF(Py_None);
	return Py_None;
}
Exemplo n.º 29
0
// @pymethod <o PyHANDLE>|win32ts|WTSQueryUserToken|Retrieves the access token for a session
// @comm This function is intended only for use by trusted processes that have SE_TCB_PRIVILEGE enabled
static PyObject *PyWTSQueryUserToken(PyObject *self, PyObject *args, PyObject *kwargs)
{
	CHECK_PFN(WTSQueryUserToken);
	static char *keywords[]={"SessionId", NULL};
	HANDLE h;
	ULONG SessionId;
	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "k:WTSQueryUserToken", keywords,
		&SessionId))	// @pyparm int|SessionId||Terminal services session id
		return NULL;
	if (!(*pfnWTSQueryUserToken)(SessionId, &h))
		return PyWin_SetAPIError("WTSQueryUserToken");
	return PyWinObject_FromHANDLE(h);
}
Exemplo n.º 30
0
// @pymethod str|PyCRYPTKEY|CryptEncrypt|Encrypts and optionally hashes data
PyObject *PyCRYPTKEY::PyCryptEncrypt(PyObject *self, PyObject *args, PyObject *kwargs)
{
	static char *keywords[]={"Final", "Data", "Hash", "Flags", NULL};
	PyObject *obdata, *ret=NULL, *obcrypthash=Py_None;
	BOOL Final;
	DWORD err=0, bytes_to_encrypt=0, dwFlags=0, dwDataLen=0, dwBufLen=0;
	BYTE *pbData=NULL, *origdata;
	HCRYPTHASH hcrypthash=NULL;
	HCRYPTKEY hcryptkey=((PyCRYPTKEY *)self)->GetHCRYPTKEY();

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "lO|Ok:CryptEncrypt", keywords,
		&Final,			// @pyparm int|Final||Boolean, use True if this is final encryption operation		
		&obdata,		// @pyparm buffer|Data||Data to be encrypted
		&obcrypthash,	// @pyparm <o PyCRYPTHASH>|Hash|None|Hash to be updated with data passed in, can be None
		&dwFlags))		// @pyparm int|Flags|0|Reserved, use 0 if passed in
		return NULL;
	if (!PyWinObject_AsHCRYPTHASH(obcrypthash, &hcrypthash, TRUE))
		return NULL;
	if (!PyWinObject_AsReadBuffer(obdata, (void **)&origdata, &bytes_to_encrypt, FALSE))
		return NULL;
	dwDataLen=bytes_to_encrypt;    // read/write - receives bytes needed for encrypted data
	dwBufLen=bytes_to_encrypt;

	// First call to get required buffer size - don't pass hash, or it will be updated twice
	if (!CryptEncrypt(hcryptkey, NULL, Final, dwFlags, NULL, &dwDataLen, dwBufLen))
		return PyWin_SetAPIError("CryptEncrypt");
	pbData=(BYTE *)malloc(dwDataLen);
	if (pbData==NULL)
		return PyErr_NoMemory();
	memcpy(pbData,origdata,bytes_to_encrypt);
	dwBufLen=dwDataLen;
	dwDataLen=bytes_to_encrypt;
	if (!CryptEncrypt(hcryptkey, hcrypthash, Final, dwFlags, pbData, &dwDataLen, dwBufLen))
		PyWin_SetAPIError("CryptEncrypt");
	else
		ret=PyString_FromStringAndSize((char *)pbData, dwDataLen);
	free(pbData);
	return ret;
}