Пример #1
1
static void _php_finfo_get_type(INTERNAL_FUNCTION_PARAMETERS, int mode, int mimetype_emu) /* {{{ */
{
	zend_long options = 0;
	char *ret_val = NULL, *buffer = NULL;
	size_t buffer_len;
	php_fileinfo *finfo = NULL;
	zval *zfinfo, *zcontext = NULL;
	zval *what;
	char mime_directory[] = "directory";

	struct magic_set *magic = NULL;
	FILEINFO_DECLARE_INIT_OBJECT(object)

	if (mimetype_emu) {

		/* mime_content_type(..) emulation */
		if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &what) == FAILURE) {
			return;
		}

		switch (Z_TYPE_P(what)) {
			case IS_STRING:
				buffer = Z_STRVAL_P(what);
				buffer_len = Z_STRLEN_P(what);
				mode = FILEINFO_MODE_FILE;
				break;

			case IS_RESOURCE:
				mode = FILEINFO_MODE_STREAM;
				break;

			default:
				php_error_docref(NULL, E_WARNING, "Can only process string or stream arguments");
				RETURN_FALSE;
		}

		magic = magic_open(MAGIC_MIME_TYPE);
		if (magic_load(magic, NULL) == -1) {
			php_error_docref(NULL, E_WARNING, "Failed to load magic database.");
			goto common;
		}
	} else if (object) {
		if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|lr", &buffer, &buffer_len, &options, &zcontext) == FAILURE) {
			RETURN_FALSE;
		}
		FILEINFO_FROM_OBJECT(finfo, object);
		magic = finfo->magic;
	} else {
		if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs|lr", &zfinfo, &buffer, &buffer_len, &options, &zcontext) == FAILURE) {
			RETURN_FALSE;
		}
		if ((finfo = (php_fileinfo *)zend_fetch_resource(Z_RES_P(zfinfo), "file_info", le_fileinfo)) == NULL) {
			RETURN_FALSE;
		}
		magic = finfo->magic;
	}

	/* Set options for the current file/buffer. */
	if (options) {
		FINFO_SET_OPTION(magic, options)
	}

	switch (mode) {
		case FILEINFO_MODE_BUFFER:
		{
			ret_val = (char *) magic_buffer(magic, buffer, buffer_len);
			break;
		}

		case FILEINFO_MODE_STREAM:
		{
				php_stream *stream;
				zend_off_t streampos;

				php_stream_from_zval_no_verify(stream, what);
				if (!stream) {
					goto common;
				}

				streampos = php_stream_tell(stream); /* remember stream position for restoration */
				php_stream_seek(stream, 0, SEEK_SET);

				ret_val = (char *) magic_stream(magic, stream);

				php_stream_seek(stream, streampos, SEEK_SET);
				break;
		}

		case FILEINFO_MODE_FILE:
		{
			/* determine if the file is a local file or remote URL */
			const char *tmp2;
			php_stream_wrapper *wrap;
			php_stream_statbuf ssb;

			if (buffer == NULL || !*buffer) {
				php_error_docref(NULL, E_WARNING, "Empty filename or path");
				RETVAL_FALSE;
				goto clean;
			}

			wrap = php_stream_locate_url_wrapper(buffer, &tmp2, 0);

			if (wrap) {
				php_stream *stream;
				php_stream_context *context = php_stream_context_from_zval(zcontext, 0);

#ifdef PHP_WIN32
				if (php_stream_stat_path_ex(buffer, 0, &ssb, context) == SUCCESS) {
					if (ssb.sb.st_mode & S_IFDIR) {
						ret_val = mime_directory;
						goto common;
					}
				}
#endif

#if PHP_API_VERSION < 20100412
				stream = php_stream_open_wrapper_ex(buffer, "rb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, context);
#else
				stream = php_stream_open_wrapper_ex(buffer, "rb", REPORT_ERRORS, NULL, context);
#endif

				if (!stream) {
					RETVAL_FALSE;
					goto clean;
				}

				if (php_stream_stat(stream, &ssb) == SUCCESS) {
					if (ssb.sb.st_mode & S_IFDIR) {
						ret_val = mime_directory;
					} else {
						ret_val = (char *)magic_stream(magic, stream);
					}
				}

				php_stream_close(stream);
			}
			break;
		}

		default:
			php_error_docref(NULL, E_WARNING, "Can only process string or stream arguments");
	}

common:
	if (ret_val) {
		RETVAL_STRING(ret_val);
	} else {
		php_error_docref(NULL, E_WARNING, "Failed identify data %d:%s", magic_errno(magic), magic_error(magic));
		RETVAL_FALSE;
	}

clean:
	if (mimetype_emu) {
		magic_close(magic);
	}

	/* Restore options */
	if (options) {
		FINFO_SET_OPTION(magic, finfo->options)
	}
	return;
}
Пример #2
0
static VALUE
magic_library_error(VALUE klass, void *data)
{
    magic_exception_t e;
    const char *message = NULL;
    const char *empty = "(null)";

    magic_t cookie = data;
    assert(cookie != NULL && "Must be a valid pointer to `magic_t' type");

    e.magic_errno = -1;
    e.magic_error = error(E_UNKNOWN);
    e.klass = klass;

    message = magic_error(cookie);
    if (message) {
        e.magic_errno = magic_errno(cookie);
        e.magic_error = message;
    }

    assert(strncmp(e.magic_error, empty, strlen(empty)) != 0 && \
            "Empty or invalid error message");

    return magic_exception(&e);
}
Пример #3
0
/*
 * call-seq:
 *    magic.file( path ) -> string or array
 *
 * Returns
 *
 * Example:
 *
 *    magic = Magic.new   #=> #<Magic:0x007f8fdc012e58>
 *
 * Will raise <i>Magic::LibraryError</i> exception if, or
 *
 * See also: Magic#buffer and Magic#descriptor
 */
VALUE
rb_mgc_file(VALUE object, VALUE value)
{
    int rv;
    magic_arguments_t ma;
    const char *cstring = NULL;
    const char *empty = "(null)";

    Check_Type(value, T_STRING);

    CHECK_MAGIC_OPEN(object);
    MAGIC_COOKIE(ma.cookie);

    ma.flags = NUM2INT(rb_mgc_getflags(object));
    ma.data.file.path = RVAL2CSTR(value);

    cstring = (const char *)MAGIC_SYNCHRONIZED(magic_file_internal, &ma);
    if (!cstring) {
        rv = magic_version_wrapper();

        if (ma.flags & MAGIC_ERROR) {
            MAGIC_LIBRARY_ERROR(ma.cookie);
        }
        else if (rv < 515) {
            (void)magic_errno(ma.cookie);
            cstring = magic_error(ma.cookie);
        }
    }

    assert(cstring != NULL && "Must be a valid pointer to `const char' type");
    assert(strncmp(cstring, empty, strlen(empty)) != 0 && \
            "Empty or invalid result");

    return magic_return(CSTR2RVAL(cstring), &ma);
}
Пример #4
0
Spider::Spider()
    : db_name_(),
      db_server_(),
      db_user_(),
      db_password_() {
  openlog("spider", LOG_CONS | LOG_ODELAY, LOG_USER);

  mime_type_attr_ = NULL;
  pserver_manager_ = NULL;
  result_ = NULL;

  if (smbc_init(libsmbmm_guest_auth_smbc_get_data, 0) < 0) {
    DetectError();
    MSS_FATAL("smbc_init", error_);
    return;
  }

  // Create a directory to store file headers.
  if (mkdir(TMPDIR, 00744 /* rwxr--r-- */) && errno != EEXIST) {
    DetectError();
    MSS_ERROR("mkdir", error_);
    return;
  }

  // Prepare to work with libmagic
  if ((cookie_ = magic_open(MAGIC_MIME_TYPE | MAGIC_ERROR)) == NULL) {
    error_ = magic_errno(cookie_);
    MSS_ERROR("magic_open", error_);
    return;
  }
  if (magic_load(cookie_, NULL) == -1) {
    error_ = magic_errno(cookie_);
    MSS_ERROR("magic_open", error_);
    return;
  }

  // Allocate memory to the result vector.
  result_ = new(std::nothrow) std::vector<std::string>(VECTOR_SIZE);
  if (result_ == NULL) {
    error_ = ENOMEM;
    MSS_FATAL("result_", error_);
    return;
  }
  last_ = result_->begin();

  error_ = 0;
}
Пример #5
0
static PyObject* py_magic_errno(PyObject* self, PyObject* args)
{
    PyObject *pycookie;
    magic_t cookie;

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

    cookie = PyCObject_AsVoidPtr(pycookie);
    return PyInt_FromLong(magic_errno(cookie));
}
Пример #6
0
/*
 * Return the mimetype of the file given with filename.
 */
VALUE t_file(VALUE self, VALUE input)
{
	//SaveStringValue(input);
	char *result= magic_file(cookie, StringValueCStr(input));
	int errno;
	if (errno= magic_errno(cookie)) {
		rb_raise(rb_mErrno, errno);
		return Qnil;
	}
	char *error;
	if (error= magic_error(cookie)) {
		rb_raise(rb_eException, error);
		return Qnil;
	}
	return rb_str_new2(result);
}
Пример #7
0
R_API int r_magic_errno(RMagic* m) {
	return magic_errno (m);
}
Пример #8
0
char *file_type(const char *filepath, char **encoding)
{
    magic_t ms = magic_open(MAGIC_ERROR|MAGIC_MIME);
    const char *result;
    *encoding = NULL;

    if (magic_load(ms,NULL) < 0 ||
            (result = magic_file(ms, filepath)) == NULL) {
        int error = magic_errno(ms);
        if (error == 0) {
            ERROR("%s:%s", filepath, magic_error(ms));
        } else {
            ERROR("%s:%s", filepath, strerror(error));
        }
        return NULL;
    } else {
        char fileinfo[1000];
        char *filetype;

        INFO("Récupération du type");
        if (sscanf(result, "%[^;\n]", fileinfo)==1) {
            filetype = malloc(sizeof(char)*(strlen(fileinfo)+1));
            if (filetype == NULL) {
                FATAL("Erreur d'allocation mémoire : %s", strerror(errno));
                exit(100);
            }
            strcpy(filetype, fileinfo);
        } else {
            INFO("Pas de type, html par défaut");
            filetype = malloc(sizeof(char)*(strlen("text/html")+1));
            if (filetype == NULL) {
                FATAL("Erreur d'allocation mémoire : %s", strerror(errno));
                exit(100);
            }
            strcpy(filetype,"text/html");
        }
        INFO("Type : <%s>", filetype);

        INFO("Récupération de l'encodage");
        if (sscanf(result+strlen(filetype), "; charset=%s", fileinfo)==1) {
            *encoding = malloc(sizeof(char)*(strlen(fileinfo)+1));
            if (*encoding == NULL) {
                FATAL("Erreur d'allocation mémoire : %s", strerror(errno));
                exit(100);
            }
            strcpy(*encoding, fileinfo);
        } else {
            *encoding = malloc(sizeof(char));
            if (*encoding == NULL) {
                FATAL("Erreur d'allocation mémoire : %s", strerror(errno));
                exit(100);
            }
            (*encoding)[0] = '\0';
        }
        INFO("Encodage : <%s>", *encoding);

        magic_close(ms);

        return filetype;
    }
#if 0
    char *buffer;
    char *filetype;
    char tmpfn[strlen(TMPFN)+1] = TMPFN;
    char fileinfo[100];
    int tmpfd;
    FILE *f;

    INFO("Détermination du type du fichier %s", filepath);

    DEBUG("Création d'un fichier temporaire");
    if ((tmpfd = mkstemp(tmpfn)) == -1) {
        ERROR("Erreur de création du fichier temporaire : %s", strerror(errno));
        return NULL;
    }
    f = fdopen(tmpfd,"r");

    DEBUG("Allocation de la mémoire");
    buffer = malloc((strlen(FILETYPE)
                +strlen(filepath)
                +strlen(tmpfn)+1)
            *sizeof(char));
    if (buffer == NULL) {
        FATAL("Erreur d'allocation mémoire : %s", strerror(errno));
        exit(100);
    }
    sprintf(buffer, FILETYPE, filepath, tmpfn);
    INFO("Exécution de la commande : %s", buffer);
    system(buffer);

    INFO("Récupération du type");
    if (fscanf(f, "%[^;\n]", fileinfo)==1) {
        filetype = malloc(sizeof(char)*(strlen(fileinfo)+1));
        if (filetype == NULL) {
            FATAL("Erreur d'allocation mémoire : %s", strerror(errno));
            exit(100);
        }
        strcpy(filetype, fileinfo);
    } else {
        INFO("Pas de type, html par défaut");
        filetype = malloc(sizeof(char)*(strlen("text/html")+1));
        if (filetype == NULL) {
            FATAL("Erreur d'allocation mémoire : %s", strerror(errno));
            exit(100);
        }
        strcpy(filetype,"text/html");
    }
    INFO("Type : <%s>", filetype);

    INFO("Récupération de l'encodage");
    if (fscanf(f, "; charset=%s", fileinfo)==1) {
        *encoding = malloc(sizeof(char)*(strlen(fileinfo)+1));
        if (*encoding == NULL) {
            FATAL("Erreur d'allocation mémoire : %s", strerror(errno));
            exit(100);
        }
        strcpy(*encoding, fileinfo);
    } else {
        *encoding = malloc(sizeof(char));
        if (*encoding == NULL) {
            FATAL("Erreur d'allocation mémoire : %s", strerror(errno));
            exit(100);
        }
        (*encoding)[0] = '\0';
    }
    INFO("Encodage : <%s>", *encoding);

    DEBUG("Libération de la mémoire");
    free(buffer);

    DEBUG("Libération du fichier temporaire");
    close(tmpfd);
    unlink(tmpfn);

    return filetype;
#endif
}
Пример #9
0
const char *Spider::DetectMimeType(const std::string &path) {
  int smb_fd = smbc_open(path.c_str(), O_RDONLY, 0);
  if (UNLIKELY(smb_fd < 0)) {
    if (LIKELY(errno == EISDIR))
      return "inode/directory";

    DetectError();
    MSS_ERROR(("smbc_open " + path).c_str(), error_);
    return "unknown";
  }

  // Extract name of the file
  // Don't detele '/' symbol it need to form path.
  std::string name(path, path.rfind("/"));

  // Create a storage for file header in TMPDIR and open it
  int fd = open((TMPDIR + name).c_str(), O_CREAT | O_RDWR | O_EXCL,
                00744 /* rwxr--r-- */);
  if (UNLIKELY(fd == -1)) {
    if (LIKELY(errno = ENOTDIR)) {
      // TODO(yulyugin): Check if TMPDIR doesn't exists create it.
    }
    DetectError();
    MSS_ERROR("open", error_);
    if (UNLIKELY(smbc_close(smb_fd))) {
      DetectError();
      MSS_ERROR("smbc_close", error_);
    }
    return "unknown";
  }

  void *buf = malloc(HEADERSIZE);  // Buffer to store header.

  // Copy file header to TMPDIR
  if (UNLIKELY(smbc_read(smb_fd, buf, HEADERSIZE) < 0)) {
    DetectError();
    MSS_ERROR("smbc_read", error_);
    if (UNLIKELY(smbc_close(smb_fd))) {
      DetectError();
      MSS_ERROR("smbc_close", error_);
    }
    if (UNLIKELY(close(fd))) {
      DetectError();
      MSS_ERROR("close", error_);
    }
    free(buf);
    return "unknown";
  }

  if (UNLIKELY(write(fd, buf, HEADERSIZE) < 0)) {
    DetectError();
    MSS_ERROR("write", error_);
    if (UNLIKELY(smbc_close(smb_fd))) {
      DetectError();
      MSS_ERROR("smbc_close", error_);
    }
    if (UNLIKELY(close(fd))) {
      DetectError();
      MSS_ERROR("close", error_);
    }
    free(buf);
    return "unknown";
  }

  // Move to the begining of the file
  if (UNLIKELY(lseek(fd, 0, SEEK_SET) != 0)) {
    DetectError();
    MSS_ERROR("lseek", error_);
    if (UNLIKELY(smbc_close(smb_fd))) {
      DetectError();
      MSS_ERROR("smbc_close", error_);
    }
    if (UNLIKELY(close(fd))) {
      DetectError();
      MSS_ERROR("close", error_);
    }
    free(buf);
    return "unknown";
  }

  const char *mime_type = magic_descriptor(cookie_, fd);
  if (UNLIKELY(mime_type == NULL)) {
    error_ = magic_errno(cookie_);
    MSS_ERROR("magic_descriptor", error_);
    if (UNLIKELY(smbc_close(smb_fd))) {
      DetectError();
      MSS_ERROR("smbc_close", error_);
    }
    if (UNLIKELY(close(fd))) {
      DetectError();
      MSS_ERROR("close", error_);
    }
    free(buf);
    return "unknown";
  }

  if (UNLIKELY(smbc_close(smb_fd))) {
    DetectError();
    MSS_ERROR("smbc_close", error_);
  }
  free(buf);

  // Remove temporary file.
  if (UNLIKELY(unlink((TMPDIR + name).c_str()))) {
    DetectError();
    MSS_ERROR("unlink", error_);
  }

  return mime_type;
}