static PyObject *
flow_FlowLog(PyObject *self, PyObject *args, PyObject *kw_args)
{
    FlowLogObject *rv;
    static char *keywords[] = { "path", "mode", NULL };
    char *path = NULL, *mode = "rb";

    if (!PyArg_ParseTupleAndKeywords(args, kw_args, "s|s:FlowLog", keywords,
                                     &path, &mode))
        return NULL;
    if ((rv = PyObject_New(FlowLogObject, &FlowLog_Type)) == NULL)
        return (NULL);
    if ((rv->flowlog = PyFile_FromString(path, mode)) == NULL)
        return (NULL);
    PyFile_SetBufSize(rv->flowlog, 8192);

    return (PyObject *)rv;
}
static PyObject *
flow_FlowLog_fromfile(PyObject *self, PyObject *args, PyObject *kw_args)
{
    FlowLogObject *rv;
    static char *keywords[] = { "file", NULL };
    PyObject *file = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kw_args, "O!:FlowLog_fromfile",
                                     keywords, &PyFile_Type, (PyObject *)&file))
        return NULL;
    if ((rv = PyObject_New(FlowLogObject, &FlowLog_Type)) == NULL)
        return (NULL);
    Py_INCREF(file);
    rv->flowlog = file;
    PyFile_SetBufSize(rv->flowlog, 8192);

    return (PyObject *)rv;
}
Beispiel #3
0
static PyObject *posixfile(PyObject *self, PyObject *args, PyObject *kwds)
{
	static char *kwlist[] = {"name", "mode", "buffering", NULL};
	PyObject *file_obj = NULL;
	char *name = NULL;
	char *mode = "rb";
	DWORD access = 0;
	DWORD creation;
	HANDLE handle;
	int fd, flags = 0;
	int bufsize = -1;
	char m0, m1, m2;
	char fpmode[4];
	int fppos = 0;
	int plus;
	FILE *fp;

	if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:posixfile", kwlist,
					 Py_FileSystemDefaultEncoding,
					 &name, &mode, &bufsize))
		return NULL;

	m0 = mode[0];
	m1 = m0 ? mode[1] : '\0';
	m2 = m1 ? mode[2] : '\0';
	plus = m1 == '+' || m2 == '+';

	fpmode[fppos++] = m0;
	if (m1 == 'b' || m2 == 'b') {
		flags = _O_BINARY;
		fpmode[fppos++] = 'b';
	}
	else
		flags = _O_TEXT;
	if (plus) {
		flags |= _O_RDWR;
		access = GENERIC_READ | GENERIC_WRITE;
		fpmode[fppos++] = '+';
	}
	fpmode[fppos++] = '\0';

	switch (m0) {
	case 'r':
		creation = OPEN_EXISTING;
		if (!plus) {
			flags |= _O_RDONLY;
			access = GENERIC_READ;
		}
		break;
	case 'w':
		creation = CREATE_ALWAYS;
		if (!plus) {
			access = GENERIC_WRITE;
			flags |= _O_WRONLY;
		}
		break;
	case 'a':
		creation = OPEN_ALWAYS;
		flags |= _O_APPEND;
		if (!plus) {
			flags |= _O_WRONLY;
			access = GENERIC_WRITE;
		}
		break;
	default:
		PyErr_Format(PyExc_ValueError,
			     "mode string must begin with one of 'r', 'w', "
			     "or 'a', not '%c'", m0);
		goto bail;
	}

	handle = CreateFile(name, access,
			    FILE_SHARE_READ | FILE_SHARE_WRITE |
			    FILE_SHARE_DELETE,
			    NULL,
			    creation,
			    FILE_ATTRIBUTE_NORMAL,
			    0);

	if (handle == INVALID_HANDLE_VALUE) {
		PyErr_SetFromWindowsErrWithFilename(GetLastError(), name);
		goto bail;
	}

	fd = _open_osfhandle((intptr_t)handle, flags);

	if (fd == -1) {
		CloseHandle(handle);
		PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
		goto bail;
	}
#ifndef IS_PY3K
	fp = _fdopen(fd, fpmode);
	if (fp == NULL) {
		_close(fd);
		PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
		goto bail;
	}

	file_obj = PyFile_FromFile(fp, name, mode, fclose);
	if (file_obj == NULL) {
		fclose(fp);
		goto bail;
	}

	PyFile_SetBufSize(file_obj, bufsize);
#else
	file_obj = PyFile_FromFd(fd, name, mode, bufsize, NULL, NULL, NULL, 1);
	if (file_obj == NULL)
		goto bail;
#endif
bail:
	PyMem_Free(name);
	return file_obj;
}
Beispiel #4
0
static PyObject *
obj_read(PyObject *self, PyObject *args)
{
	/* The :compress tells PyArg_ParseTuple what function to use 
	 * in its error message
	 */
	char *pstr;
	if (!PyArg_ParseTuple(args, "s:read", &pstr)) {
		return NULL;
	}

	PyFileObject* f;
	f = PyFile_FromString((char*) pstr, "r");
	int bufsize = -1;

	PyObject* faces = PyList_New(0);
	PyObject* points = PyList_New(0);
	PyObject* normals = PyList_New(0);
	PyObject* faces_normals = PyList_New(0);

	if (f != NULL) {
		PyFile_SetBufSize(f, bufsize);

		for (;;) {
			/* From PyFile_GetLine doc
			 *
			 * If n is 0, exactly one line is read,
			 * regardless of the length of the line. If n is
			 * greater than 0, no more than n bytes will be read
			 * from the file; a partial line can be returned. In
			 * both cases, an empty string is returned if the end
			 * of the file is reached immediately.
			 */
			PyObject* line = PyFile_GetLine(f, 0);

			/* Invalid line ? */
			if (! line || ! PyString_Check(line)) break;

			/* Empty line ? */
			int num = PyString_Size(line); 
			if (num == 0) break;

			/*
			 * sscanf params
			 * http://www.cs.utah.edu/~zachary/isp/tutorials/io/io.html
			 */
			char* cline = PyString_AsString(line);
			if (cline[0] == 'f') {
                char p1[255];
                int has_normals = 0;
                int f1, f2, f3, f4;
                int n1, n2, n3, n4;
                int tmp;
                int cnt = sscanf(cline+2, "%s %s %s %s", p1, p1, p1, p1);
                // printf("%d\n", cnt);

                if (strchr(p1, '/') == NULL) {
                    if (cnt == 3)
                        sscanf(cline+2, "%d %d %d", &f1, &f2, &f3); 
                    else
                        sscanf(cline+2, "%d %d %d", &f1, &f2, &f3); 
                } else {
                    has_normals = 1;
                    if (strstr(p1, "//")) {
                        if (cnt == 3) 
                            sscanf(cline+2, "%d//%d %d//%d %d//%d", 
                                &f1, &n1, &f2, &n2, &f3, &n3);
                        else
                            sscanf(cline+2, "%d//%d %d//%d %d//%d %d//%d", 
                                &f1, &n1, &f2, &n2, &f3, &n3, &f4, &n4);
                    } else {
                        if (cnt == 3) 
                            sscanf(cline+2, "%d/%d/%d %d/%d/%d %d/%d/%d", 
                                &f1, &tmp, &n1, &f2, &tmp, &n2, &f3, &tmp, &n3);
                        else {
                            sscanf(cline+2, "%d/%d/%d %d/%d/%d %d/%d/%d %d/%d/%d", 
                                &f1, &tmp, &n1, &f2, &tmp, &n2, &f3, &tmp, &n3, &f4, &tmp, &n4);
                        }
                    }
                }

				PyObject* face = PyList_New(3);
				PyList_SetItem(face, 0, PyInt_FromLong(f1-1));
				PyList_SetItem(face, 1, PyInt_FromLong(f2-1));
				PyList_SetItem(face, 2, PyInt_FromLong(f3-1));
				PyList_Append(faces, face);

                if (cnt == 4) {
                    PyObject* face2 = PyList_New(3);
                    PyList_SetItem(face2, 0, PyInt_FromLong(f3-1));
                    PyList_SetItem(face2, 1, PyInt_FromLong(f4-1));
                    PyList_SetItem(face2, 2, PyInt_FromLong(f1-1));
                    PyList_Append(faces, face2);
                }

                if (has_normals) {
                    PyObject* n = PyList_New(3);
                    PyList_SetItem(n, 0, PyInt_FromLong(n1-1));
                    PyList_SetItem(n, 1, PyInt_FromLong(n2-1));
                    PyList_SetItem(n, 2, PyInt_FromLong(n3-1));
                    PyList_Append(faces_normals, n);

                    if (cnt == 4) {
                        PyObject* p = PyList_New(3);
                        PyList_SetItem(p, 0, PyInt_FromLong(n3-1));
                        PyList_SetItem(p, 1, PyInt_FromLong(n4-1));
                        PyList_SetItem(p, 2, PyInt_FromLong(n1-1));
                        PyList_Append(faces_normals, p);
                    }
                }
			}
			else if (cline[0] == 'v' && cline[1] == ' ') {
				double a, b, c;
				PyObject* vertex = PyList_New(3);
				sscanf(cline+2, "%lf %lf %lf", &a, &b, &c);

				// printf("%lf %lf %lf\n", a, b, c);

				PyList_SetItem(vertex, 0, PyFloat_FromDouble(a));
				PyList_SetItem(vertex, 1, PyFloat_FromDouble(b));
				PyList_SetItem(vertex, 2, PyFloat_FromDouble(c));

				PyList_Append(points, vertex);
			}
			else if (cline[0] == 'v' && cline[1] == 'n') {
				double a, b, c;
				PyObject* normal = PyList_New(3);
				sscanf(cline+3, "%lf %lf %lf", &a, &b, &c);

				// printf("%lf %lf %lf\n", a, b, c);

				PyList_SetItem(normal, 0, PyFloat_FromDouble(a));
				PyList_SetItem(normal, 1, PyFloat_FromDouble(b));
				PyList_SetItem(normal, 2, PyFloat_FromDouble(c));

				PyList_Append(normals, normal);
			}
		}
	}
	fclose(PyFile_AsFile(f));

	PyObject* tuple = PyList_New(4);
	PyList_SetItem(tuple, 0, points);
	PyList_SetItem(tuple, 1, faces);
	PyList_SetItem(tuple, 2, normals);
	PyList_SetItem(tuple, 3, faces_normals);

	return tuple;
}
// The following code is based off of KB: Q190351
static PyObject *_PyPopen(char *cmdstring, int mode, int n)
{
	HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr,
		hChildStderrRd, hChildStderrWr, hChildStdinWrDup, hChildStdoutRdDup,
		hChildStderrRdDup, hProcess; // hChildStdoutWrDup;
      
	SECURITY_ATTRIBUTES saAttr;
	BOOL fSuccess;
	int fd1, fd2, fd3;
	FILE *f1, *f2, *f3;
	long file_count;
	PyObject *f;

	saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
	saAttr.bInheritHandle = TRUE;
	saAttr.lpSecurityDescriptor = NULL;

	if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0))
		return PyWin_SetAPIError("CreatePipe");


	// Create new output read handle and the input write handle. Set
	// the inheritance properties to FALSE. Otherwise, the child inherits
	// the these handles; resulting in non-closeable handles to the pipes
	// being created.
	fSuccess = DuplicateHandle( GetCurrentProcess(), hChildStdinWr,
								GetCurrentProcess(), &hChildStdinWrDup, 0,
								FALSE,
								DUPLICATE_SAME_ACCESS);
	if (!fSuccess)
		return PyWin_SetAPIError("DuplicateHandle");

	// Close the inheritable version of ChildStdin
	// that we're using.
	CloseHandle(hChildStdinWr);

	if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))
		return PyWin_SetAPIError("CreatePipe");

	fSuccess = DuplicateHandle( GetCurrentProcess(), hChildStdoutRd,
								GetCurrentProcess(), &hChildStdoutRdDup, 0,
								FALSE,
								DUPLICATE_SAME_ACCESS);
	if (!fSuccess)
		return PyWin_SetAPIError("DuplicateHandle");

	// Close the inheritable version of ChildStdout
	// that we're using.
	CloseHandle(hChildStdoutRd);

	if (n != POPEN_4)
	{
		if (!CreatePipe(&hChildStderrRd, &hChildStderrWr, &saAttr, 0))
			return PyWin_SetAPIError("CreatePipe");
		fSuccess = DuplicateHandle( GetCurrentProcess(), hChildStderrRd,
									GetCurrentProcess(), &hChildStderrRdDup, 0,
									FALSE,
									DUPLICATE_SAME_ACCESS);
		if (!fSuccess)
			return PyWin_SetAPIError("DuplicateHandle");
		// Close the inheritable version of ChildStdErr that we're using.
		CloseHandle(hChildStderrRd);
	}
      
	switch (n)
	{
	case POPEN_1:
	    switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY))
		{
		case _O_WRONLY | _O_TEXT:
			// Case for writing to child Stdin in text mode.
			fd1 = _open_osfhandle((INT_PTR)hChildStdinWrDup, mode);
			f1 = _fdopen(fd1, "w");
			f = PyFile_FromFile(f1, cmdstring, "w", _PyPclose);
			PyFile_SetBufSize(f, 0);
			// We don't care about these pipes anymore, so close them.
			CloseHandle(hChildStdoutRdDup);
			CloseHandle(hChildStderrRdDup);
			break;

		case _O_RDONLY | _O_TEXT:
			// Case for reading from child Stdout in text mode.
			fd1 = _open_osfhandle((INT_PTR)hChildStdoutRdDup, mode);
			f1 = _fdopen(fd1, "r");
			f = PyFile_FromFile(f1, cmdstring, "r", _PyPclose);
			PyFile_SetBufSize(f, 0);
			// We don't care about these pipes anymore, so close them.
			CloseHandle(hChildStdinWrDup);
			CloseHandle(hChildStderrRdDup);
			break;

		case _O_RDONLY | _O_BINARY:
			// Case for readinig from child Stdout in binary mode.
			fd1 = _open_osfhandle((INT_PTR)hChildStdoutRdDup, mode);
			f1 = _fdopen(fd1, "rb");
			f = PyFile_FromFile(f1, cmdstring, "rb", _PyPclose);
			PyFile_SetBufSize(f, 0);
			// We don't care about these pipes anymore, so close them.
			CloseHandle(hChildStdinWrDup);
			CloseHandle(hChildStderrRdDup);
			break;

		case _O_WRONLY | _O_BINARY:
			// Case for writing to child Stdin in binary mode.
			fd1 = _open_osfhandle((INT_PTR)hChildStdinWrDup, mode);
			f1 = _fdopen(fd1, "wb");
			f = PyFile_FromFile(f1, cmdstring, "wb", _PyPclose);
			PyFile_SetBufSize(f, 0);
			// We don't care about these pipes anymore, so close them.
			CloseHandle(hChildStdoutRdDup);
			CloseHandle(hChildStderrRdDup);
			break;
		}
		file_count = 1;
		break;
	
	case POPEN_2:
	case POPEN_4:
	{
	    char *m1, *m2;
	    PyObject *p1, *p2;
	    
	    if (mode & _O_TEXT)
		{
			m1="r";
			m2="w";
		}
	    else
		{
			m1="rb";
			m2="wb";
		}

	    fd1 = _open_osfhandle((INT_PTR)hChildStdinWrDup, mode);
	    f1 = _fdopen(fd1, m2);
	    fd2 = _open_osfhandle((INT_PTR)hChildStdoutRdDup, mode);
	    f2 = _fdopen(fd2, m1);
	    p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose);
		PyFile_SetBufSize(p1, 0);
	    p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose);
		PyFile_SetBufSize(p2, 0);

	    if (n != 4)
			CloseHandle(hChildStderrRdDup);

	    f = Py_BuildValue("OO",p1,p2);
	    Py_XDECREF(p1);
	    Py_XDECREF(p2);
	    file_count = 2;
	    break;
	}
	
	case POPEN_3:
	{
	    char *m1, *m2;
	    PyObject *p1, *p2, *p3;
	    
	    if (mode & _O_TEXT)
		{
			m1="r";
			m2="w";
		}
	    else
		{
			m1="rb";
			m2="wb";
		}

	    fd1 = _open_osfhandle((INT_PTR)hChildStdinWrDup, mode);
	    f1 = _fdopen(fd1, m2);
		fd2 = _open_osfhandle((INT_PTR)hChildStdoutRdDup, mode);
	    f2 = _fdopen(fd2, m1);
		fd3 = _open_osfhandle((INT_PTR)hChildStderrRdDup, mode);
	    f3 = _fdopen(fd3, m1);
	    p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose);
	    p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose);
	    p3 = PyFile_FromFile(f3, cmdstring, m1, _PyPclose);
		PyFile_SetBufSize(p1, 0);
		PyFile_SetBufSize(p2, 0);
		PyFile_SetBufSize(p3, 0);
	    f = Py_BuildValue("OOO",p1,p2,p3);
	    Py_XDECREF(p1);
	    Py_XDECREF(p2);
	    Py_XDECREF(p3);
	    file_count = 3;
	    break;
	}
	}

	if (n == POPEN_4)
	{
		if (!_PyPopenCreateProcess(cmdstring,
								   hChildStdinRd,
								   hChildStdoutWr,
								   hChildStdoutWr,
								   &hProcess))
			return PyWin_SetAPIError("CreateProcess");
	}
	else
	{
		if (!_PyPopenCreateProcess(cmdstring,
								   hChildStdinRd,
								   hChildStdoutWr,
								   hChildStderrWr,
								   &hProcess))
			return PyWin_SetAPIError("CreateProcess");
	}

	/*
	 * Insert the files we've created into the process dictionary
	 * all referencing the list with the process handle and the
	 * initial number of files (see description below in _PyPclose).
	 * Since if _PyPclose later tried to wait on a process when all
	 * handles weren't closed, it could create a deadlock with the
	 * child, we spend some energy here to try to ensure that we
	 * either insert all file handles into the dictionary or none
	 * at all.  It's a little clumsy with the various popen modes
	 * and variable number of files involved.
	 */
	if (!_PyPopenProcs) {
		_PyPopenProcs = PyDict_New();
	}

	if (_PyPopenProcs) {
		PyObject *procObj, *hProcessObj, *intObj, *fileObj[3];
		int ins_rc[3];

		fileObj[0] = fileObj[1] = fileObj[2] = NULL;
		ins_rc[0]  = ins_rc[1]  = ins_rc[2]  = 0;

		procObj = PyList_New(2);
		hProcessObj = PyLong_FromVoidPtr(hProcess);
		intObj = PyInt_FromLong(file_count);

		if (procObj && hProcessObj && intObj) {
			PyList_SetItem(procObj,0,hProcessObj);
			PyList_SetItem(procObj,1,intObj);

			fileObj[0] = PyLong_FromVoidPtr(f1);
			if (fileObj[0]) {
			   ins_rc[0] = PyDict_SetItem(_PyPopenProcs,
						      fileObj[0],
						      procObj);
			}
			if (file_count >= 2) {
				fileObj[1] = PyLong_FromVoidPtr(f2);
				if (fileObj[1]) {
				   ins_rc[1] = PyDict_SetItem(_PyPopenProcs,
							      fileObj[1],
							      procObj);
				}
			}
			if (file_count >= 3) {
				fileObj[2] = PyLong_FromVoidPtr(f3);
				if (fileObj[2]) {
				   ins_rc[2] = PyDict_SetItem(_PyPopenProcs,
							      fileObj[2],
							      procObj);
				}
			}

			if (ins_rc[0] < 0 || !fileObj[0] ||
			    ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) ||
			    ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) {
				/* Something failed - remove any dictionary
				 * entries that did make it.
				 */
				if (!ins_rc[0] && fileObj[0]) {
					PyDict_DelItem(_PyPopenProcs,
						       fileObj[0]);
				}
				if (!ins_rc[1] && fileObj[1]) {
					PyDict_DelItem(_PyPopenProcs,
						       fileObj[1]);
				}
				if (!ins_rc[2] && fileObj[2]) {
					PyDict_DelItem(_PyPopenProcs,
						       fileObj[2]);
				}
			}
		}

		/*
		 * Clean up our localized references for the dictionary keys
		 * and value since PyDict_SetItem will Py_INCREF any copies
		 * that got placed in the dictionary.
		 */
		Py_XDECREF(procObj);
		Py_XDECREF(fileObj[0]);
		Py_XDECREF(fileObj[1]);
		Py_XDECREF(fileObj[2]);
	}

    // Child is launched. Close the parents copy of those pipe handles
	// that only the child should have open.
	// You need to make sure that no handles to the write end of the
	// output pipe are maintained in this process or else the pipe will
	// not close when the child process exits and the ReadFile will hang.
	if (!CloseHandle(hChildStdinRd))
		return PyWin_SetAPIError("CloseHandle");
      
	if (!CloseHandle(hChildStdoutWr))
		return PyWin_SetAPIError("CloseHandle");
      
	if ((n != 4) && (!CloseHandle(hChildStderrWr)))
		return PyWin_SetAPIError("CloseHandle");

	return f;
}