• Skip to content
  • Skip to link menu
Trinity API Reference
  • Trinity API Reference
  • kio/kio
 

kio/kio

kmimemagic.cpp
00001 /* This file is part of the TDE libraries
00002    Copyright (C) 2014 Timothy Pearson <kb9vqf@pearsoncomputing.net>
00003 
00004    Small portions (the original KDE interface and utime code) are:
00005    Copyright (C) 2000 Fritz Elfert <fritz@kde.org>
00006    Copyright (C) 2004 Allan Sandfeld Jensen <kde@carewolf.com>
00007 
00008    This library is free software; you can redistribute it and/or
00009    modify it under the terms of the GNU Library General Public
00010    License version 2 as published by the Free Software Foundation.
00011 
00012    This library is distributed in the hope that it will be useful,
00013    but WITHOUT ANY WARRANTY; without even the implied warranty of
00014    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015    Library General Public License for more details.
00016 
00017    You should have received a copy of the GNU Library General Public License
00018    along with this library; see the file COPYING.LIB.  If not, write to
00019    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00020    Boston, MA 02110-1301, USA.
00021 */
00022 
00023 #include "config.h"
00024 #include "kmimemagic.h"
00025 #include <kdebug.h>
00026 #include <kapplication.h>
00027 #include <tqfile.h>
00028 #include <ksimpleconfig.h>
00029 #include <kstandarddirs.h>
00030 #include <kstaticdeleter.h>
00031 #include <klargefile.h>
00032 #include <assert.h>
00033 
00034 #include <magic.h>
00035 
00036 #ifndef MAGIC_MIME_TYPE
00037 #define MAGIC_MIME_TYPE MAGIC_MIME
00038 #endif
00039 
00040 // Taken from file/file.h
00041 // Keep in sync with that header!
00042 #define FILE_LOAD   0
00043 
00044 static void process(struct config_rec* conf,  const TQString &);
00045 
00046 KMimeMagic* KMimeMagic::s_pSelf;
00047 static KStaticDeleter<KMimeMagic> kmimemagicsd;
00048 
00049 KMimeMagic* KMimeMagic::self() {
00050     if( !s_pSelf ) {
00051         initStatic();
00052     }
00053     return s_pSelf;
00054 }
00055 
00056 void KMimeMagic::initStatic() {
00057     s_pSelf = kmimemagicsd.setObject( s_pSelf, new KMimeMagic() );
00058     s_pSelf->setFollowLinks( true );
00059 }
00060 
00061 #include <stdio.h>
00062 #include <unistd.h>
00063 #include <stdlib.h>
00064 #include <sys/wait.h>
00065 #include <sys/types.h>
00066 #include <sys/stat.h>
00067 #include <fcntl.h>
00068 #include <errno.h>
00069 #include <ctype.h>
00070 #include <time.h>
00071 #include <utime.h>
00072 #include <stdarg.h>
00073 #include <tqregexp.h>
00074 #include <tqstring.h>
00075 
00076 #define MIME_INODE_DIR         "inode/directory"
00077 #define MIME_INODE_CDEV        "inode/chardevice"
00078 #define MIME_INODE_BDEV        "inode/blockdevice"
00079 #define MIME_INODE_FIFO        "inode/fifo"
00080 #define MIME_INODE_LINK        "inode/link"
00081 #define MIME_INODE_SOCK        "inode/socket"
00082 #define MIME_BINARY_UNREADABLE "application/x-unreadable"
00083 #define MIME_BINARY_ZEROSIZE   "application/x-zerosize"
00084 
00095 class KMimeMagicUtimeConf {
00096     public:
00097         KMimeMagicUtimeConf() {
00098             tmpDirs << TQString::fromLatin1("/tmp"); // default value
00099 
00100             // The trick is that we also don't want the user to override globally set
00101             // directories. So we have to misuse KStandardDirs :}
00102             TQStringList confDirs = KGlobal::dirs()->resourceDirs( "config" );
00103             if ( !confDirs.isEmpty() ) {
00104                 TQString globalConf = confDirs.last() + "kmimemagicrc";
00105                 if ( TQFile::exists( globalConf ) ) {
00106                     KSimpleConfig cfg( globalConf );
00107                     cfg.setGroup( "Settings" );
00108                     tmpDirs = cfg.readListEntry( "atimeDirs" );
00109                 }
00110                 if ( confDirs.count() > 1 ) {
00111                     TQString localConf = confDirs.first() + "kmimemagicrc";
00112                     if ( TQFile::exists( localConf ) ) {
00113                         KSimpleConfig cfg( localConf );
00114                         cfg.setGroup( "Settings" );
00115                         tmpDirs += cfg.readListEntry( "atimeDirs" );
00116                     }
00117                 }
00118                 for ( TQStringList::Iterator it = tmpDirs.begin() ; it != tmpDirs.end() ; ++it ) {
00119                     TQString dir = *it;
00120                     if ( !dir.isEmpty() && dir[ dir.length()-1 ] != '/' ) {
00121                         (*it) += '/';
00122                     }
00123                 }
00124             }
00125         #if 0
00126             // debug code
00127             for ( TQStringList::Iterator it = tmpDirs.begin() ; it != tmpDirs.end() ; ++it ) {
00128                 kdDebug(7018) << " atimeDir: " << *it << endl;
00129             }
00130         #endif
00131         }
00132 
00133         bool restoreAccessTime( const TQString & file ) const {
00134             TQString dir = file.left( file.findRev( '/' ) );
00135             bool res = tmpDirs.contains( dir );
00136             //kdDebug(7018) << "restoreAccessTime " << file << " dir=" << dir << " result=" << res << endl;
00137             return res;
00138         }
00139         TQStringList tmpDirs;
00140 };
00141 
00142 TQString fixupMagicOutput(TQString &mime) {
00143     if (mime == "inode/x-empty") {
00144         return MIME_BINARY_ZEROSIZE;
00145     }
00146     else if (mime.contains("no read permission")) {
00147         return MIME_BINARY_UNREADABLE;
00148     }
00149     else {
00150         return mime;
00151     }
00152 }
00153 
00154 /* current config */
00155 struct config_rec {
00156     bool followLinks;
00157     TQString resultBuf;
00158     int accuracy;
00159 
00160     magic_t magic;
00161     TQStringList databases;
00162 
00163     KMimeMagicUtimeConf * utimeConf;
00164 };
00165 
00166 /*
00167  * apprentice - load configuration from the magic file.
00168  */
00169 int KMimeMagic::apprentice( const TQString& magicfile ) {
00170     TQString maindatabase = magicfile;
00171     if (maindatabase == "") {
00172 #ifdef HAVE_LIBMAGIC_GETPATH
00173         maindatabase = magic_getpath(0, FILE_LOAD);
00174 #else
00175         maindatabase = TQString(LIBMAGIC_PATH);
00176 #endif
00177     }
00178     conf->databases.clear();
00179     conf->databases.append(maindatabase);
00180     return magic_load(conf->magic, conf->databases[0].latin1());
00181 }
00182 
00183 /*
00184  * magic_process - process input file fn. Opens the file and reads a
00185  * fixed-size buffer to begin processing the contents.
00186  */
00187 
00188 void process(struct config_rec* conf, const TQString & fn) {
00189     KDE_struct_stat sb;
00190         TQCString fileName = TQFile::encodeName( fn );
00191 
00192     int magic_flags = MAGIC_ERROR|MAGIC_MIME_TYPE/*|MAGIC_DEBUG*/;
00193     if (conf->followLinks) {
00194         magic_flags |= MAGIC_SYMLINK;
00195     }
00196     magic_setflags(conf->magic, magic_flags);
00197     conf->resultBuf = TQString(magic_file(conf->magic, fileName));
00198     conf->resultBuf = fixupMagicOutput(conf->resultBuf);
00199 
00200     if ( conf->utimeConf && conf->utimeConf->restoreAccessTime( fn ) ) {
00201         /*
00202         * Try to restore access, modification times if read it.
00203         * This changes the "change" time (ctime), but we can't do anything
00204         * about that.
00205         */
00206         struct utimbuf utbuf;
00207         utbuf.actime = sb.st_atime;
00208         utbuf.modtime = sb.st_mtime;
00209         (void) utime(fileName, &utbuf);
00210     }
00211 }
00212 
00213 KMimeMagic::KMimeMagic() {
00214     // Magic file detection init
00215     TQString mimefile = locate( "mime", "magic" );
00216     init( mimefile );
00217     // Add snippets from share/config/magic/*
00218     TQStringList snippets = KGlobal::dirs()->findAllResources( "config", "magic/*.magic", true );
00219     for ( TQStringList::Iterator it = snippets.begin() ; it != snippets.end() ; ++it ) {
00220         if ( !mergeConfig( *it ) ) {
00221             kdWarning() << k_funcinfo << "Failed to parse " << *it << endl;
00222         }
00223     }
00224 }
00225 
00226 KMimeMagic::KMimeMagic(const TQString & _configfile) {
00227     init( _configfile );
00228 }
00229 
00230 void KMimeMagic::init( const TQString& _configfile ) {
00231     int result;
00232     conf = new config_rec;
00233 
00234     /* initialize libmagic */
00235     conf->magic = magic_open(MAGIC_MIME_TYPE);
00236     magicResult = NULL;
00237     conf->followLinks = false;
00238 
00239         conf->utimeConf = 0L; // created on demand
00240     /* on the first time through we read the magic file */
00241     result = apprentice(_configfile);
00242     if (result == -1) {
00243         return;
00244     }
00245 }
00246 
00247 /*
00248  * The destructor.
00249  * Free the magic-table and other resources.
00250  */
00251 KMimeMagic::~KMimeMagic() {
00252     if (conf) {
00253         magic_close(conf->magic);
00254                 delete conf->utimeConf;
00255         delete conf;
00256     }
00257         delete magicResult;
00258 }
00259 
00260 bool KMimeMagic::mergeConfig(const TQString & _configfile) {
00261     conf->databases.append(_configfile);
00262     TQString merged_databases = conf->databases.join(":");
00263 #ifdef MAGIC_VERSION
00264     int magicvers = magic_version();
00265 #else // MAGIC_VERSION
00266     int magicvers = 0;
00267 #endif // MAGIC_VERSION
00268     if ((magicvers < 512) || (magicvers >= 518)) {
00269         if (magic_load(conf->magic, merged_databases.latin1()) == 0) {
00270             return true;
00271         }
00272         else {
00273             return false;
00274         }
00275     }
00276     else {
00277         kdWarning(7018) << "KMimeMagic::mergeConfig disabled due to buggy libmagic version " << magicvers << endl;
00278         return false;
00279     }
00280 }
00281 
00282 void KMimeMagic::setFollowLinks( bool _enable ) {
00283     conf->followLinks = _enable;
00284 }
00285 
00286 KMimeMagicResult *KMimeMagic::findBufferType(const TQByteArray &array) {
00287     conf->resultBuf = TQString::null;
00288     if ( !magicResult ) {
00289         magicResult = new KMimeMagicResult();
00290     }
00291     magicResult->setInvalid();
00292     conf->accuracy = 100;
00293 
00294     int nbytes = array.size();
00295     if (nbytes == 0) {
00296         conf->resultBuf = MIME_BINARY_ZEROSIZE;
00297     }
00298     else {
00299         int magic_flags = MAGIC_ERROR|MAGIC_MIME_TYPE/*|MAGIC_DEBUG*/;
00300         if (conf->followLinks) {
00301             magic_flags |= MAGIC_SYMLINK;
00302         }
00303         magic_setflags(conf->magic, magic_flags);
00304         conf->resultBuf = TQString(magic_buffer(conf->magic, array.data(), nbytes));
00305         conf->resultBuf = fixupMagicOutput(conf->resultBuf);
00306     }
00307     /* if we have any results, put them in the request structure */
00308     magicResult->setMimeType(conf->resultBuf.stripWhiteSpace());
00309     magicResult->setAccuracy(conf->accuracy);
00310     return magicResult;
00311 }
00312 
00313 static void refineResult(KMimeMagicResult *r, const TQString & _filename) {
00314     TQString tmp = r->mimeType();
00315     if (tmp.isEmpty())
00316         return;
00317     if ( tmp == "text/x-c" || tmp == "text/x-objc" )
00318     {
00319         if ( _filename.right(2) == ".h" )
00320             tmp += "hdr";
00321         else
00322             tmp += "src";
00323         r->setMimeType(tmp);
00324     }
00325     else
00326     if ( tmp == "text/x-c++" )
00327     {
00328         if ( _filename.endsWith(".h")
00329           || _filename.endsWith(".hh")
00330           || _filename.endsWith(".H")
00331           || !_filename.right(4).contains('.'))
00332             tmp += "hdr";
00333         else
00334             tmp += "src";
00335         r->setMimeType(tmp);
00336     }
00337     else
00338     if ( tmp == "application/x-sharedlib" )
00339     {
00340         if ( _filename.find( ".so" ) == -1 ) 
00341         {
00342             tmp = "application/x-executable";
00343             r->setMimeType( tmp );
00344         }
00345     }
00346 }
00347 
00348 KMimeMagicResult *KMimeMagic::findBufferFileType( const TQByteArray &data, const TQString &fn) {
00349         KMimeMagicResult * r = findBufferType( data );
00350     refineResult(r, fn);
00351         return r;
00352 }
00353 
00354 /*
00355  * Find the content-type of the given file.
00356  */
00357 KMimeMagicResult* KMimeMagic::findFileType(const TQString & fn) {
00358 #ifdef DEBUG_MIMEMAGIC
00359     kdDebug(7018) << "KMimeMagic::findFileType " << fn << endl;
00360 #endif
00361     conf->resultBuf = TQString::null;
00362 
00363     if ( !magicResult ) {
00364         magicResult = new KMimeMagicResult();
00365     }
00366     magicResult->setInvalid();
00367     conf->accuracy = 100;
00368 
00369     if ( !conf->utimeConf ) {
00370         conf->utimeConf = new KMimeMagicUtimeConf();
00371     }
00372 
00373     /* process it based on the file contents */
00374     process(conf, fn );
00375 
00376     /* if we have any results, put them in the request structure */
00377     magicResult->setMimeType(conf->resultBuf.stripWhiteSpace());
00378     magicResult->setAccuracy(conf->accuracy);
00379     refineResult(magicResult, fn);
00380     return magicResult;
00381 }

kio/kio

Skip menu "kio/kio"
  • Main Page
  • Modules
  • Namespace List
  • Class Hierarchy
  • Alphabetical List
  • Class List
  • File List
  • Namespace Members
  • Class Members
  • Related Pages

kio/kio

Skip menu "kio/kio"
  • arts
  • dcop
  • dnssd
  • interfaces
  •     interface
  •     library
  •   kspeech
  •   ktexteditor
  • kabc
  • kate
  • kcmshell
  • kdecore
  • kded
  • kdefx
  • kdeprint
  • kdesu
  • kdeui
  • kdoctools
  • khtml
  • kimgio
  • kinit
  • kio
  •   bookmarks
  •   httpfilter
  •   kfile
  •   kio
  •   kioexec
  •   kpasswdserver
  •   kssl
  • kioslave
  •   http
  • kjs
  • kmdi
  •   kmdi
  • knewstuff
  • kparts
  • krandr
  • kresources
  • kspell2
  • kunittest
  • kutils
  • kwallet
  • libkmid
  • libkscreensaver
Generated for kio/kio by doxygen 1.7.6.1
This website is maintained by Timothy Pearson.
KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V. |