Exemple #1
0
int
OggFlacDecoder_init(decoders_OggFlacDecoder *self,
                    PyObject *args, PyObject *kwds) {
    char* filename;
    ogg_status result;
    uint16_t header_packets;

    self->ogg_stream = NULL;
    self->ogg_file = NULL;
    self->subframe_data = aa_int_new();
    self->residuals = a_int_new();
    self->qlp_coeffs = a_int_new();
    self->framelist_data = a_int_new();
    self->audiotools_pcm = NULL;
    self->packet = br_substream_new(BS_BIG_ENDIAN);
    self->stream_finalized = 0;

    if (!PyArg_ParseTuple(args, "si", &filename, &(self->channel_mask)))
        return -1;

    if (self->channel_mask < 0) {
        PyErr_SetString(PyExc_ValueError, "channel_mask must be >= 0");
        return -1;
    }

    self->ogg_file = fopen(filename, "rb");
    if (self->ogg_file == NULL) {
        PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
        return -1;
    } else {
        self->ogg_stream = oggreader_open(self->ogg_file);
    }

    /*the first packet should be the FLAC's STREAMINFO*/
    if ((result = oggreader_next_packet(self->ogg_stream,
                                        self->packet)) == OGG_OK) {
        if (!oggflac_read_streaminfo(self->packet,
                                     &(self->streaminfo),
                                     &header_packets))
            return -1;
    } else {
        PyErr_SetString(ogg_exception(result), ogg_strerror(result));
        return -1;
    }

    /*skip subsequent header packets*/
    for (; header_packets > 0; header_packets--) {
        if ((result = oggreader_next_packet(self->ogg_stream,
                                            self->packet)) != OGG_OK) {
            PyErr_SetString(ogg_exception(result), ogg_strerror(result));
            return -1;
        }
    }

    /*initialize the output MD5 sum*/
    audiotools__MD5Init(&(self->md5));

    /*add callback for CRC16 calculation*/
    br_add_callback(self->packet, (bs_callback_f)flac_crc16, &(self->crc16));

    /*setup a framelist generator function*/
    if ((self->audiotools_pcm = open_audiotools_pcm()) == NULL)
        return -1;

    /*mark stream as not closed and ready for reading*/
    self->closed = 0;

    return 0;
}
Exemple #2
0
static PyObject *_listdir(char *path, int pathlen, int keepstat, char *skip)
{
	PyObject *list, *elem, *stat, *ret = NULL;
	char fullpath[PATH_MAX + 10];
	int kind, err;
	struct stat st;
	struct dirent *ent;
	DIR *dir;
#ifdef AT_SYMLINK_NOFOLLOW
	int dfd = -1;
#endif

	if (pathlen >= PATH_MAX) {
		PyErr_SetString(PyExc_ValueError, "path too long");
		goto error_value;
	}
	strncpy(fullpath, path, PATH_MAX);
	fullpath[pathlen] = '/';

#ifdef AT_SYMLINK_NOFOLLOW
	dfd = open(path, O_RDONLY);
	if (dfd == -1) {
		PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
		goto error_value;
	}
	dir = fdopendir(dfd);
#else
	dir = opendir(path);
#endif
	if (!dir) {
		PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
		goto error_dir;
 	}

	list = PyList_New(0);
	if (!list)
		goto error_list;

	while ((ent = readdir(dir))) {
		if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
			continue;

		kind = entkind(ent);
		if (kind == -1 || keepstat) {
#ifdef AT_SYMLINK_NOFOLLOW
			err = fstatat(dfd, ent->d_name, &st,
				      AT_SYMLINK_NOFOLLOW);
#else
			strncpy(fullpath + pathlen + 1, ent->d_name,
				PATH_MAX - pathlen);
			fullpath[PATH_MAX] = 0;
			err = lstat(fullpath, &st);
#endif
			if (err == -1) {
				strncpy(fullpath + pathlen + 1, ent->d_name,
					PATH_MAX - pathlen);
				fullpath[PATH_MAX] = 0;
				PyErr_SetFromErrnoWithFilename(PyExc_OSError,
							       fullpath);
				goto error;
			}
			kind = st.st_mode & S_IFMT;
		}

		/* quit early? */
		if (skip && kind == S_IFDIR && !strcmp(ent->d_name, skip)) {
			ret = PyList_New(0);
			goto error;
		}

		if (keepstat) {
			stat = PyObject_CallObject((PyObject *)&listdir_stat_type, NULL);
			if (!stat)
				goto error;
			memcpy(&((struct listdir_stat *)stat)->st, &st, sizeof(st));
			elem = Py_BuildValue("siN", ent->d_name, kind, stat);
		} else
			elem = Py_BuildValue("si", ent->d_name, kind);
		if (!elem)
			goto error;

		PyList_Append(list, elem);
		Py_DECREF(elem);
	}

	ret = list;
	Py_INCREF(ret);

error:
	Py_DECREF(list);
error_list:
	closedir(dir);
error_dir:
#ifdef AT_SYMLINK_NOFOLLOW
	close(dfd);
#endif
error_value:
	return ret;
}
/** Find the executable, argument list and environment
 *
 * This will also fill in the command attribute.
 *
 * The sysctl calls here don't use a wrapper as in darwin_prcesstable.c since
 * they know the size of the returned structure already.
 *
 * The layout of the raw argument space is documented in start.s, which is
 * part of the Csu project.  In summary, it looks like:
 *
 * XXX: This layout does not match whith what the code does.  The code seems
 * to think exec_path is in between the first argc and arg[0], also the data
 * returned by ssyctl() seems to be starting at the first argc according to
 * the code.
 *
 * /---------------\ 0x00000000
 * :               :
 * :               :
 * |---------------|
 * | argc          |
 * |---------------|
 * | arg[0]        |
 * |---------------|
 * :               :
 * :               :
 * |---------------|
 * | arg[argc - 1] |
 * |---------------|
 * | 0             |
 * |---------------|
 * | env[0]        |
 * |---------------|
 * :               :
 * :               :
 * |---------------|
 * | env[n]        |
 * |---------------|
 * | 0             |
 * |---------------| <-- Beginning of data returned by sysctl() is here.
 * | argc          |
 * |---------------|
 * | exec_path     |
 * |:::::::::::::::|
 * |               |
 * | String area.  |
 * |               |
 * |---------------| <-- Top of stack.
 * :               :
 * :               :
 * \---------------/ 0xffffffff
 */
static int
set_exe(struct psi_process *proci, struct kinfo_proc *p)
{
    int mib[3], argmax, nargs;
    size_t size;
    char *procargs, *cp;
    int i;
    int env_start = 0;

    /* Get the maximum process arguments size. */
    mib[0] = CTL_KERN;
    mib[1] = KERN_ARGMAX;
    size = sizeof(argmax);

    if (sysctl(mib, 2, &argmax, &size, NULL, 0) == -1) {
        PyErr_SetFromErrnoWithFilename(PyExc_OSError, "sysctl() argmax");
        return -1;
    }

    /* Allocate space for the arguments. */
    procargs = (char *)psi_malloc(argmax);
    if (procargs == NULL)
        return -1;

    /* Make a sysctl() call to get the raw argument space of the process. */
    mib[0] = CTL_KERN;
    mib[1] = KERN_PROCARGS2;
    mib[2] = p->kp_proc.p_pid;

    size = (size_t)argmax;

    if (sysctl(mib, 3, procargs, &size, NULL, 0) == -1) {
        /* We failed to get the exe info, but it's not fatal. We probably just
         * didn't have permission to access the KERN_PROCARGS2 for this
         * process. */
        psi_free(procargs);
        proci->exe_status  = PSI_STATUS_PRIVS;
        proci->argc_status = PSI_STATUS_PRIVS;
        proci->argv_status = PSI_STATUS_PRIVS;
        proci->envc_status = PSI_STATUS_PRIVS;
        proci->envv_status = PSI_STATUS_PRIVS;
        proci->command_status = PSI_STATUS_PRIVS;
        return 0;
    }

    memcpy(&nargs, procargs, sizeof(nargs));
    cp = procargs + sizeof(nargs);

    /* Save the exe */
    proci->exe = psi_strdup(cp);
    if (proci->exe == NULL) {
        psi_free(procargs);
        return -1;
    }
    proci->exe_status = PSI_STATUS_OK;

    /* Skip over the exe. */
    cp += strlen(cp);
    if (cp == &procargs[size]) {
        psi_free(procargs);
        PyErr_SetString(PyExc_OSError, "Did not find args and env");
        return -1;
    }

    /* Skip trailing '\0' characters. */
    for (; cp < &procargs[size]; cp++) {
        if (*cp != '\0') {
            /* Beginning of first argument reached. */
            break;
        }
    }
    if (cp == &procargs[size]) {
        psi_free(procargs);
        /* We dont' have any arguments or environment */
        if (nargs == 0) {
            proci->argc = 0;
            proci->argc_status = PSI_STATUS_OK;
            proci->argv = NULL;
            proci->argv_status = PSI_STATUS_OK;
            proci->envc = 0;
            proci->envc_status = PSI_STATUS_OK;
            proci->envv = NULL;
            proci->envv_status = PSI_STATUS_OK;
            /* Update proci->command */
            if (command_from_argv(&proci->command, proci->argv, proci->argc) < 0) {
                psi_free(procargs);
                return -1;
            }
            proci->command_status = PSI_STATUS_OK;
            return 0;
        } else {
            PyErr_SetString(PyExc_OSError, "Did not find args and env");
            return -1;
        }
    }

    /* The argument list */
    proci->argc = nargs;
    proci->argc_status = PSI_STATUS_OK;
    proci->argv = psi_strings_to_array(cp, nargs);
    if (proci->argv == NULL) {
        psi_free(procargs);
        return -1;
    }
    proci->argv_status = PSI_STATUS_OK;
    if (command_from_argv(&proci->command, proci->argv, proci->argc) < 0) {
        psi_free(procargs);
        return -1;
    }
    proci->command_status = PSI_STATUS_OK;

    /* The environment */
    for (i = 0; i < nargs; i++) {
        env_start += strlen(proci->argv[i])+1;
    }
    env_start--;
    proci->envc = 0;
    for (i = 0; ; i++) {
        if (*(cp+env_start + i) == '\0') {
            if (*(cp+env_start + i + 1) == '\0')
                break;
            else
                proci->envc++;
        }
    }
    proci->envc_status = PSI_STATUS_OK;
    proci->envv = psi_strings_to_array(cp+env_start+1, proci->envc);
    psi_free(procargs);
    if (proci->envv == NULL)
        return -1;
    proci->envv_status = PSI_STATUS_OK;

    return 0;
}
int
DVDA_Title_init(decoders_DVDA_Title *self, PyObject *args, PyObject *kwds) {
    static char *kwlist[] = {"audio_ts",
                             "titleset",
                             "start_sector",
                             "end_sector",

                             "cdrom",
                             NULL};
    char* audio_ts;
    unsigned titleset;
    unsigned start_sector;
    unsigned end_sector;
#else
int
    DVDA_Title_init(decoders_DVDA_Title *self,
                    char* audio_ts,
                    unsigned titleset,
                    unsigned start_sector,
                    unsigned end_sector)
{
#endif
    char* cdrom = NULL;

    self->sector_reader = NULL;
    self->packet_reader = NULL;

    self->packet_data = buf_new();

    self->frames = buf_new();

    self->pcm_frames_remaining = 0;

    self->bits_per_sample = 0;
    self->sample_rate = 0;
    self->channel_count = 0;
    self->channel_mask = 0;

    self->mlp_decoder = open_mlp_decoder(self->frames);

    self->codec_framelist = aa_int_new();
    self->output_framelist = aa_int_new();

#ifndef STANDALONE
    if ((self->audiotools_pcm = open_audiotools_pcm()) == NULL)
        return -1;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "sIII|s",
                                     kwlist,
                                     &audio_ts,
                                     &titleset,
                                     &start_sector,
                                     &end_sector,
                                     &cdrom))
        return -1;
#endif

    /*setup a sector reader according to AUDIO_TS and cdrom device*/
    if ((self->sector_reader = open_sector_reader(audio_ts,
                                                  titleset,
                                                  cdrom)) == NULL) {
#ifndef STANDALONE
        PyErr_SetFromErrnoWithFilename(PyExc_IOError, audio_ts);
#endif
        return -1;
    }

    /*setup a packet reader according to start and end sector
      this packet reader will be shared by all returned DVDA_Tracks*/
    self->packet_reader = open_packet_reader(self->sector_reader,
                                             start_sector,
                                             end_sector);

    return 0;
}
static oss_audio_t *
newossobject(PyObject *arg)
{
    oss_audio_t *self;
    int fd, afmts, imode;
    char *basedev = NULL;
    char *mode = NULL;

    /* Two ways to call open():
         open(device, mode) (for consistency with builtin open())
         open(mode)         (for backwards compatibility)
       because the *first* argument is optional, parsing args is
       a wee bit tricky. */
    if (!PyArg_ParseTuple(arg, "s|s:open", &basedev, &mode))
       return NULL;
    if (mode == NULL) {                 /* only one arg supplied */
       mode = basedev;
       basedev = NULL;
    }

    if (strcmp(mode, "r") == 0)
        imode = O_RDONLY;
    else if (strcmp(mode, "w") == 0)
        imode = O_WRONLY;
    else if (strcmp(mode, "rw") == 0)
        imode = O_RDWR;
    else {
        PyErr_SetString(OSSAudioError, "mode must be 'r', 'w', or 'rw'");
        return NULL;
    }

    /* Open the correct device: either the 'device' argument,
       or the AUDIODEV environment variable, or "/dev/dsp". */
    if (basedev == NULL) {              /* called with one arg */
       basedev = getenv("AUDIODEV");
       if (basedev == NULL)             /* $AUDIODEV not set */
          basedev = "/dev/dsp";
    }

    /* Open with O_NONBLOCK to avoid hanging on devices that only allow
       one open at a time.  This does *not* affect later I/O; OSS
       provides a special ioctl() for non-blocking read/write, which is
       exposed via oss_nonblock() below. */
    if ((fd = open(basedev, imode|O_NONBLOCK)) == -1) {
        PyErr_SetFromErrnoWithFilename(PyExc_IOError, basedev);
        return NULL;
    }

    /* And (try to) put it back in blocking mode so we get the
       expected write() semantics. */
    if (fcntl(fd, F_SETFL, 0) == -1) {
        close(fd);
        PyErr_SetFromErrnoWithFilename(PyExc_IOError, basedev);
        return NULL;
    }

    if (ioctl(fd, SNDCTL_DSP_GETFMTS, &afmts) == -1) {
        PyErr_SetFromErrnoWithFilename(PyExc_IOError, basedev);
        return NULL;
    }
    /* Create and initialize the object */
    if ((self = PyObject_New(oss_audio_t, &OSSAudioType)) == NULL) {
        close(fd);
        return NULL;
    }
    self->fd = fd;
    self->mode = imode;
    self->icount = self->ocount = 0;
    self->afmts  = afmts;
    return self;
}
Exemple #6
0
/*
 * Return what CPU the process is running on.
 */
static PyObject *
psutil_proc_cpu_num(PyObject *self, PyObject *args) {
    int fd = NULL;
    int pid;
    char path[1000];
    struct prheader header;
    struct lwpsinfo *lwp;
    char *lpsinfo = NULL;
    char *ptr = NULL;
    int nent;
    int size;
    int proc_num;
    size_t nbytes;
    const char *procfs_path;

    if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path))
        return NULL;

    sprintf(path, "%s/%i/lpsinfo", procfs_path, pid);
    fd = open(path, O_RDONLY);
    if (fd == -1) {
        PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
        return NULL;
    }

    // read header
    nbytes = pread(fd, &header, sizeof(header), 0);
    if (nbytes == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }
    if (nbytes != sizeof(header)) {
        PyErr_SetString(
            PyExc_RuntimeError, "read() file structure size mismatch");
        goto error;
    }

    // malloc
    nent = header.pr_nent;
    size = header.pr_entsize * nent;
    ptr = lpsinfo = malloc(size);
    if (lpsinfo == NULL) {
        PyErr_NoMemory();
        goto error;
    }

    // read the rest
    nbytes = pread(fd, lpsinfo, size, sizeof(header));
    if (nbytes == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }
    if (nbytes != size) {
        PyErr_SetString(
            PyExc_RuntimeError, "read() file structure size mismatch");
        goto error;
    }

    // done
    lwp = (lwpsinfo_t *)ptr;
    proc_num = lwp->pr_onpro;
    close(fd);
    free(ptr);
    free(lpsinfo);
    return Py_BuildValue("i", proc_num);

error:
    if (fd != -1)
        close(fd);
    if (ptr != NULL)
        free(ptr);
    if (lpsinfo != NULL)
        free(lpsinfo);
    return NULL;
}
Exemple #7
0
static PyObject *
open_the_file(PyFileObject *f, char *name, char *mode)
{
	assert(f != NULL);
	assert(PyFile_Check(f));
	assert(name != NULL);
	assert(mode != NULL);
	assert(f->f_fp == NULL);

	/* rexec.py can't stop a user from getting the file() constructor --
	   all they have to do is get *any* file object f, and then do
	   type(f).  Here we prevent them from doing damage with it. */
	if (PyEval_GetRestricted()) {
		PyErr_SetString(PyExc_IOError,
			"file() constructor not accessible in restricted mode");
		return NULL;
	}
	errno = 0;
#ifdef HAVE_FOPENRF
	if (*mode == '*') {
		FILE *fopenRF();
		f->f_fp = fopenRF(name, mode+1);
	}
	else
#endif
	{
		Py_BEGIN_ALLOW_THREADS
		f->f_fp = fopen(name, mode);
		Py_END_ALLOW_THREADS
	}
	if (f->f_fp == NULL) {
#ifdef NO_FOPEN_ERRNO
		/* Metroworks only, wich does not always sets errno */
		if (errno == 0) {
			PyObject *v;
			v = Py_BuildValue("(is)", 0, "Cannot open file");
			if (v != NULL) {
				PyErr_SetObject(PyExc_IOError, v);
				Py_DECREF(v);
			}
			return NULL;
		}
#endif
#ifdef _MSC_VER
		/* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
		 * across all Windows flavors.  When it sets EINVAL varies
		 * across Windows flavors, the exact conditions aren't
		 * documented, and the answer lies in the OS's implementation
		 * of Win32's CreateFile function (whose source is secret).
		 * Seems the best we can do is map EINVAL to ENOENT.
		 */
		if (errno == 0)	/* bad mode string */
			errno = EINVAL;
		else if (errno == EINVAL) /* unknown, but not a mode string */
			errno = ENOENT;
#endif
		if (errno == EINVAL)
			PyErr_Format(PyExc_IOError, "invalid mode: %s",
				     mode);
		else
			PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
		f = NULL;
	}
	return (PyObject *)f;
}
Exemple #8
0
static PyObject *
AMC_fromFile (AMC *self, PyObject *args)
{
	char *filename;
	GIOChannel *file;
	AMC *motion;
	gchar *line;
	int terminator;
	guint64 current_frame, total_frames;
	GSList *bones = NULL;
	GSList *dofs = NULL;
	GSList *data = NULL;
	GSList *i, *j;
	float *f;
	PyArrayObject *pao;

	// get filename
	if (!PyArg_ParseTuple (args, "s;expected 'string'", &filename))
		return NULL;

	file = g_io_channel_new_file (filename, "r", NULL);
	if (file == NULL) {
		// FIXME - we should be using the GError, not errno
		return PyErr_SetFromErrnoWithFilename (PyExc_IOError, filename);
	}

	motion = (AMC *) CreateAMC ();

	// first pass - go through, grab comments & format, parse first frame
	// to find #dof for each bone, total number of frames
	while (g_io_channel_read_line (file, &line, NULL, &terminator, NULL) == G_IO_STATUS_NORMAL) {
		// get rid of line terminator
		line[terminator] = '\0';

		// parse data
		if (line[0] == '#') {
			// comment
			PyObject *string = PyString_FromString (line);
			PyList_Append (motion->comments, string);
			Py_DECREF (string);
		} else if (line[0] == ':') {
			// format specifier
			PyObject *string = PyString_FromString (line);
			PyList_Append (motion->format, string);
			Py_DECREF (string);
		} else {
			gchar *ch;
			gboolean newframe = TRUE;

			g_strstrip (line);

			// empty line?
			if (strlen (line) == 0)
				continue;

			// determine if this line just contains an int - if so, it's
			// the beginning of a new frame
			for (ch = line; *ch; ch++) {
				if (!g_ascii_isdigit (*ch)) {
					newframe = FALSE;
					break;
				}
			}

			if (newframe) {
				current_frame = g_ascii_strtoull (line, NULL, 10);
			} else {
				if (current_frame == 1) {
					gchar **tokens = g_strsplit (line, " ", 0);
					guint token;
					guint dof = 0;

					g_strstrip (tokens[0]);
					for (token = 1; tokens[token]; token++) {
						g_strstrip (tokens[token]);
						if (strlen (tokens[token]))
							dof++;
					}
					// create two lists, one with the names of the bones (so we
					// know what order things go in), the other with the number
					// of dofs for each bone
					bones = g_slist_append (bones, g_strdup (tokens[0]));
					dofs = g_slist_append (dofs, GUINT_TO_POINTER (dof));
					g_strfreev (tokens);
				}
			}
		}
		g_free (line);
	}

	total_frames = current_frame;

	// allocate Numeric arrays
	for (i = dofs; i; i = g_slist_next (i)) {
		int dims[2];
		guint dof = GPOINTER_TO_UINT (i->data);
		PyObject *array;

		dims[0] = total_frames;
		dims[1] = dof;

		array = PyArray_FromDims (2, dims, PyArray_FLOAT);
		data = g_slist_append (data, array);
	}

	g_io_channel_seek_position (file, 0, G_SEEK_SET, NULL);

	// second pass - read in all the data, now that we have space allocated for it
	while (g_io_channel_read_line (file, &line, NULL, &terminator, NULL) == G_IO_STATUS_NORMAL) {
		// get rid of line terminator
		line[terminator] = '\0';

		// parse data
		if (line[0] == '#' || line[0] == ':') {
			// we read these in during the first pass. ignore
			continue;
		} else {
			gchar *ch;
			gboolean newframe = TRUE;

			g_strstrip (line);

			// empty line ?
			if (strlen (line) == 0)
				continue;

			// determine if this line just contains an int - if so, it's
			// the beginning of a new frame
			for (ch = line; *ch; ch++) {
				if (!g_ascii_isdigit (*ch)) {
					newframe = FALSE;
					break;
				}
			}


			if (newframe) {
				current_frame = g_ascii_strtoull (line, NULL, 10) - 1;
				i = data;
				pao = i->data;
			} else {
				gchar **tokens = g_strsplit (line, " ", 0);
				guint token, dof = 0;

				g_strstrip (tokens[0]);
				for (token = 1; tokens[token]; token++) {
					g_strstrip (tokens[token]);
					if (strlen (tokens[token])) {
						f = (float *) (pao->data + (current_frame * pao->strides[0]) + (dof * pao->strides[1]));
						*f = (float) g_ascii_strtod (tokens[token], NULL);
					}
					dof++;
				}

				g_strfreev (tokens);
				i = g_slist_next (i);
				if (i != NULL) {
					pao = i->data;
				}
			}
		}

		g_free (line);
	}

	for (i = data, j = bones; i; i = g_slist_next (i), j = g_slist_next (j)) {
		PyObject *key = PyString_FromString (j->data);
		PyDict_SetItem (motion->bones, key, i->data);
	}

	g_slist_foreach (bones, (GFunc) g_free, NULL);
	g_slist_free (bones);
	g_slist_free (dofs);
	g_slist_free (data);

	g_io_channel_shutdown (file, FALSE, NULL);
	g_io_channel_unref (file);

	return (PyObject *) motion;
}
Exemple #9
0
static PyObject *
_cracklib_FascistCheck(PyObject *self, PyObject *args, PyObject *kwargs)
{
    char *candidate, *dict;
    char *defaultdict = NULL;
    const char *result;
    struct stat st;
    char *keywords[] = {"pw", "dictpath", NULL};
    char *dictfile;

    self = NULL;
    candidate = NULL;
    dict = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|s", keywords,
                                     &candidate, &dict))
    {
        PyErr_SetString(PyExc_ValueError, "error parsing arguments");
        return NULL;
    }

    if (candidate == NULL)
    {
        PyErr_SetString(PyExc_ValueError, "first argument was not a string!");
        return NULL;
    }
    if (dict != NULL)
    {
        if (dict[0] != '/')
        {
            PyErr_SetString(PyExc_ValueError,
                            "second argument was not an absolute path!");
            return NULL;
        }
        dictfile = malloc(strlen(dict) + sizeof(DICT_SUFFIX));
        if (dictfile == NULL)
        {
            PyErr_SetFromErrnoWithFilename(PyExc_OSError, dict);
            return NULL;
        }
        sprintf(dictfile, "%s" DICT_SUFFIX, dict);
        if (lstat(dictfile, &st) == -1)
        {
            PyErr_SetFromErrnoWithFilename(PyExc_OSError, dictfile);
            free(dictfile);
            return NULL;
        }
        free(dictfile);
    } else
    {
        defaultdict = strdup(GetDefaultCracklibDict());
        if (errno == ENOMEM) {
            PyErr_SetFromErrno(PyExc_OSError);
            return NULL;
        }
        dictfile = malloc(strlen(defaultdict) + sizeof(DICT_SUFFIX));
        if (dictfile == NULL)
        {
            PyErr_SetFromErrnoWithFilename(PyExc_OSError, defaultdict);
            free(defaultdict);
            return NULL;
        }
        sprintf(dictfile, "%s" DICT_SUFFIX, defaultdict);
        if (lstat(dictfile, &st) == -1)
        {
            PyErr_SetFromErrnoWithFilename(PyExc_OSError, dictfile);
            free(defaultdict);
            free(dictfile);
            return NULL;
        }
        free(dictfile);
    }

	setlocale(LC_ALL, "");
#ifdef ENABLE_NLS
	textdomain("cracklib");
#endif

    LOCK();
    result = FascistCheck(candidate, dict ? dict : defaultdict);
    UNLOCK();

    if (defaultdict != NULL)
    {
        free(defaultdict);
    }

    if (result != NULL)
    {
    	PyErr_SetString(PyExc_ValueError, result);
        return NULL;
    }
    return Py_BuildValue("s", candidate);
}
/* Function of no arguments returning new Data object */
static PyObject *
open_file(PyObject *self, PyObject *args)
{
	char *filename;
	int fd;
	DataObject *data_obj;
	unsigned char file_hdr[2], jpeg_hdr[2] = {0xff,0xd8};

	if (!PyArg_ParseTuple(args, "s:new", &filename))
		return NULL;

	/* check if the file exists first.  We close this fd just
	 * because, but maybe in the future there is a case for
	 * keeping it around. */
	fd = open(filename, O_RDONLY);
	if (fd < 0)
		return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);

	/* read the first 2 bytes, and check it looks like a jpeg */
	if (read(fd, file_hdr, 2) < 2)	{
		close(fd);
		return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
	}
	if (memcmp(jpeg_hdr, file_hdr, 2) != 0)	{
		close(fd);
		PyErr_SetString(PyExc_ValueError,
				"This file does not appear to be a JPEG file\n");
		return NULL;
	}
	close(fd);

	data_obj = newDataObject(args);
	if (data_obj == NULL)
		return PyErr_NoMemory();

	/* save the filename for later */
	data_obj->filename = PyString_FromString(filename);
	if (!data_obj->filename) {
		Py_DECREF(data_obj);
		return PyErr_NoMemory();
	}

	/* firstly, try and get the existing data */
	data_obj->d = iptc_data_new_from_jpeg(filename);
	if (data_obj->d) {
		/* read the existing iptc data into the dataset objects */
		int i;
		for (i=0; i < data_obj->d->count; i++) {
			IptcDataSet *e = data_obj->d->datasets[i];
			DataSetObject *ds = newDataSetObject(e);
			/* XXX bail out? */

			/* dataset objects hold a reference to their
			 * parent dataobject */
			ds->parent = data_obj;
			Py_INCREF(data_obj);

			ds->state = VALID;

			PyList_Append(data_obj->DataSet_list, (PyObject *)ds);
		}
	} else {
		/* create a new, empty data object */
		data_obj->d = iptc_data_new();
		if (!data_obj->d)
			return PyErr_NoMemory();
	}

	data_obj->state = OPEN;

	return (PyObject*)data_obj;
}
Exemple #11
0
int
Command_build(twopence_Command *self, twopence_command_t *cmd)
{
	twopence_buf_t *buffer = NULL;

	twopence_command_init(cmd, self->command);

	cmd->user = self->user;
	cmd->timeout = self->timeout;
	cmd->request_tty = self->useTty;
	cmd->background = self->background;

	twopence_command_ostreams_reset(cmd);
	if (self->quiet || self->stdout == Py_None) {
		/* ostream has already been reset above */
	} else {
		/* Copy remote stdout to our stdout */
		twopence_command_iostream_redirect(cmd, TWOPENCE_STDOUT, 1, false);
	}

	if (!Command_redirect_iostream(cmd, TWOPENCE_STDOUT, self->stdout, &buffer))
		return -1;

	if (self->quiet || self->stderr == Py_None) {
		/* ostream has already been reset above */
	} else {
		/* Copy remote stderr to our stderr */
		twopence_command_iostream_redirect(cmd, TWOPENCE_STDERR, 2, false);
	}

	/* If cmd.stdout and cmd.stderr are both NULL, or both refer to the same
	 * bytearray object, send the remote stdout and stderr to a shared buffer */
	if (buffer && self->stderr == self->stdout) {
		twopence_command_ostream_capture(cmd, TWOPENCE_STDERR, buffer);
	} else
	if (!Command_redirect_iostream(cmd, TWOPENCE_STDERR, self->stderr, NULL)) {
		return -1;
	}

	if (self->stdinPath != NULL) {
		int fd = open(self->stdinPath, O_RDONLY);

		if (fd < 0) {
			PyErr_SetFromErrnoWithFilename(PyExc_IOError, self->stdinPath);
			return -1;
		}
		twopence_command_iostream_redirect(cmd, TWOPENCE_STDIN, fd, true);
	} else
	if (self->stdin) {
		if (!Command_redirect_iostream(cmd, TWOPENCE_STDIN, self->stdin, NULL))
			return -1;
	} else
	if (!self->background) {
		/* Eric wants us to pipe stdin into the command by default */
		FILE *fp;
		int fd;

		fp = PySys_GetFile("stdin", NULL);
		if (fp != NULL) {
			if ((fd = fileno(fp)) < 0) {
				PyErr_SetString(PyExc_SystemError, "cannot connect command to stdin (not a regular file)");
				return -1;
			}
			/* We dup() the file descriptor so that we no longer have to worry
			 * about what python does with its File object */
			twopence_command_iostream_redirect(cmd, TWOPENCE_STDIN, dup(fd), true);
		}
	}

	/* Copy all environment variables */
	if (self->environ.count)
		twopence_env_copy(&cmd->env, &self->environ);

	return 0;
}
psi_mountlist_t *
psi_arch_mountlist(const int remote)
{
    FILE *mntent;
    struct mntent mnt;
    char buf[PATH_MAX * 3];     /* size used in autofs so I hope it's okay */
    psi_mountlist_t *ml = NULL;
    psi_mountinfo_t *mounti, **mounts;

    /* Open /etc/mtab */
    mntent = setmntent(_PATH_MOUNTED, "r");
    if (mntent == NULL)
        return (psi_mountlist_t *) PyErr_SetFromErrnoWithFilename(
            PyExc_OSError, _PATH_MOUNTED);

    /* Create our (empty) mountlist */
    ml = (psi_mountlist_t *)psi_calloc(sizeof(psi_mountlist_t));
    if (ml == NULL) {
        fclose(mntent);
        return NULL;
    }

    /* Step through each line in the mount file */
    while (getmntent_r(mntent, &mnt, buf, sizeof(buf)) != NULL) {

        /* Skip remote filesystems if not asked for them */
        if (!remote &&
            (strchr(mnt.mnt_fsname, ':') != NULL ||
             strncmp(mnt.mnt_fsname, "//", 2) == 0))
            continue;

        /* Allocate space for the mount information */
        if ((mounti = psi_calloc(sizeof(psi_mountinfo_t))) == NULL) {
            fclose(mntent);
            psi_free_mountlist(ml);
            return NULL;
        }
        
        /* And then allocate more space for the mount list */
        mounts = (psi_mountinfo_t **)psi_realloc(
            ml->mounts,
            (ml->count + 1) * sizeof(psi_mountinfo_t *));
        if (mounts == NULL) {
            fclose(mntent);
            psi_free_mountinfo(mounti);
            psi_free_mountlist(ml);
            return NULL;
        }
        ml->mounts = mounts;
        ml->mounts[ml->count] = mounti;
        ml->count += 1;

        /* Finally add the information to mounti */
        if (set_mntent(mounti, &mnt) < 0) {
            fclose(mntent);
            psi_free_mountlist(ml);
            return NULL;
        }
        if (posix_set_vfs(mounti) < 0) {
            fclose(mntent);
            psi_free_mountlist(ml);
            return NULL;
        }
    }
    if (!feof(mntent)) {        /* Uh oh, we had a read error */
        endmntent(mntent);
        psi_free_mountlist(ml);
        PyErr_Format(PyExc_OSError, "Read error in %s", _PATH_MOUNTED);
        return NULL;
    }
    endmntent(mntent);
    return ml;
}
Exemple #13
0
static PyObject * _psp_module_parse(PyObject *self, PyObject *argv)
{
    PyObject *code;
    char     *filename;
    char     *dir = NULL;
    char     *path;
    psp_parser_t  *parser;
    yyscan_t scanner;
    FILE *f;

    if (!PyArg_ParseTuple(argv, "s|s", &filename, &dir)) {
        return NULL;
    }

    if (dir) {
        path = malloc(strlen(filename)+strlen(dir)+1);
        if (!path)
            return PyErr_NoMemory();
        strcpy(path, dir);
        strcat(path, filename);
    }
    else {
        path = filename;
    }

    Py_BEGIN_ALLOW_THREADS
    f = fopen(path, "rb");
    Py_END_ALLOW_THREADS

    if (f == NULL) {
        PyErr_SetFromErrnoWithFilename(PyExc_IOError, path);
        if (dir) free(path);
        return NULL;
    }
    if (dir) free(path);

    parser = psp_parser_init();
    if (dir)
        parser->dir = dir;

    yylex_init(&scanner);
    yyset_in(f, scanner);
    yyset_extra(parser, scanner);
    yylex(scanner);
    yylex_destroy(scanner);

    fclose(f);
    psp_string_0(&parser->pycode);

    if (PyErr_Occurred()) {
        psp_parser_cleanup(parser);
        return NULL;
    }

    if (parser->pycode.blob) {
        code = MpBytesOrUnicode_FromString(parser->pycode.blob);
    }
    else {
        code = MpBytesOrUnicode_FromString("");
    }

    psp_parser_cleanup(parser);

    return code;
}
Exemple #14
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;
}
Exemple #15
0
PyObject*
encoders_encode_shn(PyObject *dummy,
                    PyObject *args, PyObject *keywds)
{
    static char *kwlist[] = {"filename",
                             "pcmreader",
                             "is_big_endian",
                             "signed_samples",
                             "header_data",
                             "footer_data",
                             "block_size",
                             NULL};
    char *filename;
    FILE *output_file;
    BitstreamWriter* writer;
    pcmreader* pcmreader;
    int is_big_endian = 0;
    int signed_samples = 0;
    char* header_data;
#ifdef PY_SSIZE_T_CLEAN
    Py_ssize_t header_size;
#else
    int header_size;
#endif
    char* footer_data = NULL;
#ifdef PY_SSIZE_T_CLEAN
    Py_ssize_t footer_size = 0;
#else
    int footer_size = 0;
#endif
    unsigned block_size = 256;
    unsigned bytes_written = 0;
    unsigned i;

    /*fetch arguments*/
    if (!PyArg_ParseTupleAndKeywords(args, keywds, "sO&iis#|s#I",
                                     kwlist,
                                     &filename,
                                     pcmreader_converter,
                                     &pcmreader,
                                     &is_big_endian,
                                     &signed_samples,
                                     &header_data,
                                     &header_size,

                                     &footer_data,
                                     &footer_size,
                                     &block_size))
        return NULL;

    /*ensure PCMReader is compatible with Shorten*/
    if ((pcmreader->bits_per_sample != 8) &&
        (pcmreader->bits_per_sample != 16)) {
        pcmreader->del(pcmreader);
        PyErr_SetString(PyExc_ValueError, "unsupported bits per sample");
        return NULL;
    }

    /*open given filename for writing*/
    if ((output_file = fopen(filename, "wb")) == NULL) {
        PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
        pcmreader->del(pcmreader);
        return NULL;
    } else {
        writer = bw_open(output_file, BS_BIG_ENDIAN);
    }

    /*write magic number and version*/
    writer->build(writer, "4b 8u", "ajkg", 2);

    bw_add_callback(writer, byte_counter, &bytes_written);

    /*write Shorten header*/
    write_header(writer,
                 pcmreader->bits_per_sample,
                 is_big_endian,
                 signed_samples,
                 pcmreader->channels,
                 block_size);

    /*issue initial VERBATIM command with header data*/
    write_unsigned(writer, COMMAND_SIZE, FN_VERBATIM);
    write_unsigned(writer, VERBATIM_SIZE, header_size);
    for (i = 0; i < header_size; i++)
        write_unsigned(writer, VERBATIM_BYTE_SIZE, (uint8_t)header_data[i]);

    /*process PCM frames*/
    if (encode_audio(writer, pcmreader, signed_samples, block_size))
        goto error;

    /*if there's footer data, issue a VERBATIM command for it*/
    if ((footer_data != NULL) && (footer_size > 0)) {
        write_unsigned(writer, COMMAND_SIZE, FN_VERBATIM);
        write_unsigned(writer, VERBATIM_SIZE, footer_size);
        for (i = 0; i < footer_size; i++)
            write_unsigned(writer, VERBATIM_BYTE_SIZE, (uint8_t)footer_data[i]);
    }

    /*issue QUIT command*/
    write_unsigned(writer, COMMAND_SIZE, FN_QUIT);

    /*pad output (not including header) to a multiple of 4 bytes*/
    writer->byte_align(writer);
    while ((bytes_written % 4) != 0) {
        writer->write(writer, 8, 0);
    }

    /*deallocate temporary buffers and close files*/
    pcmreader->del(pcmreader);
    writer->close(writer);

    Py_INCREF(Py_None);
    return Py_None;
 error:
    pcmreader->del(pcmreader);
    writer->close(writer);

    return NULL;
}
Exemple #16
0
static PyObject* bignumpy(PyObject* self, PyObject* args) {
  const char* filename = NULL;
  PyObject* dtype = NULL;
  PyObject* shape = Py_None;
  int fd;
  PyArrayObject* z;
  PyArray_Descr* descr;
  int nd = 0;
  npy_intp dims[BIGNUMPY_MAXDIMS];
  npy_intp strides[BIGNUMPY_MAXDIMS];
  size_t nelm;
  int i;
  npy_intp stride;
  PyObject* obj;
  struct BignumpyObject* bno;

  if (!PyArg_ParseTuple(args,"sO|O",&filename,&dtype,&shape)) return NULL;

  // We actually start with the type.  If we can't figure out the size
  // it is useless to open the file.  dtype can be almost anything, so
  // here, we create an array of zeros to get information about the
  // type using the actual numpy interface
  z = /*owned*/ (PyArrayObject*)PyObject_CallFunctionObjArgs(ZEROS,EMPTY,dtype,NULL);
  if (!z) return NULL;
  Py_INCREF(descr = PyArray_DESCR(z));
  Py_DECREF(z); z = NULL;

  // OK, we can open the file.  If it does not exist, we may have to create it
  fd = open(filename,O_RDWR|O_CREAT,0666);
  if (fd < 0) {
    Py_DECREF(descr);
    return PyErr_SetFromErrnoWithFilename(PyExc_OSError,filename);
  }


  // Figure out the current size of the file.
  struct stat status;
  if (fstat(fd,&status) < 0) {
    Py_DECREF(descr);
    close(fd);
    return PyErr_SetFromErrnoWithFilename(PyExc_OSError,filename);
  }

  //If the size is zero and we have a shape,
  // then we'll use ftruncate to change the size.  If we have no shape,
  // assume shape is (size(file)/elsize,)
  if (shape == Py_None) {
    strides[nd] = descr->elsize;
    dims[nd++] = status.st_size/descr->elsize;
  } else {
    PyObject* iterator = PyObject_GetIter(shape);
    if (!iterator) {
      long v = PyInt_AsLong(shape);
      if (v == -1 && PyErr_Occurred()) {
	PyErr_SetString(PyExc_RuntimeError,"invalid shape");
	Py_DECREF(descr);
	close(fd);
	return NULL;
      }
      dims[nd++] = v;
    } else {
      PyObject* item;
      while((item = PyIter_Next(iterator))) {
	if (nd >= BIGNUMPY_MAXDIMS) {
	  Py_DECREF(iterator);
	  Py_DECREF(item);
	  Py_DECREF(descr);
	  close(fd);
	  PyErr_SetString(PyExc_RuntimeError,"shape has too many dimensions");
	  return NULL;
	}
	long v = PyInt_AsLong(item);
	if (v == -1 && PyErr_Occurred()) {
	  Py_DECREF(iterator);
	  Py_DECREF(item);
	  Py_DECREF(descr);
	  close(fd);
	  PyErr_SetString(PyExc_RuntimeError,"invalid shape");
	  return NULL;
	}
	strides[nd] = 1;
	dims[nd++] = v;
	Py_DECREF(item);
      }
      Py_DECREF(iterator);
    }
  }

  // ----------------------------------------------------------------------
  // Compute the number of required elements
  // ----------------------------------------------------------------------
  nelm = 0;
  if (nd > 0) {
    nelm = 1;
    for(i=0;i<nd;++i) nelm *= dims[i];
  }

  // ---------------------------------------------------------------------- 
  // The strides include the element size.  We compute from back to front
  // ----------------------------------------------------------------------
  stride = descr->elsize;
  for(i=0;i<nd;++i) {
    strides[nd-1-i] = stride;
    stride *= dims[nd-1-i];
  }

  // ----------------------------------------------------------------------
  // Grow (but do not shrink) to be the expected size
  // ----------------------------------------------------------------------
  off_t expected = nelm * descr->elsize;
  if (status.st_size < expected) {
    if (ftruncate(fd,expected) < 0) {
      Py_DECREF(descr);
      close(fd);
      return PyErr_SetFromErrnoWithFilename(PyExc_OSError,filename);
    }
  }

  // ----------------------------------------------------------------------
  // At this point, we can map the values into memory
  // ----------------------------------------------------------------------
  if (!expected) expected = 1; // mmap doesn't like 0 size
  void* m = mmap(NULL,expected,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
  if (m == MAP_FAILED) {
    Py_DECREF(descr);
    close(fd);
    return PyErr_SetFromErrnoWithFilename(PyExc_OSError,filename);
  }

  // ----------------------------------------------------------------------
  // Make a C object to hold the map state (pointer and size);
  // ----------------------------------------------------------------------

  obj = PyArray_NewFromDescr(
			      &Bignumpy_Type,
			      descr, /* steals reference */
			      nd,
			      dims,
			      strides,
			      m,
			      NPY_ARRAY_DEFAULT,
			      NULL);
  bno = (struct BignumpyObject*)obj;

  bno->fd = fd;
  bno->map = m;
  bno->size = expected;
  return obj;
}
Exemple #17
0
static lad_t *
newladobject(PyObject *arg)
{
    lad_t *xp;
    int fd, afmts, imode;
    char *basedev = NULL;
    char *mode = NULL;

    /* Two ways to call linuxaudiodev.open():
         open(device, mode) (for consistency with builtin open())
         open(mode)         (for backwards compatibility)
       because the *first* argument is optional, parsing args is
       a wee bit tricky. */
    if (!PyArg_ParseTuple(arg, "s|s:open", &basedev, &mode))
        return NULL;
    if (mode == NULL) {                 /* only one arg supplied */
        mode = basedev;
        basedev = NULL;
    }

    if (strcmp(mode, "r") == 0)
        imode = O_RDONLY;
    else if (strcmp(mode, "w") == 0)
        imode = O_WRONLY;
    else {
        PyErr_SetString(LinuxAudioError, "mode should be 'r' or 'w'");
        return NULL;
    }

    /* Open the correct device.  The base device name comes from the
     * AUDIODEV environment variable first, then /dev/dsp.  The
     * control device tacks "ctl" onto the base device name.
     *
     * Note that the only difference between /dev/audio and /dev/dsp
     * is that the former uses logarithmic mu-law encoding and the
     * latter uses 8-bit unsigned encoding.
     */

    if (basedev == NULL) {              /* called with one arg */
        basedev = getenv("AUDIODEV");
        if (basedev == NULL)             /* $AUDIODEV not set */
            basedev = "/dev/dsp";
    }

    if ((fd = open(basedev, imode)) == -1) {
        PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
        return NULL;
    }
    if (imode == O_WRONLY && ioctl(fd, SNDCTL_DSP_NONBLOCK, NULL) == -1) {
        PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
        return NULL;
    }
    if (ioctl(fd, SNDCTL_DSP_GETFMTS, &afmts) == -1) {
        PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
        return NULL;
    }
    /* Create and initialize the object */
    if ((xp = PyObject_New(lad_t, &Ladtype)) == NULL) {
        close(fd);
        return NULL;
    }
    xp->x_fd = fd;
    xp->x_mode = imode;
    xp->x_icount = xp->x_ocount = 0;
    xp->x_afmts  = afmts;
    return xp;
}
Exemple #18
0
static PyObject *
AMC_save (AMC *self, PyObject *args)
{
	char *filename;
	GIOChannel *file;
	int size, frames, i, j, k;
	PyObject *keys;

	// get filename
	if (!PyArg_ParseTuple (args, "s;expected 'string'", &filename))
		return NULL;

	file = g_io_channel_new_file (filename, "w", NULL);
	if (file == NULL) {
		// FIXME - we should be using the GError, not errno
		return PyErr_SetFromErrnoWithFilename (PyExc_IOError, filename);
	}

	// write out comment
	size = PyList_Size (self->comments);
	for (i = 0; i < size; i++) {
		PyObject *line;
		char *cline;

		line = PyList_GetItem (self->comments, i);
		cline = PyString_AsString (line);

		g_io_channel_write_chars (file, cline, strlen (cline), NULL, NULL);
		g_io_channel_write_chars (file, "\n", 1, NULL, NULL);
	}

	// write out format
	size = PyList_Size (self->format);
	if (size == 0)
		g_io_channel_write_chars (file, ":FULLY-SPECIFIED\n:DEGREES\n", strlen (":FULLY-SPECIFIED\n:DEGREES\n"), NULL, NULL);
	for (i = 0; i < size; i++) {
		PyObject *line;
		char *cline;

		line = PyList_GetItem (self->format, i);
		cline = PyString_AsString (line);

		g_io_channel_write_chars (file, cline, strlen (cline), NULL, NULL);
		g_io_channel_write_chars (file, "\n", 1, NULL, NULL);
	}

	// get keys
	keys = PyDict_Keys (self->bones);
	size = PyList_Size (keys);
	if (size == 0)
		// FIXME - throw error
		return Py_False;

	// find # of frames
	{
		PyObject *bone = PyDict_GetItem (self->bones, PyList_GetItem (keys, 0));
		PyArrayObject *array = (PyArrayObject *) bone;
		frames = array->dimensions[0];
	}

	for (j = 0; j < frames; j++) {
		GIOStatus status;
		char *frame;

		// Write out the frame number
		frame = g_strdup_printf ("%d\n", j + 1);
		g_io_channel_write_chars (file, frame, strlen (frame), NULL, NULL);
		g_free (frame);

		for (i = 0; i < size; i++) {
			PyObject *key;
			char *bone_name;
			PyArrayObject *bone;

			// Write the bone name
			key = PyList_GetItem (keys, i);
			bone = (PyArrayObject *) PyDict_GetItem (self->bones, key);
			bone_name = PyString_AsString (key);
			g_io_channel_write_chars (file, bone_name, strlen (bone_name), NULL, NULL);

			// Write out the bone data
			for (k = 0; k < bone->dimensions[1]; k++) {
				char *data = g_strdup_printf (" %f", *((float*) (bone->data + (j * bone->strides[0]) + (k * bone->strides[1]))));
				g_io_channel_write_chars (file, data, strlen (data), NULL, NULL);
				g_free (data);
			}
			 g_io_channel_write_chars (file, "\n", 1, NULL, NULL);
		}
	}

	g_io_channel_shutdown (file, TRUE, NULL);
	g_io_channel_unref (file);

	Py_RETURN_TRUE;
}
Exemple #19
0
static PyObject *
posix_error_with_allocated_filename(char* name) {
	PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);
	PyMem_Free(name);
	return rc; }
Exemple #20
0
PyObject*
encoders_encode_opus(PyObject *dummy, PyObject *args, PyObject *keywds)
{
    char *filename;
    struct PCMReader *pcmreader = NULL;
    int quality;
    int original_sample_rate;
    static char *kwlist[] = {"filename",
                             "pcmreader",
                             "quality",
                             "original_sample_rate",
                             NULL};
    result_t result;

    if (!PyArg_ParseTupleAndKeywords(args, keywds, "sO&ii",
                                     kwlist,
                                     &filename,
                                     py_obj_to_pcmreader,
                                     &pcmreader,
                                     &quality,
                                     &original_sample_rate)) {
        if (pcmreader != NULL)
            pcmreader->del(pcmreader);
        return NULL;
    }

    /*sanity check quality*/
    if ((quality < 0) || (quality > 10)) {
        PyErr_SetString(PyExc_ValueError, "quality must be 0-10");
        pcmreader->del(pcmreader);
        return NULL;
    }

    /*sanity check original sample rate*/
    if (original_sample_rate <= 0) {
        PyErr_SetString(PyExc_ValueError, "original_sample_rate must be > 0");
        pcmreader->del(pcmreader);
        return NULL;
    }

    /*sanity check PCMReader*/
    if (pcmreader->sample_rate != 48000) {
        PyErr_SetString(PyExc_ValueError,
                        "PCMReader sample_rate must be 48000");
        pcmreader->del(pcmreader);
        return NULL;
    } else if (pcmreader->bits_per_sample != 16) {
        PyErr_SetString(PyExc_ValueError,
                        "PCMReader bits_per_sample must be 16");
        pcmreader->del(pcmreader);
        return NULL;
    }

    result = encode_opus_file(filename, pcmreader,
                              quality, original_sample_rate);

    pcmreader->del(pcmreader);

    switch (result) {
    case ENCODE_OK:
    default:
        Py_INCREF(Py_None);
        return Py_None;
    case ERR_IOERROR:
        PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
        return NULL;
    case ERR_ENCODER_INIT:
        PyErr_SetString(PyExc_ValueError, "error initializing encoder");
        return NULL;
    case ERR_PCMREADER:
        /*pass error through from PCMReader*/
        return NULL;
    case ERR_BLOCK_SIZE:
        PyErr_SetString(PyExc_ValueError,
                        "FrameList too large, please use BufferedPCMReader");
        return NULL;
    case ERR_ENCODE_ERROR:
        PyErr_SetString(PyExc_ValueError,
                        "Opus encoding error");
        return NULL;
    }
}
Exemple #21
0
//-----------------------------------------------------------------------------
// SetExecutableName()
//   Set the script to execute and calculate the directory in which the
// executable is found as well as the exclusive (only for this executable) and
// shared zip file names.
//-----------------------------------------------------------------------------
static int SetExecutableName(
    const char *fileName)               // script to execute
{
    char temp[MAXPATHLEN + 12], *ptr;
    const char *tempStr = NULL;
    PyObject *encodedObj;
#ifndef MS_WINDOWS
    char linkData[MAXPATHLEN + 1];
    struct stat statData;
    size_t linkSize, i;
    PyObject *dirName;
#endif

    // store file name
    g_FileName = cxString_FromString(fileName);
    if (!g_FileName)
        return FatalError("cannot create string for file name");

#ifndef MS_WINDOWS
    for (i = 0; i < 25; i++) {
        if (cxString_ToString(g_FileName, &encodedObj, &fileName) < 0)
            return -1;
        if (lstat(fileName, &statData) < 0) {
            PyErr_SetFromErrnoWithFilename(PyExc_OSError, (char*) fileName);
            return FatalError("unable to stat file");
        }
        if (!S_ISLNK(statData.st_mode))
            break;
        linkSize = readlink(fileName, linkData, sizeof(linkData));
        if (linkSize < 0) {
            PyErr_SetFromErrnoWithFilename(PyExc_OSError, (char*) fileName);
            return FatalError("unable to stat file");
        }
        Py_DECREF(encodedObj);
        if (linkData[0] == '/') {
            Py_DECREF(g_FileName);
            g_FileName = cxString_FromStringAndSize(linkData, linkSize);
        } else {
            if (cxString_ToString(g_FileName, &encodedObj, &fileName) < 0)
                return -1;
            if (GetDirName(fileName, &dirName) < 0) {
                Py_DECREF(encodedObj);
                return -1;
            }
            Py_DECREF(encodedObj);
            if (cxString_ToString(dirName, &encodedObj, &tempStr) < 0)
                return -1;
            if (strlen(tempStr) + linkSize + 1 > MAXPATHLEN) {
                Py_DECREF(dirName);
                Py_DECREF(encodedObj);
                return FatalError("cannot dereference link, path too large");
            }
            strcpy(temp, tempStr);
            Py_DECREF(encodedObj);
            strcat(temp, "/");
            strncat(temp, linkData, linkSize);
            Py_DECREF(g_FileName);
            g_FileName = cxString_FromString(temp);
        }
        if (!g_FileName)
            return FatalError("cannot create string for linked file name");
    }
#endif

    // calculate and store directory name
    if (GetDirName(fileName, &g_DirName) < 0)
        return -1;

    // calculate and store exclusive zip file name
    strcpy(temp, fileName);
    ptr = temp + strlen(temp) - 1;
    while (ptr > temp && *ptr != SEP && *ptr != '.')
        ptr--;
    if (*ptr == '.')
        *ptr = '\0';
    strcat(temp, ".zip");
    g_ExclusiveZipFileName = cxString_FromString(temp);
    if (!g_ExclusiveZipFileName)
        return FatalError("cannot create string for exclusive zip file name");

    // calculate and store shared zip file name
    if (cxString_ToString(g_DirName, &encodedObj, &tempStr) < 0)
        return -1;
    strcpy(temp, tempStr);
    Py_DECREF(encodedObj);
    ptr = temp + strlen(temp);
    *ptr++ = SEP;
    strcpy(ptr, "library.zip");
    g_SharedZipFileName = cxString_FromString(temp);
    if (!g_SharedZipFileName)
        return FatalError("cannot create string for shared zip file name");

    return 0;
}
/*
 * Return TCP and UDP connections opened by process.
 * UNIX sockets are excluded.
 *
 * Thanks to:
 * https://github.com/DavidGriffith/finx/blob/master/
 *     nxsensor-3.5.0-1/src/sysdeps/solaris.c
 * ...and:
 * https://hg.java.net/hg/solaris~on-src/file/tip/usr/src/cmd/
 *     cmd-inet/usr.bin/netstat/netstat.c
 */
static PyObject *
psutil_net_connections(PyObject *self, PyObject *args)
{
    long pid;
    int sd = NULL;
    mib2_tcpConnEntry_t *tp = NULL;
    mib2_udpEntry_t     *ude;
#if defined(AF_INET6)
    mib2_tcp6ConnEntry_t *tp6;
    mib2_udp6Entry_t     *ude6;
#endif
    char buf[512];
    int i, flags, getcode, num_ent, state;
    char lip[200], rip[200];
    int lport, rport;
    int processed_pid;
    struct strbuf ctlbuf, databuf;
    struct T_optmgmt_req *tor = (struct T_optmgmt_req *)buf;
    struct T_optmgmt_ack *toa = (struct T_optmgmt_ack *)buf;
    struct T_error_ack   *tea = (struct T_error_ack *)buf;
    struct opthdr        *mibhdr;

    PyObject *py_retlist = PyList_New(0);
    PyObject *py_tuple = NULL;
    PyObject *py_laddr = NULL;
    PyObject *py_raddr = NULL;
    PyObject *af_filter = NULL;
    PyObject *type_filter = NULL;

    if (py_retlist == NULL)
        return NULL;
    if (! PyArg_ParseTuple(args, "lOO", &pid, &af_filter, &type_filter))
        goto error;
    if (!PySequence_Check(af_filter) || !PySequence_Check(type_filter)) {
        PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence");
        goto error;
    }

    sd = open("/dev/arp", O_RDWR);
    if (sd == -1) {
        PyErr_SetFromErrnoWithFilename(PyExc_OSError, "/dev/arp");
        goto error;
    }

    /*
    XXX - These 2 are used in ifconfig.c but they seem unnecessary
    ret = ioctl(sd, I_PUSH, "tcp");
    if (ret == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }
    ret = ioctl(sd, I_PUSH, "udp");
    if (ret == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }
    */

    // OK, this mess is basically copied and pasted from nxsensor project
    // which copied and pasted it from netstat source code, mibget()
    // function.  Also see:
    // http://stackoverflow.com/questions/8723598/
    tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
    tor->OPT_offset = sizeof (struct T_optmgmt_req);
    tor->OPT_length = sizeof (struct opthdr);
    tor->MGMT_flags = T_CURRENT;
    mibhdr = (struct opthdr *)&tor[1];
    mibhdr->level = EXPER_IP_AND_ALL_IRES;
    mibhdr->name  = 0;
    mibhdr->len   = 0;

    ctlbuf.buf = buf;
    ctlbuf.len = tor->OPT_offset + tor->OPT_length;
    flags = 0;  // request to be sent in non-priority

    if (putmsg(sd, &ctlbuf, (struct strbuf *)0, flags) == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }

    mibhdr = (struct opthdr *)&toa[1];
    ctlbuf.maxlen = sizeof (buf);

    for (;;) {
        flags = 0;
        getcode = getmsg(sd, &ctlbuf, (struct strbuf *)0, &flags);

        if (getcode != MOREDATA ||
                ctlbuf.len < sizeof (struct T_optmgmt_ack) ||
                toa->PRIM_type != T_OPTMGMT_ACK ||
                toa->MGMT_flags != T_SUCCESS)
        {
            break;
        }
        if (ctlbuf.len >= sizeof (struct T_error_ack) &&
                tea->PRIM_type == T_ERROR_ACK)
        {
            PyErr_SetString(PyExc_RuntimeError, "ERROR_ACK");
            goto error;
        }
        if (getcode == 0 &&
                ctlbuf.len >= sizeof (struct T_optmgmt_ack) &&
                toa->PRIM_type == T_OPTMGMT_ACK &&
                toa->MGMT_flags == T_SUCCESS)
        {
            PyErr_SetString(PyExc_RuntimeError, "ERROR_T_OPTMGMT_ACK");
            goto error;
        }

        databuf.maxlen = mibhdr->len;
        databuf.len = 0;
        databuf.buf = (char *)malloc((int)mibhdr->len);
        if (!databuf.buf) {
            PyErr_NoMemory();
            goto error;
        }

        flags = 0;
        getcode = getmsg(sd, (struct strbuf *)0, &databuf, &flags);
        if (getcode < 0) {
            PyErr_SetFromErrno(PyExc_OSError);
            goto error;
        }

        // TCPv4
        if (mibhdr->level == MIB2_TCP && mibhdr->name == MIB2_TCP_13) {
            tp = (mib2_tcpConnEntry_t *)databuf.buf;
            num_ent = mibhdr->len / sizeof(mib2_tcpConnEntry_t);
            for (i = 0; i < num_ent; i++, tp++) {
                processed_pid = tp->tcpConnCreationProcess;
                if (pid != -1 && processed_pid != pid)
                    continue;
                // construct local/remote addresses
                inet_ntop(AF_INET, &tp->tcpConnLocalAddress, lip, sizeof(lip));
                inet_ntop(AF_INET, &tp->tcpConnRemAddress, rip, sizeof(rip));
                lport = tp->tcpConnLocalPort;
                rport = tp->tcpConnRemPort;

                // contruct python tuple/list
                py_laddr = Py_BuildValue("(si)", lip, lport);
                if (!py_laddr)
                    goto error;
                if (rport != 0) {
                    py_raddr = Py_BuildValue("(si)", rip, rport);
                }
                else {
                    py_raddr = Py_BuildValue("()");
                }
                if (!py_raddr)
                    goto error;
                state = tp->tcpConnEntryInfo.ce_state;

                // add item
                py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_STREAM,
                                         py_laddr, py_raddr, state,
                                         processed_pid);
                if (!py_tuple) {
                    goto error;
                }
                if (PyList_Append(py_retlist, py_tuple))
                    goto error;
                Py_DECREF(py_tuple);
            }
        }
#if defined(AF_INET6)
        // TCPv6
        else if (mibhdr->level == MIB2_TCP6 && mibhdr->name == MIB2_TCP6_CONN)
        {
            tp6 = (mib2_tcp6ConnEntry_t *)databuf.buf;
            num_ent = mibhdr->len / sizeof(mib2_tcp6ConnEntry_t);

            for (i = 0; i < num_ent; i++, tp6++) {
                processed_pid = tp6->tcp6ConnCreationProcess;
                if (pid != -1 && processed_pid != pid)
                    continue;
                // construct local/remote addresses
                inet_ntop(AF_INET6, &tp6->tcp6ConnLocalAddress, lip, sizeof(lip));
                inet_ntop(AF_INET6, &tp6->tcp6ConnRemAddress, rip, sizeof(rip));
                lport = tp6->tcp6ConnLocalPort;
                rport = tp6->tcp6ConnRemPort;

                // contruct python tuple/list
                py_laddr = Py_BuildValue("(si)", lip, lport);
                if (!py_laddr)
                    goto error;
                if (rport != 0) {
                    py_raddr = Py_BuildValue("(si)", rip, rport);
                }
                else {
                    py_raddr = Py_BuildValue("()");
                }
                if (!py_raddr)
                    goto error;
                state = tp6->tcp6ConnEntryInfo.ce_state;

                // add item
                py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_STREAM,
                                         py_laddr, py_raddr, state, processed_pid);
                if (!py_tuple) {
                    goto error;
                }
                if (PyList_Append(py_retlist, py_tuple))
                    goto error;
                Py_DECREF(py_tuple);
            }
        }
#endif
        // UDPv4
        else if (mibhdr->level == MIB2_UDP || mibhdr->level == MIB2_UDP_ENTRY) {
            ude = (mib2_udpEntry_t *)databuf.buf;
            num_ent = mibhdr->len / sizeof(mib2_udpEntry_t);
            for (i = 0; i < num_ent; i++, ude++) {
                processed_pid = ude->udpCreationProcess;
                if (pid != -1 && processed_pid != pid)
                    continue;
                // XXX Very ugly hack! It seems we get here only the first
                // time we bump into a UDPv4 socket.  PID is a very high
                // number (clearly impossible) and the address does not
                // belong to any valid interface.  Not sure what else
                // to do other than skipping.
                if (processed_pid > 131072)
                    continue;
                inet_ntop(AF_INET, &ude->udpLocalAddress, lip, sizeof(lip));
                lport = ude->udpLocalPort;
                py_laddr = Py_BuildValue("(si)", lip, lport);
                if (!py_laddr)
                    goto error;
                py_raddr = Py_BuildValue("()");
                if (!py_raddr)
                    goto error;
                py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_DGRAM,
                                         py_laddr, py_raddr, PSUTIL_CONN_NONE,
                                         processed_pid);
                if (!py_tuple) {
                    goto error;
                }
                if (PyList_Append(py_retlist, py_tuple))
                    goto error;
                Py_DECREF(py_tuple);
            }
        }
#if defined(AF_INET6)
        // UDPv6
        else if (mibhdr->level == MIB2_UDP6 || mibhdr->level == MIB2_UDP6_ENTRY) {
            ude6 = (mib2_udp6Entry_t *)databuf.buf;
            num_ent = mibhdr->len / sizeof(mib2_udp6Entry_t);
            for (i = 0; i < num_ent; i++, ude6++) {
                processed_pid = ude6->udp6CreationProcess;
                if (pid != -1 && processed_pid != pid)
                    continue;
                inet_ntop(AF_INET6, &ude6->udp6LocalAddress, lip, sizeof(lip));
                lport = ude6->udp6LocalPort;
                py_laddr = Py_BuildValue("(si)", lip, lport);
                if (!py_laddr)
                    goto error;
                py_raddr = Py_BuildValue("()");
                if (!py_raddr)
                    goto error;
                py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_DGRAM,
                                         py_laddr, py_raddr, PSUTIL_CONN_NONE,
                                         processed_pid);
                if (!py_tuple) {
                    goto error;
                }
                if (PyList_Append(py_retlist, py_tuple))
                    goto error;
                Py_DECREF(py_tuple);
            }
        }
#endif
        free(databuf.buf);
    }

    close(sd);
    return py_retlist;

error:
    Py_XDECREF(py_tuple);
    Py_XDECREF(py_laddr);
    Py_XDECREF(py_raddr);
    Py_DECREF(py_retlist);
    // TODO : free databuf
    if (sd != NULL)
        close(sd);
    return NULL;
}
int
VorbisDecoder_init(decoders_VorbisDecoder *self, PyObject *args, PyObject *kwds) {
    char* filename;
    ogg_status ogg_result;
    vorbis_status vorbis_result;

    self->ogg_stream = NULL;
    self->ogg_file = NULL;
    self->packet = br_substream_new(BS_LITTLE_ENDIAN);

    if (!PyArg_ParseTuple(args, "s", &filename))
        goto error;
    self->ogg_file = fopen(filename, "rb");
    if (self->ogg_file == NULL) {
        PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
        goto error;
    } else {
        self->ogg_stream = oggreader_open(self->ogg_file);
    }

    /*read identification packet*/
    if ((ogg_result = oggreader_next_packet(self->ogg_stream,
                                        self->packet)) == OGG_OK) {
        if ((vorbis_result =
             vorbis_read_identification_packet(self->packet,
                                               &(self->identification))) !=
            VORBIS_OK) {
            PyErr_SetString(vorbis_exception(vorbis_result),
                            vorbis_strerror(vorbis_result));
            goto error;
        }
    } else {
        PyErr_SetString(ogg_exception(ogg_result), ogg_strerror(ogg_result));
        goto error;
    }

    /*skip comments packet, but ensure it's positioned properly*/
    if ((ogg_result = oggreader_next_packet(self->ogg_stream,
                                        self->packet)) == OGG_OK) {
        if (vorbis_read_common_header(self->packet) != 3) {
            PyErr_SetString(PyExc_ValueError,
                            "comment not second Ogg packet");
            goto error;
        }
    } else {
        PyErr_SetString(ogg_exception(ogg_result), ogg_strerror(ogg_result));
        goto error;
    }

    /*read setup header*/
    if ((ogg_result = oggreader_next_packet(self->ogg_stream,
                                        self->packet)) == OGG_OK) {
        if ((vorbis_result = vorbis_read_setup_packet(self->packet)) !=
            VORBIS_OK) {
            PyErr_SetString(vorbis_exception(vorbis_result),
                            vorbis_strerror(vorbis_result));
            goto error;
        }
    } else {
        PyErr_SetString(ogg_exception(ogg_result), ogg_strerror(ogg_result));
        goto error;
    }

    return 0;

 error:
    return -1;
}