Line data Source code
1 : // Snap Websites Servers -- check the MIME type of a file using the magic database
2 : // Copyright (c) 2013-2019 Made to Order Software Corp. All Rights Reserved
3 : //
4 : // This program is free software; you can redistribute it and/or modify
5 : // it under the terms of the GNU General Public License as published by
6 : // the Free Software Foundation; either version 2 of the License, or
7 : // (at your option) any later version.
8 : //
9 : // This program is distributed in the hope that it will be useful,
10 : // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : // GNU General Public License for more details.
13 : //
14 : // You should have received a copy of the GNU General Public License
15 : // along with this program; if not, write to the Free Software
16 : // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 :
18 : // self
19 : //
20 : #include "edhttp/mime_type.h"
21 :
22 : #include "edhttp/exception.h"
23 :
24 :
25 : // C lib
26 : //
27 : #include <magic.h>
28 :
29 :
30 : // last include
31 : //
32 : #include <snapdev/poison.h>
33 :
34 :
35 :
36 : namespace edhttp
37 : {
38 :
39 : namespace
40 : {
41 : magic_t g_magic = nullptr;
42 : }
43 :
44 :
45 : /** \brief Generate a MIME type from a buffer.
46 : *
47 : * This function determines the MIME type of a buffer (std::string)
48 : * using the magic library. The magic library is likely to
49 : * understand all the files that a user is to upload on a
50 : * website (within reason, of course).
51 : *
52 : * This function runs against the specified buffer (\p data) from
53 : * memory.
54 : *
55 : * The function returns the computed MIME type such as text/html or
56 : * image/png.
57 : *
58 : * \note
59 : * Compressed files get their type determined after decompression.
60 : *
61 : * \exception mime_type_no_magic
62 : * The function generates an exception if it cannot access the
63 : * magic library (the magic_open() function fails). If the magic
64 : * library is available but the type of the buffer can't be
65 : * determine, then a default MIME type is returned.
66 : *
67 : * \param[in] data The buffer to be transformed in a MIME type.
68 : *
69 : * \return The MIME type of the input buffer.
70 : */
71 0 : std::string get_mime_type(std::string const & data)
72 : {
73 0 : if(g_magic == nullptr)
74 : {
75 0 : g_magic = magic_open(MAGIC_COMPRESS | MAGIC_MIME);
76 0 : if(g_magic == nullptr)
77 : {
78 0 : throw mime_type_no_magic("Magic MIME type cannot be opened (magic_open() failed)");
79 : }
80 :
81 : // load the default magic database
82 : //
83 0 : magic_load(g_magic, nullptr);
84 : }
85 :
86 0 : return magic_buffer(g_magic, data.data(), data.length());
87 : }
88 :
89 :
90 :
91 : } // namespace edhttp
92 : // vim: ts=4 sw=4 et
|