Beispiel #1
0
/**
 * a_jpg_magic_check:
 * @filename: The file
 *
 * Returns: Whether the file is a JPG.
 *  Uses Magic library if available to determine the jpgness.
 *  Otherwise uses a rudimentary extension name check.
 */
gboolean a_jpg_magic_check ( const gchar *filename )
{
	gboolean is_jpg = FALSE;
#ifdef HAVE_MAGIC_H
	magic_t myt = magic_open ( MAGIC_CONTINUE|MAGIC_ERROR|MAGIC_MIME );
	if ( myt ) {
#ifdef WINDOWS
		// We have to 'package' the magic database ourselves :(
		//  --> %PROGRAM FILES%\Viking\magic.mgc
		magic_load ( myt, "magic.mgc" );
#else
		// Use system default
		magic_load ( myt, NULL );
#endif
		const char* magic = magic_file (myt, filename);
		g_debug ( "%s:%s", __FUNCTION__, magic );
		if ( g_ascii_strncasecmp (magic, "image/jpeg", 10) == 0 )
			is_jpg = TRUE;

		magic_close ( myt );
	}
	else
#endif
		is_jpg = a_file_check_ext ( filename, ".jpg" );

	return is_jpg;
}
Beispiel #2
0
/**
 * a_try_decompress_file:
 * @name:  The potentially compressed filename
 *
 * Perform magic to decide how which type of decompression to attempt
 */
void a_try_decompress_file (gchar *name)
{
#ifdef HAVE_MAGIC_H
#ifdef MAGIC_VERSION
	// Or magic_version() if available - probably need libmagic 5.18 or so
	//  (can't determine exactly which version the versioning became available)
	g_debug ("%s: magic version: %d", __FUNCTION__, MAGIC_VERSION );
#endif
	magic_t myt = magic_open ( MAGIC_CONTINUE|MAGIC_ERROR|MAGIC_MIME );
	gboolean zip = FALSE;
	gboolean bzip2 = FALSE;
	if ( myt ) {
#ifdef WINDOWS
		// We have to 'package' the magic database ourselves :(
		//  --> %PROGRAM FILES%\Viking\magic.mgc
		int ml = magic_load ( myt, ".\\magic.mgc" );
#else
		// Use system default
		int ml = magic_load ( myt, NULL );
#endif
		if ( ml == 0 ) {
			const char* magic = magic_file (myt, name);
			g_debug ("%s: magic output: %s", __FUNCTION__, magic );

			if ( g_ascii_strncasecmp(magic, "application/zip", 15) == 0 )
				zip = TRUE;

			if ( g_ascii_strncasecmp(magic, "application/x-bzip2", 19) == 0 )
				bzip2 = TRUE;
		}
		else {
			g_critical ("%s: magic load database failure", __FUNCTION__ );
		}

		magic_close ( myt );
	}

	if ( !(zip || bzip2) )
		return;

	if ( zip ) {
		uncompress_zip ( name );
	}
	else if ( bzip2 ) {
		gchar* bz2_name = uncompress_bzip2 ( name );
		if ( bz2_name ) {
			if ( g_remove ( name ) )
				g_critical ("%s: remove file failed [%s]", __FUNCTION__, name );
			if ( g_rename (bz2_name, name) )
				g_critical ("%s: file rename failed [%s] to [%s]", __FUNCTION__, bz2_name, name );
		}
	}

	return;
#endif
}
FileDetector::FileDetector(const std::string &installDir): mCookie(magic_open(MAGIC_MIME_TYPE)), pBuffer(new char[MAGIC_BUFFER_SIZE])
{
    magic_load(mCookie, 0);
    if (magic_error(mCookie))
    {
        magic_close(mCookie);
        mCookie = magic_open(MAGIC_MIME_TYPE);
        magic_load(mCookie, (installDir + "magic.mgc").c_str());
    }
}
Beispiel #4
0
void magic_init()
{
     MAGIC = magic_open(0);
     snprintf(LOGBUF, LOG_BUF_SZ, "loading magic file from %s", magic_filepath);
     slog(LOGBUF, LOG_INF);
     magic_load(MAGIC, (const char *)magic_filepath);
}
Beispiel #5
0
/** \test magic lib calls -- lookup */
int MagicDetectTest04(void)
{
    magic_t magic_ctx;
    char *result = NULL;

    char buffer[] = {
        0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x00, 0x08,
        0x00, 0x00, 0x52, 0x7b, 0x86, 0x3c, 0x8b, 0x70,
        0x96, 0x08, 0x1c, 0x00, 0x00, 0x00, 0x1c, 0x00,
        0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x6d, 0x69,

        0x6d, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70,
        0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f,
        0x6e, 0x2f, 0x76, 0x6e, 0x64, 0x2e, 0x73, 0x75,
        0x6e, 0x2e, 0x78, 0x6d, 0x6c, 0x2e, 0x62, 0x61,

        0x73, 0x65, 0x50, 0x4b, 0x03, 0x04, 0x14, 0x00,
        0x00, 0x08, 0x00, 0x00, 0x52, 0x7b, 0x86, 0x3c,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00,

        0x4d, 0x45, 0x54, 0x41, 0x2d, 0x49, 0x4e, 0x46,
        0x2f, 0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x00,
        0x08, 0x08, 0x00, 0xa8, 0x42, 0x1d, 0x37, 0x5d,
        0xa7, 0xb2, 0xc1, 0xde, 0x01, 0x00, 0x00, 0x7e,

        0x04, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x63,
        0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x78,
        0x6d, 0x6c, 0x95, 0x54, 0x4d, 0x6f, 0xdb, 0x30,
        0x0c, 0xbd, 0xe7, 0x57, 0x18, 0x02, 0x06, 0x6c,

        0x07, 0xc5, 0xe9, 0xb6, 0xc3, 0x22, 0xc4, 0x29,
        0x86, 0x7d, 0x00, 0x05, 0x8a, 0x9d, 0xb2, 0x43,
        0x8f, 0xb2, 0x24, 0xa7, 0xc2, 0x64, 0xc9, 0x15,
    };
    size_t buffer_len = sizeof(buffer);
    int retval = 0;

    magic_ctx = magic_open(0);
    if (magic_ctx == NULL) {
        printf("failure retrieving magic_ctx\n");
        return 0;
    }

    if (magic_load(magic_ctx, NULL) == -1) {
        printf("magic_load failure\n");
        goto end;
    }

    result = (char *)magic_buffer(magic_ctx, (void *)buffer, buffer_len);
    if (result == NULL || strcmp(result, "OpenOffice.org 1.x Database file") != 0) {
        printf("result %p:%s, not \"OpenOffice.org 1.x Database file\": ", result,result?result:"(null)");
        goto end;
    }

    retval = 1;
end:
    magic_close(magic_ctx);
    return retval;
}
QString Configuration::getMimeType(const QFileInfo& info) {
    QString result("application/octet-stream");
    magic_t magicMimePredictor;
    magicMimePredictor = magic_open(MAGIC_MIME_TYPE); // Open predictor
    if (!magicMimePredictor) {
        qDebug() << "libmagic: Unable to initialize magic library";
    }
    else
    {
        if (magic_load(magicMimePredictor, 0)) { // if not 0 - error
            qDebug() << "libmagic: Can't load magic database - " +
                        QString(magic_error(magicMimePredictor));
            magic_close(magicMimePredictor); // Close predictor
        }
        else
        {
            char *file = info.canonicalFilePath().toAscii().data();
            const char *mime;
            mime = magic_file(magicMimePredictor, file); // getting mime-type
            result = QString(mime);
            magic_close(magicMimePredictor); // Close predictor
        }
    }
    qDebug() << "libmagic: result mime type - " + result + "for file: " +
                info.canonicalFilePath();
    return result;
}
Beispiel #7
0
/*
 * Determine the mime type with the file util.
 */
void Init_magicmime()
{
	cookie= magic_open(MAGIC_SYMLINK | MAGIC_MIME_TYPE);
	magic_load(cookie, 0);
	M_magicmime= rb_define_module("MagicMime");
	rb_define_module_function(M_magicmime, "file", t_file, 1);
}
Beispiel #8
0
const char* FileIO::mimetype(const char *file) {
  static char *buffer = NULL;
  static size_t bufferSize = 0, len;
	const char *mimetype = NULL, *mttemp;
	struct magic_set *mcookie;

	if ((mcookie = magic_open(MAGIC_MIME|MAGIC_CHECK)) != NULL) {
		if (magic_load(mcookie, NULL) == 0) {
			mimetype = magic_file(mcookie, file);
			len = strlen(mimetype);
			mttemp = strchr(mimetype, ';');
			if (mttemp != NULL)
				len = mttemp - mimetype;
			if (len + 1 > bufferSize) {
				if (buffer != NULL)
					delete [] buffer;
				buffer = new char[len + 1];
				bufferSize = len + 1;
			}
			strncpy(buffer, mimetype, len);
			buffer[len] = '\0';
			mimetype = buffer;
		}
		magic_close(mcookie);
	}
	return mimetype;
}
Beispiel #9
0
/** Get filetype of file given by file descriptor.
 * Returns a long decriptive string of the filetype, similar to the file
 * console utility.
 * @param fd file descriptor of open file, make sure the file descriptor is rewinded
 * Warning, the file descriptor is closed by the underlying libmagic. Use dup() to
 * duplicate it and pass this as file descriptor if you need the file afterwards.
 * @return descriptive string
 */
std::string
filetype_file(int fd)
{
  std::string rv;

#ifdef HAVE_LIBMAGIC
  magic_t m = magic_open( MAGIC_ERROR );
  magic_load( m, NULL );

  const char * res = magic_descriptor( m, fd );
  if ( res == NULL ) {
    fawkes::Exception e("Failed to determine file type of descriptor: %s", magic_error(m));
    magic_close(m);
    throw e;
  }

  rv = res;
  magic_close( m );
#else
  throw fawkes::Exception("Failed to determine file type "
			  "(libmagic not available at compile time)");
#endif

  return rv;
}
Beispiel #10
0
rpmmg rpmmgNew(const char * fn, int flags)
{
    rpmmg mg = rpmmgGetPool(_rpmmgPool);
    int xx;

    if (fn)
	mg->fn = xstrdup(fn);
#if defined(HAVE_MAGIC_H)
    mg->flags = (flags ? flags : MAGIC_CHECK);/* XXX MAGIC_COMPRESS flag? */
    mg->ms = magic_open(flags);
    if (mg->ms == NULL) {
	rpmlog(RPMLOG_ERR, _("magic_open(0x%x) failed: %s\n"),
		flags, strerror(errno));
	return rpmmgFree(mg);
    }
    xx = magic_load(mg->ms, mg->fn);
    if (xx == -1) {
        rpmlog(RPMLOG_ERR, _("magic_load(ms, %s) failed: %s\n"),
                (fn ? fn : "(nil)"), magic_error(mg->ms));
	return rpmmgFree(mg);
    }
#endif

    return rpmmgLink(mg);
}
Beispiel #11
0
QString getFileMimeType(const QFileInfo& fileInfo)
{

    QString result("application/octet-stream");

    magic_t magicMimePredictor;
    magicMimePredictor = magic_open(MAGIC_MIME_TYPE); // Open predictor
    if (!magicMimePredictor) {
        qWarning() << "libmagic: Unable to initialize magic library";
        return result;
    }


    if (magic_load(magicMimePredictor, 0)) { // if not 0 - error
        qWarning() << QString("libmagic: Can't load magic database - %1").arg(magic_error(magicMimePredictor));
        magic_close(magicMimePredictor); // Close predictor
        return result;
    }

    QByteArray ar = fileInfo.absoluteFilePath().toLocal8Bit();
    char *file = ar.data();

    // getting mime-type ........................
    const char *mime;
    mime = magic_file(magicMimePredictor, file);
    result = QString(mime);

    // Close predictor ..........................
    magic_close(magicMimePredictor);

    return result;
}
Beispiel #12
0
int main(void)
{
	char *s = "/path/file";
  const char * ftype;

  int msflags = MAGIC_CHECK | MAGIC_COMPRESS | MAGIC_NO_CHECK_TOKENS;
  magic_t ms = NULL;
  ms = magic_open(msflags);
  if (ms == NULL) {
      printf("magic_open(0x%x) failed: %s\n", msflags, errno);
      return 1;
  }

  if (magic_load(ms, NULL) == -1) {
	    printf("magic_load failed: %s\n", magic_error(ms));
      return 1;
  }

  ftype = magic_file(ms, s);

  if (ftype == NULL) {
      printf("Error reconociendo fichero: %s", magic_error(ms));
	    return 1;
  } else {
      printf("tipo de fichero: %s\n", ftype);
  }

  magic_close(ms);

  return 0;
}
Beispiel #13
0
void mime_magic( char *filename, char *key ) {
	struct obj_mime *tuple = NULL;
	magic_t magic = NULL;
	const char *mime = NULL;

	if( ! file_isreg( filename) ) {
		return;
	}

	if( (magic = magic_open( MAGIC_ERROR|MAGIC_MIME)) == NULL ) {
		return;
	}
  
	if( magic_load( magic,NULL) != 0 ) {
		magic_close( magic );
		return;
	}

	if( (mime = magic_file( magic, filename)) == NULL ) {
		magic_close( magic );
		return;
	}
	
	/* Cache mime type in memory */
	mutex_block( _main->mime->mutex );
	tuple = mime_add( key, mime );
	mutex_unblock( _main->mime->mutex );
	
	/* Clear handle */
	magic_close( magic );

	info( NULL, 0, "New MIME: \"%s\" -> \"%s\"", tuple->key, tuple->val );
}
Beispiel #14
0
/** \test magic lib calls -- lookup */
int MagicDetectTest01(void)
{
    magic_t magic_ctx;
    char *result = NULL;
    char buffer[] = { 0x25, 'P', 'D', 'F', '-', '1', '.', '3', 0x0d, 0x0a};
    size_t buffer_len = sizeof(buffer);
    int retval = 0;

    magic_ctx = magic_open(0);
    if (magic_ctx == NULL) {
        printf("failure retrieving magic_ctx\n");
        return 0;
    }

    if (magic_load(magic_ctx, NULL) == -1) {
        printf("magic_load failure\n");
        goto end;
    }

    result = (char *)magic_buffer(magic_ctx, (void *)buffer, buffer_len);
    if (result == NULL || strncmp(result, "PDF document", 12) != 0) {
        printf("result %p:%s, not \"PDF document\": ", result,result?result:"(null)");
        goto end;
    }

    retval = 1;
end:
    magic_close(magic_ctx);
    return retval;
}
Beispiel #15
0
/** Get mime-type of file given by file descriptor.
 * This function gives a brief mime-type for the given file.
 * @param fd file descriptor of open file, make sure the file descriptor is rewinded.
 * Warning, the file descriptor is closed by the underlying libmagic. Use dup() to
 * duplicate it and pass this as file descriptor if you need the file afterwards.
 * @return descriptive string
 */
std::string
mimetype_file(int fd)
{
  std::string rv;

#ifdef HAVE_LIBMAGIC
#  ifdef MAGIC_MIME_TYPE
  magic_t m = magic_open( MAGIC_ERROR | MAGIC_MIME_TYPE );
#  else
  magic_t m = magic_open( MAGIC_ERROR | MAGIC_MIME );
#  endif
  magic_load( m, NULL );

  const char * res = magic_descriptor( m, fd );
  if ( res == NULL ) {
    fawkes::Exception e("Failed to determine mime type of descriptor: %s", magic_error(m));
    magic_close(m);
    throw e;
  }

  rv = res;
#  ifndef MAGIC_MIME_TYPE
  rv = rv.substr(0, rv.find(","));
#  endif
  magic_close(m);
#else
  throw fawkes::Exception("Failed to determine file type "
			  "(libmagic not available at compile time)");
#endif
  return rv;
}
Beispiel #16
0
int module_load(
    YR_SCAN_CONTEXT* context,
    YR_OBJECT* module_object,
    void* module_data,
    size_t module_data_size)
{
  cached_types[context->tidx] = NULL;
  cached_mime_types[context->tidx] = NULL;

  if (magic_cookie[context->tidx] == NULL)
  {
    magic_cookie[context->tidx] = magic_open(0);

    if (magic_cookie[context->tidx] != NULL)
    {
      if (magic_load(magic_cookie[context->tidx], NULL) != 0)
      {
        magic_close(magic_cookie[context->tidx]);
        return ERROR_INTERNAL_FATAL_ERROR;
      }
    }
    else
    {
      return ERROR_INSUFFICIENT_MEMORY;
    }
  }

  return ERROR_SUCCESS;
}
Beispiel #17
0
int get_mimetype(const char *path, const char *test) {
    int ret = 0;
    const char *mimetype;
    magic_t magic;
    
    if ((magic = magic_open(MAGIC_MIME_TYPE)) == NULL) {
        ERROR("An error occurred while loading libmagic database.");
        return ret;
    }
    if (magic_load(magic, NULL) == -1) {
        ERROR("An error occurred while loading libmagic database.");
        goto end;
    }
    if ((mimetype = magic_file(magic, path)) == NULL) {
        ERROR("An error occurred while loading libmagic database.");
        goto end;
    }
    if (strstr(mimetype, test)) {
        ret = 1;
    }
    
end:
    magic_close(magic);
    return ret;
}
Beispiel #18
0
/**
 *  \brief Initialize the "magic" context.
 */
int MagicInit(void)
{
    BUG_ON(g_magic_ctx != NULL);

    SCEnter();

    char *filename = NULL;
    FILE *fd = NULL;

    SCMutexInit(&g_magic_lock, NULL);
    SCMutexLock(&g_magic_lock);

    g_magic_ctx = magic_open(0);
    if (g_magic_ctx == NULL) {
        SCLogError(SC_ERR_MAGIC_OPEN, "magic_open failed: %s",
                magic_error(g_magic_ctx));
        goto error;
    }

    (void)ConfGet("magic-file", &filename);


    if (filename != NULL) {
        if (strlen(filename) == 0) {
            /* set filename to NULL on *nix systems so magic_load uses system
             * default path (see man libmagic) */
            SCLogConfig("using system default magic-file");
            filename = NULL;
        }
        else {
            SCLogConfig("using magic-file %s", filename);

            if ( (fd = fopen(filename, "r")) == NULL) {
                SCLogWarning(SC_ERR_FOPEN, "Error opening file: \"%s\": %s",
                        filename, strerror(errno));
                goto error;
            }
            fclose(fd);
        }
    }

    if (magic_load(g_magic_ctx, filename) != 0) {
        SCLogError(SC_ERR_MAGIC_LOAD, "magic_load failed: %s",
                magic_error(g_magic_ctx));
        goto error;
    }

    SCMutexUnlock(&g_magic_lock);
    SCReturnInt(0);

error:
    if (g_magic_ctx != NULL) {
        magic_close(g_magic_ctx);
        g_magic_ctx = NULL;
    }

    SCMutexUnlock(&g_magic_lock);
    SCReturnInt(-1);
}
Beispiel #19
0
/**
 * Entry point to demo.  Note: this HTTP server will make all
 * files in the current directory and its subdirectories available
 * to anyone.  Press ENTER to stop the server once it has started.
 *
 * @param argc number of arguments in argv
 * @param argv first and only argument should be the port number
 * @return 0 on success
 */
int
main (int argc, char *const *argv)
{
  struct MHD_Daemon *d;
  unsigned int port;

  if ( (argc != 2) ||
       (1 != sscanf (argv[1], "%u", &port)) ||
       (UINT16_MAX < port) )
    {
      fprintf (stderr,
	       "%s PORT\n", argv[0]);
      return 1;
    }
#ifndef MINGW
  ignore_sigpipe ();
#endif
  magic = magic_open (MAGIC_MIME_TYPE);
  (void) magic_load (magic, NULL);

  (void) pthread_mutex_init (&mutex, NULL);
  file_not_found_response = MHD_create_response_from_buffer (strlen (FILE_NOT_FOUND_PAGE),
							     (void *) FILE_NOT_FOUND_PAGE,
							     MHD_RESPMEM_PERSISTENT);
  mark_as_html (file_not_found_response);
  request_refused_response = MHD_create_response_from_buffer (strlen (REQUEST_REFUSED_PAGE),
							     (void *) REQUEST_REFUSED_PAGE,
							     MHD_RESPMEM_PERSISTENT);
  mark_as_html (request_refused_response);
  internal_error_response = MHD_create_response_from_buffer (strlen (INTERNAL_ERROR_PAGE),
							     (void *) INTERNAL_ERROR_PAGE,
							     MHD_RESPMEM_PERSISTENT);
  mark_as_html (internal_error_response);
  update_directory ();
  d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
                        port,
                        NULL, NULL,
			&generate_page, NULL,
			MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (256 * 1024),
#if PRODUCTION
			MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) (64),
#endif
			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) (120 /* seconds */),
			MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS,
			MHD_OPTION_NOTIFY_COMPLETED, &response_completed_callback, NULL,
			MHD_OPTION_END);
  if (NULL == d)
    return 1;
  fprintf (stderr, "HTTP server running. Press ENTER to stop the server\n");
  (void) getc (stdin);
  MHD_stop_daemon (d);
  MHD_destroy_response (file_not_found_response);
  MHD_destroy_response (request_refused_response);
  MHD_destroy_response (internal_error_response);
  update_cached_response (NULL);
  (void) pthread_mutex_destroy (&mutex);
  magic_close (magic);
  return 0;
}
Beispiel #20
0
    CarlaMagic()
        : fMagic(magic_open(MAGIC_SYMLINK)),
          fLoadedOk(false)
    {
        CARLA_SAFE_ASSERT_RETURN(fMagic != nullptr,);

        fLoadedOk = magic_load(fMagic, std::getenv("CARLA_MAGIC_FILE")) == 0;
    }
Beispiel #21
0
    /**
     * Module initialization function. Takes a string as input that allows
     * arguments to be passed into the module.
     * @param arguments Tells the module which
     */
    TskModule::Status TSK_MODULE_EXPORT initialize(const char* arguments)
    {
        magicHandle = magic_open(MAGIC_NONE);
        if (magicHandle == NULL) {
            LOGERROR("FileTypeSigModule: Error allocating magic cookie.");
            return TskModule::FAIL;
        }

//Attempt to load magic database from default places on Linux.
//Don't bother trying magic_load() for defaults on win32 because it will always cause an exception instead of gracefully returning.
#ifndef TSK_WIN32
        /* Load the default magic database, which is found in this order:
               1. MAGIC env variable
               2. $HOME/.magic.mgc (or $HOME/.magic dir)
               3. /usr/share/misc/magic.mgc (or /usr/share/misc/magic dir) (unless libmagic was build configured abnormally)
        */
        if (magic_load(magicHandle, NULL)) {
            std::stringstream msg;
            msg << "FileTypeSigModule: Error loading default magic file: " << magic_error(magicHandle);
            LOGERROR(msg.str());
            //don't return, just fall through to the default loading below
        } else {
            return TskModule::OK;
        }
#endif
        //Load the magic database file in the repo
        std::string path = GetSystemProperty(TskSystemProperties::MODULE_CONFIG_DIR) + Poco::Path::separator() + MODULE_NAME + Poco::Path::separator() + "magic.mgc";

        Poco::File magicFile = Poco::File(path);
        if (magicFile.exists() == false) {
            std::stringstream msg;
            msg << "FileTypeSigModule: Magic file not found: " << path;
            LOGERROR(msg.str());
            return TskModule::FAIL;
        }

        if (magic_load(magicHandle, path.c_str())) {
            std::stringstream msg;
            msg << "FileTypeSigModule: Error loading magic file: " << magic_error(magicHandle) << GetSystemProperty(TskSystemProperties::MODULE_CONFIG_DIR);
            LOGERROR(msg.str());
            return TskModule::FAIL;
        }

        return TskModule::OK;
    }
	MagicProvider() :
		inited_(false) {
		magic_ = magic_open(MAGIC_MIME_TYPE);
		if (NULL != magic_) {
			if (magic_load(magic_, 0) != -1) {
				inited_ = true;
			}
		}
	}
Beispiel #23
0
void FileType::init() {
	magic_ = magic_open(MAGIC_MIME_TYPE | MAGIC_NO_CHECK_COMPRESS); 
	if (!magic_) {
		printf("Error:%s", magic_error(magic_));
	}
	if (magic_load(magic_, 0)) {
		printf("Error:%s", magic_error(magic_));
	}
}
Beispiel #24
0
const gchar *
rstto_file_get_content_type ( RsttoFile *r_file )
{
    const gchar *file_path, *content_type = NULL;

    if ( NULL == r_file->priv->content_type )
    {
#if HAVE_MAGIC_H
        magic_t magic = magic_open (MAGIC_MIME_TYPE | MAGIC_SYMLINK);
        if ( NULL != magic )
        {
            file_path = rstto_file_get_path (r_file);
            if ( NULL != file_path && magic_load (magic, NULL) == 0 )
            {
                content_type = magic_file (magic, file_path);
                if ( NULL != content_type )
                {
                    /* image types that aren't supported by gdk_pixbuf_loader_new_with_mime_type () */
                    if ( g_strcmp0 (content_type, "image/x-ms-bmp") == 0 )
                    {
                        content_type = "image/bmp"; // bug #13489
                    }
                    else if ( g_strcmp0 (content_type, "image/x-portable-greymap") == 0 )
                    {
                        content_type = "image/x-portable-graymap"; // bug #14709
                    }

                    r_file->priv->content_type = g_strdup (content_type);
                }
            }
            magic_close (magic);
        }
#endif

        if ( NULL == content_type )
        {
            GFileInfo *file_info = g_file_query_info (
                    r_file->priv->file,
                    "standard::content-type",
                    0,
                    NULL,
                    NULL );
            if ( NULL != file_info )
            {
                content_type = g_file_info_get_content_type (file_info);
                if ( NULL != content_type )
                {
                    r_file->priv->content_type = g_strdup (content_type);
                }
                g_object_unref (file_info);
            }
        }
    }

    return (const gchar *)r_file->priv->content_type;
}
Beispiel #25
0
		magic() {
			m_magic = magic_open(MAGIC_MIME);
			if (!m_magic)
				throw std::runtime_error("Failed to create MIME magic handler");

			if (magic_load(m_magic, 0) == -1) {
				magic_close(m_magic);
				throw std::runtime_error("Failed to load MIME magic database");
			}
		}
Beispiel #26
0
extern int
s_init(char *p)
{
#ifdef HAVE_LIBMAGIC
    file_magic = magic_open(MAGIC_MIME);
    magic_load(file_magic, DATADIR "/magic");
#endif

    return 0;
}
Beispiel #27
0
svn_error_t *
svn_magic__init(svn_magic__cookie_t **magic_cookie,
                apr_hash_t *config,
                apr_pool_t *result_pool)
{
  svn_magic__cookie_t *mc = NULL;

#ifdef SVN_HAVE_LIBMAGIC
  if (config)
    {
      svn_boolean_t enable;
      svn_config_t *cfg = svn_hash_gets(config, SVN_CONFIG_CATEGORY_CONFIG);

      SVN_ERR(svn_config_get_bool(cfg, &enable,
                                  SVN_CONFIG_SECTION_MISCELLANY,
                                  SVN_CONFIG_OPTION_ENABLE_MAGIC_FILE,
                                  TRUE));
      if (!enable)
        {
          *magic_cookie = NULL;
          return SVN_NO_ERROR;
        }
    }

  mc = apr_palloc(result_pool, sizeof(*mc));

  /* Initialise libmagic. */
#ifndef MAGIC_MIME_TYPE
  /* Some old versions of libmagic don't support MAGIC_MIME_TYPE.
   * We can use MAGIC_MIME instead. It returns more than we need
   * but we can work around that (see below). */
  mc->magic = magic_open(MAGIC_MIME | MAGIC_ERROR);
#else
  mc->magic = magic_open(MAGIC_MIME_TYPE | MAGIC_ERROR);
#endif
  if (mc->magic)
    {
      /* This loads the default magic database.
       * Point the MAGIC environment variable at your favourite .mgc
       * file to load a non-default database. */
      if (magic_load(mc->magic, NULL) == -1)
        {
          magic_close(mc->magic);
          mc = NULL;
        }
      else
        apr_pool_cleanup_register(result_pool, mc, close_magic_cookie,
                                  apr_pool_cleanup_null);
    }
#endif

  *magic_cookie = mc;

  return SVN_NO_ERROR;
}
Beispiel #28
0
int main(int argc, char *argv[])
{
    const char *magic_result;
    magic_t magic_cookie;
    int ret = EXIT_FAILURE;
    const int MAGIC_FLAGS_LENGTH = 3;
    struct magic_flag_s magic_flags[] = {
        mk_magic_flag(MAGIC_NONE),
        mk_magic_flag(MAGIC_MIME),
        mk_magic_flag(MAGIC_MIME_ENCODING),
    };

    // Function magic_open() takes flags that modify libmagic's behaviour, but
    // they can be modified later by using function magic_setflags().
    magic_cookie = magic_open(MAGIC_NONE); 
    if (magic_cookie == NULL)
    {
        printf("Unable to initialize libmagic.\n");
        goto fail;
    }

    // NULL - Using default database, it is possible to specify your own.
    if (magic_load(magic_cookie, NULL) != 0)
    {
        printf("Failed while loading magic database: %s\n",
            magic_error(magic_cookie));
        goto fail_with_cleanup;
    }

    for (int i = 1; i < argc; i++)
    {
        for (int j = 0; j < MAGIC_FLAGS_LENGTH; j++)
        {
            magic_setflags(magic_cookie, magic_flags[j].value);

            // I'm assuming that magic_file() returns pointer to some allocated
            // memmory associated with magic_cookie and therefore it's not
            // necessary to dealocate it afterwards.
            magic_result = magic_file(magic_cookie, argv[i]);
            if (magic_result != NULL)
            {
                printf("Result with %s flag: %s\n",
                    magic_flags[j].string, magic_result);
            }
        }
    }
    ret = EXIT_SUCCESS;

fail_with_cleanup:
    magic_close(magic_cookie);

fail:
    return ret;
}
Beispiel #29
0
/** \test magic lib calls -- lookup */
int MagicDetectTest03(void)
{
    magic_t magic_ctx;
    char *result = NULL;

    char buffer[] = {
        0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x0b, 0x55, 0x2a, 0x36, 0x5e, 0xc6,
        0x32, 0x0c, 0x27, 0x00, 0x00, 0x00, 0x27, 0x00,
        0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x6d, 0x69,

        0x6d, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70,
        0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f,
        0x6e, 0x2f, 0x76, 0x6e, 0x64, 0x2e, 0x6f, 0x61,
        0x73, 0x69, 0x73, 0x2e, 0x6f, 0x70, 0x65, 0x6e,

        0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74,
        0x2e, 0x74, 0x65, 0x78, 0x74, 0x50, 0x4b, 0x03,
        0x04, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b,
        0x55, 0x2a, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00,

        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1a,
        0x00, 0x00, 0x00, 0x43, 0x6f, 0x6e, 0x66, 0x69,
        0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e,
        0x73, 0x32, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75,

        0x73, 0x62, 0x61, 0x72, 0x2f, 0x50, 0x4b, 0x03,
        0x04, 0x14, 0x00, 0x08, 0x00, 0x08, 0x00, 0x0b,
    };
    size_t buffer_len = sizeof(buffer);
    int retval = 0;

    magic_ctx = magic_open(0);
    if (magic_ctx == NULL) {
        printf("failure retrieving magic_ctx\n");
        return 0;
    }

    if (magic_load(magic_ctx, NULL) == -1) {
        printf("magic_load failure\n");
        goto end;
    }

    result = (char *)magic_buffer(magic_ctx, (void *)buffer, buffer_len);
    if (result == NULL || strcmp(result, "OpenDocument Text") != 0) {
        printf("result %p:%s, not \"OpenDocument Text\": ", result,result?result:"(null)");
        goto end;
    }

    retval = 1;
end:
    magic_close(magic_ctx);
    return retval;
}
Beispiel #30
0
/**
 * @brief initialize
 */
int  FindCmdInit()
{
  MagicCookie = magic_open(MAGIC_PRESERVE_ATIME|MAGIC_MIME);
  if (MagicCookie == NULL)
  {
    fprintf(stderr,"FATAL: Failed to initialize magic cookie\n");
    return -1;
  }

  magic_load(MagicCookie,NULL);
  return 0;
}