├── .dockerignore ├── Dockerfile ├── AUTHORS ├── meson_options.txt ├── .gitignore ├── .clang-format ├── src ├── meson.build ├── mimetypecounter.h ├── mimetypecounter.cpp ├── zimcreatorfs.h ├── tools.h ├── queue.h ├── article.h ├── zimcreatorfs.cpp ├── article.cpp ├── zimwriterfs.cpp └── tools.cpp ├── format_code.sh ├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── docker └── Dockerfile ├── meson.build ├── ChangeLog ├── contrib └── zimwriterfs-in-docker ├── README.md └── LICENSE /.dockerignore: -------------------------------------------------------------------------------- 1 | build 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | docker/Dockerfile -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Emmanuel Engelhart 2 | -------------------------------------------------------------------------------- /meson_options.txt: -------------------------------------------------------------------------------- 1 | option('static-linkage', type : 'boolean', value : false, 2 | description : 'Create statically linked binaries.') 3 | option('magic-install-prefix', type : 'string', value : '', 4 | description : 'Prefix where libmagic has been installed') 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *#* 3 | compile 4 | depcomp 5 | .deps 6 | .dirstamp 7 | INSTALL 8 | install-sh 9 | *.kate-swp 10 | .libs 11 | libtool 12 | *.o 13 | stamp-h1 14 | .*.swp 15 | *.zim 16 | zimwriterfs 17 | bin 18 | build 19 | lib 20 | share 21 | include 22 | pip-selfcheck.json 23 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: Google 2 | BinPackArguments: false 3 | BinPackParameters: false 4 | BreakBeforeBinaryOperators: All 5 | BreakBeforeBraces: Linux 6 | DerivePointerAlignment: false 7 | SpacesInContainerLiterals: false 8 | Standard: Cpp11 9 | 10 | AllowShortFunctionsOnASingleLine: Inline 11 | AllowShortIfStatementsOnASingleLine: false 12 | AllowShortLoopsOnASingleLine: false 13 | -------------------------------------------------------------------------------- /src/meson.build: -------------------------------------------------------------------------------- 1 | sources = [ 2 | 'zimwriterfs.cpp', 3 | 'tools.cpp', 4 | 'article.cpp', 5 | 'zimcreatorfs.cpp', 6 | 'mimetypecounter.cpp' 7 | ] 8 | 9 | deps = [thread_dep, libzim_dep, zlib_dep, gumbo_dep, magic_dep] 10 | 11 | zimwriterfs = executable('zimwriterfs', 12 | sources, 13 | dependencies : deps, 14 | install : true) -------------------------------------------------------------------------------- /format_code.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash 2 | 3 | files=( 4 | "article.cpp" 5 | "article.h" 6 | "articlesource.cpp" 7 | "articlesource.h" 8 | "indexer.cpp" 9 | "indexer.h" 10 | "mimetypecounter.cpp" 11 | "mimetypecounter.h" 12 | "pathTools.cpp" 13 | "pathTools.h" 14 | "resourceTools.cpp" 15 | "resourceTools.h" 16 | "tools.cpp" 17 | "tools.h" 18 | "xapianIndexer.cpp" 19 | "xapianIndexer.h" 20 | "zimwriterfs.cpp" 21 | "xapian/htmlparse.cc" 22 | "xapian/htmlparse.h" 23 | "xapian/myhtmlparse.cc" 24 | "xapian/myhtmlparse.h" 25 | "xapian/namedentities.h" 26 | ) 27 | 28 | for i in "${files[@]}" 29 | do 30 | echo $i 31 | clang-format -i -style=file $i 32 | done 33 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: kiwix # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # https://kiwix.org/support-us/ 13 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:bionic 2 | 3 | # Update system 4 | RUN echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections 5 | 6 | # Configure locales 7 | RUN apt-get update -y && \ 8 | apt-get install -y --no-install-recommends locales && \ 9 | apt-get clean -y && \ 10 | rm -rf /var/lib/apt/lists/* 11 | ENV LANG en_US.UTF-8 12 | ENV LANGUAGE en_US:en 13 | ENV LC_ALL en_US.UTF-8 14 | RUN locale-gen en_US.UTF-8 15 | 16 | # Install necessary packages 17 | RUN apt-get update -y && \ 18 | apt-get install -y --no-install-recommends git pkg-config libtool automake autoconf make g++ liblzma-dev coreutils meson ninja-build wget zlib1g-dev libicu-dev libgumbo-dev libmagic-dev ca-certificates && \ 19 | apt-get clean -y && \ 20 | rm -rf /var/lib/apt/lists/* 21 | 22 | # Update CA certificates 23 | RUN update-ca-certificates 24 | 25 | # Install Xapian (wget zlib1g-dev) 26 | RUN wget https://oligarchy.co.uk/xapian/1.4.14/xapian-core-1.4.14.tar.xz 27 | RUN tar xvf xapian-core-1.4.14.tar.xz 28 | RUN cd xapian-core-1.4.14 && ./configure 29 | RUN cd xapian-core-1.4.14 && make all install 30 | RUN rm -rf xapian 31 | 32 | # Install zimlib (libicu-dev) 33 | RUN git clone https://github.com/openzim/libzim.git 34 | RUN cd libzim && git checkout 6.0.2 35 | RUN cd libzim && meson . build 36 | RUN cd libzim && ninja -C build install 37 | RUN rm -rf libzim 38 | 39 | # Install zimwriterfs (libgumbo-dev libmagic-dev) 40 | COPY . zimwriterfs 41 | RUN cd zimwriterfs && meson . build 42 | RUN cd zimwriterfs && ninja -C build install 43 | RUN rm -rf zimwriterfs 44 | RUN ldconfig 45 | ENV LD_LIBRARY_PATH /usr/local/lib/x86_64-linux-gnu/ 46 | 47 | # Boot commands 48 | CMD zimwriterfs ; /bin/bash 49 | -------------------------------------------------------------------------------- /src/mimetypecounter.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2016 Emmanuel Engelhart 3 | * Copyright 2016 Matthieu Gautier 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software 17 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 18 | * MA 02110-1301, USA. 19 | */ 20 | 21 | #ifndef OPENZIM_ZIMWRITERFS_MIMETYPECOUNTER_H 22 | #define OPENZIM_ZIMWRITERFS_MIMETYPECOUNTER_H 23 | 24 | #include "article.h" 25 | #include "zimcreatorfs.h" 26 | #include 27 | 28 | class MimetypeCounter; 29 | 30 | class MetadataCounterArticle : public MetadataArticle 31 | { 32 | private: 33 | MimetypeCounter* counter; 34 | mutable std::string data; 35 | void genData() const; 36 | 37 | public: 38 | MetadataCounterArticle(MimetypeCounter* counter); 39 | virtual zim::Blob getData() const; 40 | virtual zim::size_type getSize() const; 41 | virtual zim::writer::Url getRedirectUrl() const { return zim::writer::Url(); } 42 | }; 43 | 44 | class MimetypeCounter : public IHandler 45 | { 46 | public: 47 | void handleArticle(std::shared_ptr article); 48 | std::shared_ptr getMetaArticle() 49 | { 50 | return std::make_shared(this); 51 | } 52 | 53 | private: 54 | std::map counters; 55 | 56 | friend class MetadataCounterArticle; 57 | }; 58 | 59 | #endif // OPENZIM_ZIMWRITERFS_MIMETYPECOUNTER_H 60 | -------------------------------------------------------------------------------- /src/mimetypecounter.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2016 Emmanuel Engelhart 3 | * Copyright 2016 Matthieu Gautier 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software 17 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 18 | * MA 02110-1301, USA. 19 | */ 20 | 21 | #include "mimetypecounter.h" 22 | #include 23 | 24 | MetadataCounterArticle::MetadataCounterArticle(MimetypeCounter* counter) 25 | : MetadataArticle("Counter"), counter(counter) 26 | { 27 | } 28 | 29 | void MetadataCounterArticle::genData() const{ 30 | std::stringstream stream; 31 | for (std::map::iterator it 32 | = counter->counters.begin(); 33 | it != counter->counters.end(); 34 | ++it) { 35 | stream << it->first << "=" << it->second << ";"; 36 | } 37 | data = stream.str(); 38 | } 39 | 40 | zim::Blob MetadataCounterArticle::getData() const 41 | { 42 | if (data.empty()) 43 | genData(); 44 | return zim::Blob(data.data(), data.size()); 45 | } 46 | 47 | zim::size_type MetadataCounterArticle::getSize() const 48 | { 49 | if (data.empty()) 50 | genData(); 51 | return data.size(); 52 | } 53 | 54 | void MimetypeCounter::handleArticle(std::shared_ptr article) 55 | { 56 | if (article->isRedirect()) { 57 | return; 58 | } 59 | 60 | std::string mimeType = article->getMimeType(); 61 | if (counters.find(mimeType) == counters.end()) { 62 | counters[mimeType] = 1; 63 | } else { 64 | counters[mimeType]++; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /meson.build: -------------------------------------------------------------------------------- 1 | project('zimwriterfs', ['c', 'cpp'], 2 | version : '1.3.10', 3 | license : 'GPL-3.0-or-later', 4 | default_options : ['c_std=c11', 'cpp_std=c++11', 'werror=true']) 5 | 6 | add_global_arguments('-DVERSION="@0@"'.format(meson.project_version()), language : 'cpp') 7 | 8 | compiler = meson.get_compiler('cpp') 9 | find_library_in_compiler = meson.version().version_compare('>=0.31.0') 10 | 11 | static_linkage = get_option('static-linkage') 12 | if static_linkage 13 | add_global_link_arguments('-static-libstdc++', '--static', language:'cpp') 14 | endif 15 | 16 | thread_dep = dependency('threads') 17 | libzim_dep = dependency('libzim', version : '>=6.1.2', static:static_linkage) 18 | zlib_dep = dependency('zlib', static:static_linkage) 19 | gumbo_dep = dependency('gumbo', static:static_linkage) 20 | 21 | magic_include_path = '' 22 | magic_prefix_install = get_option('magic-install-prefix') 23 | if magic_prefix_install == '' 24 | if compiler.has_header('magic.h') 25 | if find_library_in_compiler 26 | magic_lib = compiler.find_library('magic') 27 | else 28 | magic_lib = find_library('magic') 29 | endif 30 | magic_dep = declare_dependency(link_args:['-lmagic']) 31 | else 32 | error('magic.h not found') 33 | endif 34 | else 35 | if not find_library_in_compiler 36 | error('For custom magic_prefix_install you need a meson version >=0.31.0') 37 | endif 38 | magic_include_path = magic_prefix_install + '/include' 39 | magic_include_args = ['-I'+magic_include_path] 40 | if compiler.has_header('magic.h', args:magic_include_args) 41 | magic_include_dir = include_directories(magic_include_path, is_system:true) 42 | magic_lib_path = join_paths(magic_prefix_install, get_option('libdir')) 43 | magic_lib = compiler.find_library('magic', dirs:magic_lib_path, required:false) 44 | if not magic_lib.found() 45 | magic_lib_path = join_paths(magic_prefix_install, 'lib') 46 | magic_lib = compiler.find_library('magic', dirs:magic_lib_path) 47 | endif 48 | magic_link_args = ['-L'+magic_lib_path, '-lmagic'] 49 | magic_dep = declare_dependency(include_directories:magic_include_dir, link_args:magic_link_args) 50 | else 51 | error('magic.h not found') 52 | endif 53 | endif 54 | 55 | subdir('src') 56 | 57 | -------------------------------------------------------------------------------- /ChangeLog: -------------------------------------------------------------------------------- 1 | zimwriterfs 1.3.10 2 | ================== 3 | 4 | * Fix parsing of option for --withFulltextIndex 5 | 6 | zimwriterfs 1.3.9 7 | ================= 8 | 9 | * Udpate to last version of libzim 10 | * [CI] Move the ci to github actions 11 | 12 | zimwriterfs 1.3.8 13 | ================= 14 | 15 | * Fix a few buggy mimetypes 16 | * Fix the support of --name 17 | * New --source argument 18 | 19 | zimwriterfs 1.3.7 20 | ================= 21 | 22 | * Fix buggy --withoutFulltextIndex option parsing 23 | * Rename --withoutFulltextIndex to --withoutFTIndex 24 | * Introduce backward compatible --withFulltextIndex 25 | * Docker image now using libzim 6.0.0 26 | 27 | zimwriterfs 1.3.6 28 | ================= 29 | 30 | * Remove specific script to compile zimwriterfs on macos. 31 | * Adapt to new libzim's creator api. 32 | * Correctly index redirect title. 33 | 34 | zimwriterfs 1.3.5 35 | ================= 36 | 37 | * Fix resources URL rewriting in CSS files 38 | * Add --flavour and --scraper optional arguments 39 | * Fix favicon redirection creation 40 | * Replace --withFullTextIndex by --withoutFullTextIndex 41 | 42 | zimwriterfs 1.3.4 43 | ================= 44 | 45 | * Fix wrong mimetype for Webm videos 46 | 47 | zimwriterfs 1.3.3 48 | ================= 49 | 50 | * Fix mainPage issue 51 | * Do not try to read TSV redirect if not given. 52 | 53 | zimwriterfs 1.3.2 54 | ================= 55 | 56 | * Fix usage message. 57 | * Update to the new libzim 5.0.0 API. 58 | 59 | zimwriterfs 1.3.1 60 | ================= 61 | 62 | * Update Dockerfile and docker's documentation. 63 | * Remove unused reference to xapian. 64 | * Build without rpath. 65 | 66 | zimwriterfs 1.3 67 | =============== 68 | 69 | * Proper support of woff2 font files 70 | * Added -V --version command line arguments 71 | * Properly handle wrong format of the redirect files. 72 | * Do not make zimwriterfs verbose by default. 73 | 74 | zimwriterfs 1.2 75 | =============== 76 | 77 | * Revert "Add leading '/' at indexer url. 78 | * Move to meson build system. 79 | * Addapt to new libzim's writer's API. 80 | * Add travic CI. 81 | * Add redirect articles after "normal" articles. 82 | * Explicitly use icu namespace to allow use of packaged icu lib. 83 | * Fix help/log typos. 84 | * Better README. 85 | -------------------------------------------------------------------------------- /src/zimcreatorfs.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2016 Emmanuel Engelhart 3 | * Copyright 2016 Matthieu Gautier 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software 17 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 18 | * MA 02110-1301, USA. 19 | */ 20 | 21 | #ifndef OPENZIM_ZIMWRITERFS_ZIMCREATORFS_H 22 | #define OPENZIM_ZIMWRITERFS_ZIMCREATORFS_H 23 | 24 | #include 25 | #include 26 | #include "article.h" 27 | 28 | #include 29 | 30 | class IHandler 31 | { 32 | public: 33 | virtual void handleArticle(std::shared_ptr article) = 0; 34 | virtual std::shared_ptr getMetaArticle() = 0; 35 | virtual ~IHandler() = default; 36 | }; 37 | 38 | class ZimCreatorFS : public zim::writer::Creator 39 | { 40 | public: 41 | ZimCreatorFS(std::string mainPage, bool verbose) 42 | : zim::writer::Creator(verbose), 43 | mainPage(mainPage) {} 44 | virtual ~ZimCreatorFS() = default; 45 | virtual zim::writer::Url getMainUrl() const; 46 | virtual void add_customHandler(IHandler* handler); 47 | virtual void add_redirectArticles_from_file(const std::string& path); 48 | virtual void visitDirectory(const std::string& path); 49 | 50 | virtual void addMetadata(const std::string& metadata, const std::string& content); 51 | virtual void addArticle(const std::string& path); 52 | virtual void addArticle(std::shared_ptr article); 53 | virtual void finishZimCreation(); 54 | 55 | private: 56 | std::vector articleHandlers; 57 | std::string mainPage; 58 | }; 59 | 60 | #endif // OPENZIM_ZIMWRITERFS_ARTICLESOURCE_H 61 | -------------------------------------------------------------------------------- /src/tools.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2016 Emmanuel Engelhart 3 | * Copyright 2016 Matthieu Gautier 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software 17 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 18 | * MA 02110-1301, USA. 19 | */ 20 | 21 | #ifndef OPENZIM_ZIMWRITERFS_TOOLS_H 22 | #define OPENZIM_ZIMWRITERFS_TOOLS_H 23 | 24 | #include 25 | #include 26 | #include 27 | 28 | std::string getMimeTypeForFile(const std::string& filename); 29 | std::string getNamespaceForMimeType(const std::string& mimeType); 30 | std::string getFileContent(const std::string& path); 31 | unsigned int getFileSize(const std::string& path); 32 | std::string decodeUrl(const std::string& encodedUrl); 33 | std::string computeAbsolutePath(const std::string& path, 34 | const std::string& relativePath); 35 | bool fileExists(const std::string& path); 36 | std::string removeLastPathElement(const std::string& path, 37 | const bool removePreSeparator, 38 | const bool removePostSeparator); 39 | std::string computeNewUrl(const std::string& aid, const std::string& baseUrl, const std::string& targetUrl); 40 | 41 | std::string base64_encode(unsigned char const* bytes_to_encode, 42 | unsigned int in_len); 43 | 44 | void replaceStringInPlaceOnce(std::string& subject, 45 | const std::string& search, 46 | const std::string& replace); 47 | void replaceStringInPlace(std::string& subject, 48 | const std::string& search, 49 | const std::string& replace); 50 | void stripTitleInvalidChars(std::string& str); 51 | 52 | std::string extractRedirectUrlFromHtml(const GumboVector* head_children); 53 | void getLinks(GumboNode* node, std::map& links); 54 | 55 | std::string removeAccents(const std::string& text); 56 | 57 | void remove_all(const std::string& path); 58 | 59 | #endif // OPENZIM_ZIMWRITERFS_TOOLS_H 60 | -------------------------------------------------------------------------------- /src/queue.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Matthieu Gautier 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 3 of the License, or 7 | * 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 Street, Fifth Floor, Boston, 17 | * MA 02110-1301, USA. 18 | */ 19 | 20 | #ifndef OPENZIM_ZIMWRITERFS_QUEUE_H 21 | #define OPENZIM_ZIMWRITERFS_QUEUE_H 22 | 23 | #define MAX_QUEUE_SIZE 100 24 | 25 | #include 26 | #include 27 | 28 | template 29 | class Queue { 30 | public: 31 | Queue() {pthread_mutex_init(&m_queueMutex,NULL);}; 32 | virtual ~Queue() {pthread_mutex_destroy(&m_queueMutex);}; 33 | virtual bool isEmpty(); 34 | virtual void pushToQueue(const T& element); 35 | virtual bool popFromQueue(T &filename); 36 | 37 | protected: 38 | std::queue m_realQueue; 39 | pthread_mutex_t m_queueMutex; 40 | 41 | private: 42 | // Make this queue non copyable 43 | Queue(const Queue&); 44 | Queue& operator=(const Queue&); 45 | }; 46 | 47 | template 48 | bool Queue::isEmpty() { 49 | pthread_mutex_lock(&m_queueMutex); 50 | bool retVal = m_realQueue.empty(); 51 | pthread_mutex_unlock(&m_queueMutex); 52 | return retVal; 53 | } 54 | 55 | template 56 | void Queue::pushToQueue(const T &element) { 57 | unsigned int wait = 0; 58 | unsigned int queueSize = 0; 59 | 60 | do { 61 | usleep(wait); 62 | pthread_mutex_lock(&m_queueMutex); 63 | queueSize = m_realQueue.size(); 64 | pthread_mutex_unlock(&m_queueMutex); 65 | wait += 10; 66 | } while (queueSize > MAX_QUEUE_SIZE); 67 | 68 | pthread_mutex_lock(&m_queueMutex); 69 | m_realQueue.push(element); 70 | pthread_mutex_unlock(&m_queueMutex); 71 | } 72 | 73 | template 74 | bool Queue::popFromQueue(T &element) { 75 | pthread_mutex_lock(&m_queueMutex); 76 | if (m_realQueue.empty()) { 77 | pthread_mutex_unlock(&m_queueMutex); 78 | return false; 79 | } 80 | 81 | element = m_realQueue.front(); 82 | m_realQueue.pop(); 83 | pthread_mutex_unlock(&m_queueMutex); 84 | 85 | return true; 86 | } 87 | 88 | #endif // OPENZIM_ZIMWRITERFS_QUEUE_H -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | Macos: 7 | runs-on: macos-latest 8 | steps: 9 | - name: Checkout code 10 | uses: actions/checkout@v1 11 | - name: Setup python 3.5 12 | uses: actions/setup-python@v1 13 | with: 14 | python-version: '3.5' 15 | - name: Install packages 16 | uses: mstksg/get-package@v1 17 | with: 18 | brew: gcovr pkg-config ninja libmagic 19 | - name: Install python modules 20 | run: pip3 install meson==0.49.2 pytest 21 | - name: Install deps 22 | shell: bash 23 | run: | 24 | ARCHIVE_NAME=deps2_osx_native_dyn_zimwriterfs.tar.xz 25 | wget -O- http://tmp.kiwix.org/ci/${ARCHIVE_NAME} | tar -xJ -C $HOME 26 | - name: Compile 27 | shell: bash 28 | run: | 29 | export PKG_CONFIG_PATH=$HOME/BUILD_native_dyn/INSTALL/lib/pkgconfig 30 | meson . build 31 | cd build 32 | ninja 33 | 34 | 35 | Linux: 36 | strategy: 37 | fail-fast: false 38 | matrix: 39 | target: 40 | - native_static 41 | - native_dyn 42 | include: 43 | - target: native_static 44 | image_variant: xenial 45 | lib_postfix: '/x86_64-linux-gnu' 46 | - target: native_dyn 47 | image_variant: xenial 48 | lib_postfix: '/x86_64-linux-gnu' 49 | env: 50 | HOME: /home/runner 51 | runs-on: ubuntu-latest 52 | container: 53 | image: "kiwix/kiwix-build_ci:${{matrix.image_variant}}-26" 54 | steps: 55 | - name: Extract branch name 56 | shell: bash 57 | run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})" 58 | id: extract_branch 59 | - name: Checkout code 60 | shell: python 61 | run: | 62 | from subprocess import check_call 63 | from os import environ 64 | command = [ 65 | 'git', 'clone', 66 | 'https://github.com/${{github.repository}}', 67 | '--depth=1', 68 | '--branch', '${{steps.extract_branch.outputs.branch}}' 69 | ] 70 | check_call(command, cwd=environ['HOME']) 71 | - name: Install deps 72 | shell: bash 73 | run: | 74 | ARCHIVE_NAME=deps2_${OS_NAME}_${{matrix.target}}_zimwriterfs.tar.xz 75 | wget -O- http://tmp.kiwix.org/ci/${ARCHIVE_NAME} | tar -xJ -C /home/runner 76 | - name: Compile 77 | shell: bash 78 | run: | 79 | if [[ "${{matrix.target}}" =~ .*_static ]]; then 80 | MESON_OPTION="-Dstatic-linkage=true" 81 | fi 82 | cd $HOME/zimwriterfs 83 | meson . build ${MESON_OPTION} 84 | cd build 85 | ninja 86 | env: 87 | PKG_CONFIG_PATH: "/home/runner/BUILD_${{matrix.target}}/INSTALL/lib/pkgconfig:/home/runner/BUILD_${{matrix.target}}/INSTALL/lib${{matrix.lib_postfix}}/pkgconfig" 88 | -------------------------------------------------------------------------------- /contrib/zimwriterfs-in-docker: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # vim: ai ts=4 sts=4 et sw=4 nu 4 | 5 | """ zimwriterfs drop-in replacement for macOS (or Linux) using Docker 6 | 7 | allows you to use zimwriterfs directly without having to compile/install it ; 8 | by pulling/running it from its docker image. 9 | 10 | >> just place it in /usr/local/bin/zimwriterfs. 11 | 12 | script will automatically mount (as volumes) and replace (in the command args) 13 | the HTML_FOLDER and the parent folder of the requested ZIM file. 14 | """ 15 | 16 | import os 17 | import sys 18 | import subprocess 19 | 20 | DATA_VOLUME_DST = "/data" 21 | ZIM_VOLUME_DST = "/zim" 22 | DEBUG = False 23 | 24 | CONTAINER_NAME = 'zimwriterfs' 25 | IMAGE_NAME = 'openzim/zimwriterfs' 26 | 27 | 28 | def run(arguments): 29 | if str is not bytes: # python3 30 | return subprocess.run(arguments).returncode 31 | else: 32 | return subprocess.call(arguments) 33 | 34 | 35 | def volumes_from(html_folder, zim_file): 36 | # make sure targets are expanded 37 | html_folder = os.path.expanduser(html_folder) 38 | zim_file = os.path.expanduser(zim_file) 39 | 40 | # docker command line parameters format for volume attachment 41 | vol = lambda src, dst: ['-v', "{src}:{dst}".format(src=src, dst=dst)] 42 | 43 | # outputing a list of volume-attach-params 44 | # and actual zimwriterfs params for html_folder and zim_file 45 | d = {'volumes': [], 46 | 'html_folder_path': None, 47 | 'zim_file_path': None} 48 | 49 | # html folder volume should be parent of target 50 | hvolume, hfolder = os.path.split(html_folder) \ 51 | if os.path.isabs(html_folder) \ 52 | else (os.getcwd(), html_folder) 53 | d['volumes'].append(vol(hvolume, DATA_VOLUME_DST)) 54 | d['html_folder_path'] = os.path.join(DATA_VOLUME_DST, hfolder) 55 | 56 | # zim-file volume should be parent of target 57 | if os.path.isabs(zim_file): 58 | zvolume, zfile = os.path.split(zim_file) 59 | else: 60 | zparts = [p for p in os.path.split(zim_file)[:-1] if p.strip()] 61 | # target parent might be CWD 62 | if len(zparts): 63 | zvolume = os.path.join(os.getcwd(), os.path.join(*zparts)) 64 | else: 65 | zvolume = os.getcwd() 66 | zfile = zim_file 67 | 68 | # either mount a single volume as /data or another one as /zim 69 | if hvolume != zvolume: 70 | d['volumes'].append(vol(zvolume, ZIM_VOLUME_DST)) 71 | d['zim_file_path'] = os.path.join(ZIM_VOLUME_DST, zfile) 72 | else: 73 | d['zim_file_path'] = os.path.join(DATA_VOLUME_DST, zfile) 74 | 75 | return d 76 | 77 | 78 | def stop_container(): 79 | run(['docker', 'stop', CONTAINER_NAME]) 80 | 81 | 82 | def remove_container(): 83 | run(['docker', 'rm', '-f', CONTAINER_NAME]) 84 | 85 | 86 | def stop_and_remove_container(): 87 | stop_container() 88 | remove_container() 89 | 90 | 91 | def start_container(volumes, parameters): 92 | run(['docker', 'pull', IMAGE_NAME]) 93 | command = ['docker', 'run', '--name', CONTAINER_NAME] \ 94 | + [vol_param for volume in volumes for vol_param in volume] \ 95 | + [IMAGE_NAME, 'zimwriterfs'] + parameters 96 | 97 | if DEBUG: 98 | print(" ".join(command)) 99 | return run(command) 100 | 101 | 102 | def main(arguments): 103 | if len(arguments) >= 7: 104 | main_arguments = arguments[:len(arguments) - 2] 105 | html_folder = arguments[len(arguments) - 2] 106 | zim_file = arguments[len(arguments) - 1] 107 | 108 | voldata = volumes_from(html_folder, zim_file) 109 | volumes = voldata['volumes'] 110 | arguments = main_arguments + [voldata['html_folder_path'], 111 | voldata['zim_file_path']] 112 | else: 113 | volumes = [] 114 | 115 | stop_and_remove_container() 116 | retcode = start_container(volumes, arguments) 117 | stop_and_remove_container() 118 | sys.exit(retcode) 119 | 120 | 121 | if __name__ == '__main__': 122 | main(sys.argv[1:]) 123 | -------------------------------------------------------------------------------- /src/article.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2016 Emmanuel Engelhart 3 | * Copyright 2016 Matthieu Gautier 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software 17 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 18 | * MA 02110-1301, USA. 19 | */ 20 | 21 | #ifndef OPENZIM_ZIMWRITERFS_ARTICLE_H 22 | #define OPENZIM_ZIMWRITERFS_ARTICLE_H 23 | 24 | #include 25 | #include 26 | #include 27 | 28 | extern std::string favicon; 29 | 30 | class Article : public zim::writer::Article 31 | { 32 | protected: 33 | char ns; 34 | std::string url; 35 | std::string title; 36 | std::string mimeType; 37 | zim::writer::Url redirectUrl; 38 | 39 | public: 40 | virtual zim::writer::Url getUrl() const; 41 | virtual std::string getTitle() const; 42 | virtual bool isRedirect() const; 43 | virtual std::string getMimeType() const; 44 | virtual zim::writer::Url getRedirectUrl() const; 45 | virtual bool shouldIndex() const; 46 | virtual bool shouldCompress() const; 47 | virtual ~Article(){}; 48 | }; 49 | 50 | class MetadataArticle : public zim::writer::Article 51 | { 52 | protected: 53 | std::string id; 54 | 55 | public: 56 | explicit MetadataArticle(const std::string& id) : id(id) {}; 57 | virtual zim::writer::Url getUrl() const { return zim::writer::Url('M', id); } 58 | virtual zim::writer::Url getRedirectUrl() const { return zim::writer::Url(); } 59 | virtual bool isInvalid() const { return false; } 60 | virtual std::string getTitle() const { return ""; } 61 | virtual bool isRedirect() const { return false; } 62 | virtual bool isLinktarget() const { return false; } 63 | virtual bool isDeleted() const { return false; } 64 | virtual std::string getMimeType() const { return "text/plain"; } 65 | virtual bool shouldIndex() const { return false; } 66 | virtual bool shouldCompress() const { return true; } 67 | virtual std::string getFilename() const { return ""; } 68 | }; 69 | 70 | class SimpleMetadataArticle : public MetadataArticle 71 | { 72 | private: 73 | std::string value; 74 | 75 | public: 76 | explicit SimpleMetadataArticle(const std::string& id, 77 | const std::string& value); 78 | virtual zim::Blob getData() const 79 | { 80 | return zim::Blob(value.c_str(), value.size()); 81 | } 82 | virtual zim::size_type getSize() const 83 | { 84 | return value.size(); 85 | } 86 | }; 87 | 88 | class MetadataFaviconArticle : public MetadataArticle 89 | { 90 | private: 91 | zim::writer::Url redirectUrl; 92 | public: 93 | explicit MetadataFaviconArticle(zim::writer::Url value) 94 | : MetadataArticle(""), redirectUrl(value) {} 95 | virtual zim::writer::Url getUrl() const { return zim::writer::Url('-', "favicon"); } 96 | virtual bool isInvalid() const { return false; } 97 | virtual std::string getTitle() const { return ""; } 98 | virtual bool isRedirect() const { return true; } 99 | virtual std::string getMimeType() const { return "image/png"; } 100 | virtual zim::writer::Url getRedirectUrl() const { return redirectUrl; } 101 | virtual bool shouldCompress() const { return false; } 102 | virtual std::string getFilename() const { return ""; } 103 | virtual zim::Blob getData() const { return zim::Blob(); } 104 | virtual zim::size_type getSize() const { return 0; } 105 | }; 106 | 107 | class MetadataDateArticle : public MetadataArticle 108 | { 109 | private: 110 | mutable std::string data; 111 | void genDate() const; 112 | 113 | public: 114 | MetadataDateArticle(); 115 | virtual zim::Blob getData() const; 116 | virtual zim::size_type getSize() const; 117 | }; 118 | 119 | class FileArticle : public Article 120 | { 121 | private: 122 | mutable std::string data; 123 | mutable bool dataRead; 124 | bool invalid; 125 | std::string _getFilename() const; 126 | void readData() const; 127 | void parseAndAdaptHtml(bool detectRedirects); 128 | void adaptCss(); 129 | 130 | public: 131 | explicit FileArticle(const std::string& path, 132 | const bool detectRedirects = true); 133 | virtual zim::Blob getData() const; 134 | virtual bool isLinktarget() const { return false; } 135 | virtual bool isDeleted() const { return false; } 136 | virtual zim::size_type getSize() const; 137 | virtual std::string getFilename() const; 138 | virtual bool isInvalid() const; 139 | }; 140 | 141 | class RedirectArticle : public Article 142 | { 143 | public: 144 | explicit RedirectArticle(char ns, 145 | const std::string& url, 146 | const std::string& title, 147 | const zim::writer::Url& redirectUrl); 148 | virtual zim::Blob getData() const { return zim::Blob(); } 149 | virtual bool isRedirect() const { return true; } 150 | virtual bool isLinktarget() const { return false; } 151 | virtual bool isDeleted() const { return false; } 152 | virtual zim::size_type getSize() const { return 0; } 153 | virtual std::string getFilename() const { return ""; } 154 | }; 155 | 156 | #endif // OPENZIM_ZIMWRITERFS_ARTICLE_H 157 | -------------------------------------------------------------------------------- /src/zimcreatorfs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2016 Emmanuel Engelhart 3 | * Copyright 2016 Matthieu Gautier 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software 17 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 18 | * MA 02110-1301, USA. 19 | */ 20 | 21 | #include "zimcreatorfs.h" 22 | #include "article.h" 23 | #include "tools.h" 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | bool isVerbose(); 31 | 32 | zim::writer::Url ZimCreatorFS::getMainUrl() const 33 | { 34 | return zim::writer::Url('A', mainPage); 35 | } 36 | 37 | void ZimCreatorFS::add_redirectArticles_from_file(const std::string& path) 38 | { 39 | std::ifstream in_stream; 40 | std::string line; 41 | 42 | in_stream.open(path.c_str()); 43 | int line_number = 1; 44 | while (std::getline(in_stream, line)) { 45 | std::regex line_regex("(.)\\t(.+)\\t(.+)\\t(.+)"); 46 | std::smatch matches; 47 | if (!std::regex_search(line, matches, line_regex) || matches.size() != 5) { 48 | std::cerr << "zimwriterfs: line #" << line_number 49 | << " has invalid format in redirect file " << path << ": '" 50 | << line << "'" << std::endl; 51 | in_stream.close(); 52 | exit(1); 53 | } 54 | 55 | auto redirectArticle = std::make_shared( 56 | matches[1].str()[0], 57 | matches[2].str(), 58 | matches[3].str(), 59 | matches[4].str()); 60 | addArticle(redirectArticle); 61 | ++line_number; 62 | } 63 | in_stream.close(); 64 | } 65 | 66 | void ZimCreatorFS::visitDirectory(const std::string& path) 67 | { 68 | if (isVerbose()) 69 | std::cout << "Visiting directory " << path << std::endl; 70 | 71 | DIR* directory; 72 | 73 | /* Open directory */ 74 | directory = opendir(path.c_str()); 75 | if (directory == NULL) { 76 | std::cerr << "zimwriterfs: unable to open directory " << path << std::endl; 77 | exit(1); 78 | } 79 | 80 | /* Read directory content */ 81 | struct dirent* entry; 82 | while ((entry = readdir(directory)) != NULL) { 83 | std::string entryName = entry->d_name; 84 | 85 | /* Ignore this system navigation virtual directories */ 86 | if (entryName == "." || entryName == "..") 87 | continue; 88 | 89 | std::string fullEntryName = path + '/' + entryName; 90 | 91 | switch (entry->d_type) { 92 | case DT_REG: 93 | case DT_LNK: 94 | { 95 | addArticle(fullEntryName); 96 | } 97 | break; 98 | case DT_DIR: 99 | visitDirectory(fullEntryName); 100 | break; 101 | case DT_BLK: 102 | std::cerr << "Unable to deal with " << fullEntryName 103 | << " (this is a block device)" << std::endl; 104 | break; 105 | case DT_CHR: 106 | std::cerr << "Unable to deal with " << fullEntryName 107 | << " (this is a character device)" << std::endl; 108 | break; 109 | case DT_FIFO: 110 | std::cerr << "Unable to deal with " << fullEntryName 111 | << " (this is a named pipe)" << std::endl; 112 | break; 113 | case DT_SOCK: 114 | std::cerr << "Unable to deal with " << fullEntryName 115 | << " (this is a UNIX domain socket)" << std::endl; 116 | break; 117 | case DT_UNKNOWN: 118 | struct stat s; 119 | if (stat(fullEntryName.c_str(), &s) == 0) { 120 | if (S_ISREG(s.st_mode)) { 121 | addArticle(fullEntryName); 122 | } else if (S_ISDIR(s.st_mode)) { 123 | visitDirectory(fullEntryName); 124 | } else { 125 | std::cerr << "Unable to deal with " << fullEntryName 126 | << " (no clue what kind of file it is - from stat())" 127 | << std::endl; 128 | } 129 | } else { 130 | std::cerr << "Unable to stat " << fullEntryName << std::endl; 131 | } 132 | break; 133 | default: 134 | std::cerr << "Unable to deal with " << fullEntryName 135 | << " (no clue what kind of file it is)" << std::endl; 136 | break; 137 | } 138 | } 139 | 140 | closedir(directory); 141 | } 142 | 143 | void ZimCreatorFS::addMetadata(const std::string& metadata, const std::string& content) 144 | { 145 | auto article = std::make_shared(metadata, content); 146 | addArticle(article); 147 | } 148 | 149 | void ZimCreatorFS::addArticle(const std::string& path) 150 | { 151 | auto farticle = std::make_shared(path); 152 | if (farticle->isInvalid()) { 153 | return; 154 | } 155 | addArticle(farticle); 156 | } 157 | 158 | void ZimCreatorFS::addArticle(std::shared_ptr article) 159 | { 160 | Creator::addArticle(article); 161 | for (auto& handler: articleHandlers) { 162 | handler->handleArticle(article); 163 | } 164 | } 165 | 166 | void ZimCreatorFS::finishZimCreation() 167 | { 168 | for(auto& handler: articleHandlers) { 169 | Creator::addArticle(handler->getMetaArticle()); 170 | } 171 | Creator::finishZimCreation(); 172 | } 173 | 174 | void ZimCreatorFS::add_customHandler(IHandler* handler) 175 | { 176 | articleHandlers.push_back(handler); 177 | } 178 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | zimwriterfs (migrated to zim-tools repository) 2 | ============================================== 3 | 4 | 5 | [![latest release](https://img.shields.io/github/v/tag/openzim/zimwriterfs?label=latest%20release&sort=semver)](https://download.openzim.org/release/zimwriterfs/) 6 | [![Build Status](https://github.com/openzim/zimwriterfs/workflows/CI/badge.svg?query=branch%3Amaster)](https://github.com/openzim/zimwriterfs/actions?query=branch%3Amaster) 7 | [![Docker Build Status](https://img.shields.io/docker/build/openzim/zimwriterfs)](https://hub.docker.com/r/openzim/zimwriterfs) 8 | [![CodeFactor](https://www.codefactor.io/repository/github/openzim/zimwriterfs/badge)](https://www.codefactor.io/repository/github/openzim/zimwriterfs) 9 | [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) 10 | 11 | `zimwriterfs` is a console tool to create [ZIM](https://openzim.org) 12 | files from a locally-stored directory containing "self-sufficient" 13 | HTML content (with pictures, javascript and stylesheets). The result 14 | will contain all the files of the local directory compressed and 15 | merged in the ZIM file. Nothing more, nothing less. The generated file 16 | can be opened with a ZIM reader; [Kiwix](https://kiwix.org) is one 17 | example, but there are [others](https://openzim.org/wiki/ZIM_Readers). 18 | 19 | `zimwriterfs` works - for now - only on POSIX-compatible systems, you 20 | simply need to compile it and run it. The software does not need a lot 21 | of resources, but if you create a pretty big ZIM files, then it could 22 | take a while to complete. 23 | 24 | Disclaimer 25 | ---------- 26 | 27 | This document assumes you have a little knowledge about software 28 | compilation. If you experience difficulties with the dependencies or 29 | with the `zimwriterfs` compilation itself, we recommend to have a look 30 | to [kiwix-build](https://github.com/kiwix/kiwix-build). 31 | 32 | Preamble 33 | -------- 34 | 35 | Although `zimwriterfs` can be compiled/cross-compiled on/for many 36 | systems, the following documentation explains how to do it on POSIX 37 | ones. It is primarily though for GNU/Linux systems and has been tested 38 | on recent releases of Ubuntu and Fedora. 39 | 40 | Dependencies 41 | ------------ 42 | 43 | `zimwriterfs` relies on many third parts software libraries. They are 44 | prerequisites to the Zimwriterfs compilation. Following libraries 45 | need to be available: 46 | 47 | * [ZIM](https://openzim.org) (package `libzim-dev` on Debian/Ubuntu) 48 | * [Magic](https://www.darwinsys.com/file/) (package `libmagic-dev` on Debian/Ubuntu) 49 | * [Z](https://zlib.net/) (package `zlib1g-dev` on Debian/Ubuntu) 50 | * [Gumbo](https://github.com/google/gumbo-parser) (package `libgumbo-dev` on Debian/Ubuntu) 51 | * [ICU](http://site.icu-project.org/) (package `libicu-dev` on Debian/Ubuntu) 52 | 53 | These dependencies may or may not be packaged by your operating 54 | system. They may also be packaged but only in an older version. The 55 | compilation script will tell you if one of them is missing or too old. 56 | In the worse case, you will have to download and compile a more recent 57 | version by hand. 58 | 59 | If you want to install these dependencies locally, then ensure that 60 | meson (through `pkg-config`) will properly find them. 61 | 62 | Environment 63 | ----------- 64 | 65 | `zimwriterfs` builds using [Meson](https://mesonbuild.com/) version 66 | 0.39 or higher. Meson relies itself on Ninja, Pkg-config and few other 67 | compilation tools. 68 | 69 | Install first the few common compilation tools: 70 | * Meson 71 | * Ninja 72 | * Pkg-config 73 | 74 | These tools should be packaged if you use a cutting edge operating 75 | system. If not, have a look to the [Troubleshooting](#Troubleshooting) 76 | section. 77 | 78 | Compilation 79 | ----------- 80 | 81 | Once all dependencies are installed, you can compile `zimwriterfs` with: 82 | ```bash 83 | meson . build 84 | ninja -C build 85 | ``` 86 | 87 | By default, it will compile dynamic linked libraries. All binary files 88 | will be created in the "build" directory created automatically by 89 | Meson. If you want statically linked libraries, you can add 90 | `-Dstatic-linkage=true` option to the Meson command. 91 | 92 | Depending of you system, `ninja` may be called `ninja-build`. 93 | 94 | Installation 95 | ------------ 96 | 97 | If you want to install `zimwriterfs` and the headers you just have 98 | compiled on your system, here we go: 99 | ```bash 100 | ninja -C build install 101 | ``` 102 | 103 | You might need to run the command as root (or using 'sudo'), depending 104 | where you want to install the libraries. After the installation 105 | succeeded, you may need to run ldconfig (as root). 106 | 107 | Uninstallation 108 | -------------- 109 | 110 | If you want to uninstall `zimwriterfs`: 111 | ```bash 112 | ninja -C build uninstall 113 | ``` 114 | 115 | Like for the installation, you might need to run the command as root 116 | (or using 'sudo'). 117 | 118 | Binaries 119 | -------- 120 | 121 | Statically pre-compiled binaries are provided here 122 | https://download.openzim.org/release/zimwriterfs/. 123 | 124 | Docker 125 | ------ 126 | 127 | A Docker image with `zimwriterfs` can be built from the `docker` 128 | directory. The project maintains an official image available at 129 | https://hub.docker.com/r/openzim/mwoffliner. 130 | 131 | Troubleshooting 132 | --------------- 133 | 134 | If you need to install Meson "manually": 135 | ```bash 136 | virtualenv -p python3 ./ # Create virtualenv 137 | source bin/activate # Activate the virtualenv 138 | pip3 install meson # Install Meson 139 | hash -r # Refresh bash paths 140 | ``` 141 | 142 | If you need to install Ninja "manually": 143 | ```bash 144 | git clone git://github.com/ninja-build/ninja.git 145 | cd ninja 146 | git checkout release 147 | ./configure.py --bootstrap 148 | mkdir ../bin 149 | cp ninja ../bin 150 | cd .. 151 | ``` 152 | 153 | If the compilation still fails, you might need to get a more recent 154 | version of a dependency than the one packaged by your Linux 155 | distribution. Try then with a source tarball distributed by the 156 | problematic upstream project or even directly from the source code 157 | repository. 158 | 159 | License 160 | ------- 161 | 162 | [GPLv3](https://www.gnu.org/licenses/gpl-3.0) or later, see 163 | [LICENSE](LICENSE) for more details. 164 | -------------------------------------------------------------------------------- /src/article.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2016 Emmanuel Engelhart 3 | * Copyright 2016 Matthieu Gautier 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software 17 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 18 | * MA 02110-1301, USA. 19 | */ 20 | 21 | #include "article.h" 22 | #include "tools.h" 23 | 24 | #include 25 | #include 26 | #include 27 | 28 | extern std::string directoryPath; 29 | 30 | zim::writer::Url Article::getUrl() const 31 | { 32 | return zim::writer::Url(ns, url); 33 | } 34 | 35 | std::string Article::getTitle() const 36 | { 37 | return title; 38 | } 39 | 40 | bool Article::isRedirect() const 41 | { 42 | return !redirectUrl.empty(); 43 | } 44 | 45 | std::string Article::getMimeType() const 46 | { 47 | return mimeType; 48 | } 49 | 50 | zim::writer::Url Article::getRedirectUrl() const 51 | { 52 | return redirectUrl; 53 | } 54 | 55 | bool Article::shouldCompress() const 56 | { 57 | return getMimeType().find("text") == 0 58 | || getMimeType() == "application/javascript" 59 | || getMimeType() == "application/json" 60 | || getMimeType() == "image/svg+xml"; 61 | } 62 | 63 | bool Article::shouldIndex() const 64 | { 65 | return getMimeType().find("text/html") == 0; 66 | } 67 | 68 | void FileArticle::readData() const 69 | { 70 | data = getFileContent(_getFilename()); 71 | dataRead = true; 72 | } 73 | 74 | FileArticle::FileArticle(const std::string& path, const bool detectRedirects) 75 | : dataRead(false) 76 | { 77 | invalid = false; 78 | 79 | url = path.substr(directoryPath.size() + 1); 80 | 81 | /* mime-type */ 82 | mimeType = getMimeTypeForFile(url); 83 | 84 | /* namespace */ 85 | ns = getNamespaceForMimeType(mimeType)[0]; 86 | 87 | /* HTML specific code */ 88 | if ( mimeType.find("text/html") != std::string::npos 89 | || mimeType.find("text/css") != std::string::npos ) { 90 | readData(); 91 | } 92 | 93 | if ( mimeType.find("text/html") != std::string::npos ) { 94 | parseAndAdaptHtml(detectRedirects); 95 | } else if (mimeType.find("text/css") != std::string::npos) { 96 | adaptCss(); 97 | } 98 | } 99 | 100 | bool FileArticle::isInvalid() const 101 | { 102 | return invalid; 103 | } 104 | 105 | void FileArticle::parseAndAdaptHtml(bool detectRedirects) 106 | { 107 | GumboOutput* output = gumbo_parse(data.c_str()); 108 | GumboNode* root = output->root; 109 | 110 | /* Search the content of the tag in the HTML */ 111 | if (root->type == GUMBO_NODE_ELEMENT 112 | && root->v.element.children.length >= 2) { 113 | const GumboVector* root_children = &root->v.element.children; 114 | GumboNode* head = NULL; 115 | for (unsigned int i = 0; i < root_children->length; ++i) { 116 | GumboNode* child = (GumboNode*)(root_children->data[i]); 117 | if (child->type == GUMBO_NODE_ELEMENT 118 | && child->v.element.tag == GUMBO_TAG_HEAD) { 119 | head = child; 120 | break; 121 | } 122 | } 123 | 124 | if (head != NULL) { 125 | GumboVector* head_children = &head->v.element.children; 126 | for (unsigned int i = 0; i < head_children->length; ++i) { 127 | GumboNode* child = (GumboNode*)(head_children->data[i]); 128 | if (child->type == GUMBO_NODE_ELEMENT 129 | && child->v.element.tag == GUMBO_TAG_TITLE) { 130 | if (child->v.element.children.length == 1) { 131 | GumboNode* title_text 132 | = (GumboNode*)(child->v.element.children.data[0]); 133 | if (title_text->type == GUMBO_NODE_TEXT) { 134 | title = title_text->v.text.text; 135 | stripTitleInvalidChars(title); 136 | } 137 | } 138 | } 139 | } 140 | 141 | /* Detect if this is a redirection (if no redirects TSV file specified) 142 | */ 143 | std::string targetUrl; 144 | try { 145 | targetUrl = detectRedirects 146 | ? extractRedirectUrlFromHtml(head_children) 147 | : ""; 148 | } catch (std::string& error) { 149 | std::cerr << error << std::endl; 150 | } 151 | if (!targetUrl.empty()) { 152 | auto redirectUrl = computeAbsolutePath(url, decodeUrl(targetUrl)); 153 | if (!fileExists(directoryPath + "/" + redirectUrl)) { 154 | redirectUrl.clear(); 155 | invalid = true; 156 | } else { 157 | this->redirectUrl = zim::writer::Url(redirectUrl); 158 | } 159 | } 160 | 161 | /* If no title, then compute one from the filename */ 162 | if (title.empty()) { 163 | auto path = _getFilename(); 164 | auto found = path.rfind("/"); 165 | if (found != std::string::npos) { 166 | title = path.substr(found + 1); 167 | found = title.rfind("."); 168 | if (found != std::string::npos) { 169 | title = title.substr(0, found); 170 | } 171 | } else { 172 | title = path; 173 | } 174 | std::replace(title.begin(), title.end(), '_', ' '); 175 | } 176 | } 177 | } 178 | 179 | /* Update links in the html to let them still be valid */ 180 | std::map<std::string, bool> links; 181 | getLinks(root, links); 182 | std::string longUrl = std::string("/") + ns + "/" + url; 183 | 184 | /* If a link appearch to be duplicated in the HTML, it will 185 | occurs only one time in the links variable */ 186 | for (auto& linkPair: links) { 187 | auto target = linkPair.first; 188 | if (!target.empty() && target[0] != '#' && target[0] != '?' 189 | && target.substr(0, 5) != "data:") { 190 | replaceStringInPlace(data, 191 | "\"" + target + "\"", 192 | "\"" + computeNewUrl(url, longUrl, target) + "\""); 193 | } 194 | } 195 | gumbo_destroy_output(&kGumboDefaultOptions, output); 196 | } 197 | 198 | void FileArticle::adaptCss() { 199 | /* Rewrite url() values in the CSS */ 200 | size_t startPos = 0; 201 | size_t endPos = 0; 202 | std::string url; 203 | std::string longUrl = std::string("/") + ns + "/" + this->url; 204 | 205 | while ((startPos = data.find("url(", endPos)) 206 | && startPos != std::string::npos) { 207 | 208 | /* URL delimiters */ 209 | endPos = data.find(")", startPos); 210 | startPos = startPos + (data[startPos + 4] == '\'' 211 | || data[startPos + 4] == '"' 212 | ? 5 213 | : 4); 214 | endPos = endPos - (data[endPos - 1] == '\'' 215 | || data[endPos - 1] == '"' 216 | ? 1 217 | : 0); 218 | url = data.substr(startPos, endPos - startPos); 219 | std::string startDelimiter = data.substr(startPos - 1, 1); 220 | std::string endDelimiter = data.substr(endPos, 1); 221 | 222 | if (url.substr(0, 5) != "data:") { 223 | 224 | /* Deal with URL with arguments (using '? ') */ 225 | std::string path = url; 226 | size_t markPos = url.find("?"); 227 | if (markPos != std::string::npos) { 228 | path = url.substr(0, markPos); 229 | } 230 | 231 | /* Embeded fonts need to be inline because Kiwix is 232 | otherwise not able to load same because of the 233 | same-origin security */ 234 | std::string mimeType = getMimeTypeForFile(path); 235 | if (mimeType == "application/font-ttf" 236 | || mimeType == "application/font-woff" 237 | || mimeType == "application/font-woff2" 238 | || mimeType == "application/vnd.ms-opentype" 239 | || mimeType == "application/vnd.ms-fontobject") { 240 | try { 241 | std::string fontContent = getFileContent( 242 | directoryPath + "/" + computeAbsolutePath(this->url, path)); 243 | replaceStringInPlaceOnce( 244 | data, 245 | startDelimiter + url + endDelimiter, 246 | startDelimiter + "data:" + mimeType + ";base64," 247 | + base64_encode(reinterpret_cast<const unsigned char*>( 248 | fontContent.c_str()), 249 | fontContent.length()) 250 | + endDelimiter); 251 | } catch (...) { 252 | } 253 | } else { 254 | /* Deal with URL with arguments (using '? ') */ 255 | if (markPos != std::string::npos) { 256 | endDelimiter = url.substr(markPos, 1); 257 | } 258 | 259 | replaceStringInPlaceOnce( 260 | data, 261 | startDelimiter + url + endDelimiter, 262 | startDelimiter + computeNewUrl(this->url, longUrl, path) + endDelimiter); 263 | } 264 | } 265 | } 266 | } 267 | 268 | zim::Blob FileArticle::getData() const 269 | { 270 | if (!dataRead) 271 | readData(); 272 | 273 | return zim::Blob(data.data(), data.size()); 274 | } 275 | 276 | std::string FileArticle::_getFilename() const 277 | { 278 | return directoryPath + "/" + url; 279 | } 280 | 281 | std::string FileArticle::getFilename() const 282 | { 283 | // If data is read (because we changed the content), use the content 284 | // not the content of the filename. 285 | if (dataRead) 286 | return ""; 287 | return _getFilename(); 288 | } 289 | 290 | zim::size_type FileArticle::getSize() const 291 | { 292 | if (dataRead) { 293 | return data.size(); 294 | } 295 | 296 | std::ifstream in(_getFilename(), std::ios::binary|std::ios::ate); 297 | return in.tellg(); 298 | } 299 | 300 | RedirectArticle::RedirectArticle(char ns, 301 | const std::string& url, 302 | const std::string& title, 303 | const zim::writer::Url& redirectUrl) 304 | { 305 | this->ns = ns; 306 | this->url = url; 307 | this->title = title; 308 | this->redirectUrl = redirectUrl; 309 | mimeType = getMimeTypeForFile(redirectUrl.getUrl()); 310 | } 311 | 312 | SimpleMetadataArticle::SimpleMetadataArticle(const std::string& id, 313 | const std::string& value) 314 | : MetadataArticle(id), value(value) 315 | { 316 | } 317 | 318 | MetadataDateArticle::MetadataDateArticle() : MetadataArticle("Date") 319 | { 320 | } 321 | 322 | void MetadataDateArticle::genDate() const 323 | { 324 | time_t t = time(0); 325 | struct tm* now = localtime(&t); 326 | std::stringstream stream; 327 | stream << (now->tm_year + 1900) << '-' << std::setw(2) << std::setfill('0') 328 | << (now->tm_mon + 1) << '-' << std::setw(2) << std::setfill('0') 329 | << now->tm_mday; 330 | data = stream.str(); 331 | } 332 | 333 | zim::Blob MetadataDateArticle::getData() const 334 | { 335 | if (data.empty()) { 336 | genDate(); 337 | } 338 | return zim::Blob(data.data(), data.size()); 339 | } 340 | 341 | zim::size_type MetadataDateArticle::getSize() const 342 | { 343 | if(data.empty()) { 344 | genDate(); 345 | } 346 | return data.size(); 347 | } 348 | 349 | -------------------------------------------------------------------------------- /src/zimwriterfs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2016 Emmanuel Engelhart <kelson@kiwix.org> 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 3 of the License, or 7 | * 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 Street, Fifth Floor, Boston, 17 | * MA 02110-1301, USA. 18 | */ 19 | 20 | /* Includes */ 21 | #include <getopt.h> 22 | #include <pthread.h> 23 | #include <stdio.h> 24 | #include <sys/types.h> 25 | #include <unistd.h> 26 | #include <ctime> 27 | 28 | #include <magic.h> 29 | #include <cstdio> 30 | #include <queue> 31 | 32 | #include "article.h" 33 | #include "zimcreatorfs.h" 34 | #include "mimetypecounter.h" 35 | #include "queue.h" 36 | #include "tools.h" 37 | 38 | /* Check for version number */ 39 | #ifndef VERSION 40 | #define VERSION "UNKNOWN" 41 | #endif 42 | 43 | /* Global access strings */ 44 | std::string language; 45 | std::string creator; 46 | std::string publisher; 47 | std::string title; 48 | std::string tags; 49 | std::string flavour; 50 | std::string scraper; 51 | std::string name; 52 | std::string source; 53 | std::string description; 54 | std::string welcome; 55 | std::string favicon; 56 | std::string directoryPath; 57 | std::string redirectsPath; 58 | std::string zimPath; 59 | 60 | bool verboseFlag = false; 61 | pthread_mutex_t verboseMutex; 62 | bool inflateHtmlFlag = false; 63 | bool uniqueNamespace = false; 64 | bool withoutFTIndex = false; 65 | 66 | magic_t magic; 67 | 68 | bool isVerbose() 69 | { 70 | pthread_mutex_lock(&verboseMutex); 71 | bool retVal = verboseFlag; 72 | pthread_mutex_unlock(&verboseMutex); 73 | return retVal; 74 | } 75 | 76 | /* Print current version defined in the macro */ 77 | void version() 78 | { 79 | // Access the version number through meson macro define 80 | std::cout << "Version: " << "v" << VERSION << std::endl; 81 | std::cout << "\tSee -h or --help argument flags for further argument options" << std::endl; 82 | std::cout << "\tCopyright 2013-2016 Emmanuel Engelhart <kelson@kiwix.org>" << std::endl; 83 | } 84 | 85 | /* Print correct console usage options */ 86 | void usage() 87 | { 88 | std::cout << "Usage: zimwriterfs [mandatory arguments] [optional arguments] " 89 | "HTML_DIRECTORY ZIM_FILE" 90 | << std::endl; 91 | std::cout << std::endl; 92 | 93 | std::cout << "Purpose:" << std::endl; 94 | std::cout << "\tPacking all files (HTML/JS/CSS/JPEG/WEBM/...) belonging to a " 95 | "directory in a ZIM file." 96 | << std::endl; 97 | std::cout << std::endl; 98 | 99 | std::cout << "Mandatory arguments:" << std::endl; 100 | std::cout << "\t-w, --welcome\t\tpath of default/main HTML page. The path " 101 | "must be relative to HTML_DIRECTORY." 102 | << std::endl; 103 | std::cout << "\t-f, --favicon\t\tpath of ZIM file favicon. The path must be " 104 | "relative to HTML_DIRECTORY and the image a 48x48 PNG." 105 | << std::endl; 106 | std::cout << "\t-l, --language\t\tlanguage code of the content in ISO639-3" 107 | << std::endl; 108 | std::cout << "\t-t, --title\t\ttitle of the ZIM file" << std::endl; 109 | std::cout << "\t-d, --description\tshort description of the content" 110 | << std::endl; 111 | std::cout << "\t-c, --creator\t\tcreator(s) of the content" << std::endl; 112 | std::cout << "\t-p, --publisher\t\tcreator of the ZIM file itself" 113 | << std::endl; 114 | std::cout << std::endl; 115 | std::cout << "\tHTML_DIRECTORY\t\tpath of the directory containing " 116 | "the HTML pages you want to put in the ZIM file." 117 | << std::endl; 118 | std::cout << "\tZIM_FILE\t\tpath of the ZIM file you want to obtain." 119 | << std::endl; 120 | std::cout << std::endl; 121 | 122 | std::cout << "Optional arguments:" << std::endl; 123 | std::cout << "\t-v, --verbose\t\tprint processing details on STDOUT" 124 | << std::endl; 125 | std::cout << "\t-h, --help\t\tprint this help" << std::endl; 126 | std::cout << "\t-V, --version\t\tprint the version number" << std::endl; 127 | std::cout 128 | << "\t-m, --minChunkSize\tnumber of bytes per ZIM cluster (default: 2048)" 129 | << std::endl; 130 | std::cout << "\t-x, --inflateHtml\ttry to inflate HTML files before packing " 131 | "(*.html, *.htm, ...)" 132 | << std::endl; 133 | std::cout << "\t-u, --uniqueNamespace\tput everything in the same namespace " 134 | "'A'. Might be necessary to avoid problems with " 135 | "dynamic/javascript data loading." 136 | << std::endl; 137 | std::cout << "\t-r, --redirects\t\tpath to a TSV file containing a list of " 138 | "redirects (namespace url title target_url)." 139 | << std::endl; 140 | std::cout 141 | << "\t-j, --withoutFTIndex\tdon't create and add a fulltext index of the content to the ZIM." 142 | << std::endl; 143 | std::cout << "\t-a, --tags\t\ttags - semicolon separated" << std::endl; 144 | std::cout << "\t-e, --source\t\tcontent source URL" << std::endl; 145 | std::cout << "\t-n, --name\t\tcustom (version independent) identifier for " 146 | "the content" 147 | << std::endl; 148 | std::cout << "\t-o, --flavour\t\tcustom (version independent) content flavour" 149 | << std::endl; 150 | std::cout << "\t-s, --scraper\t\tname & version of tool used to produce HTML content" 151 | << std::endl; 152 | std::cout << std::endl; 153 | 154 | std::cout << "Example:" << std::endl; 155 | std::cout 156 | << "\tzimwriterfs --welcome=index.html --favicon=m/favicon.png --language=fra --title=foobar --description=mydescription \\\n\t\t\ 157 | --creator=Wikipedia --publisher=Kiwix ./my_project_html_directory my_project.zim" 158 | << std::endl; 159 | std::cout << std::endl; 160 | 161 | std::cout << "Documentation:" << std::endl; 162 | std::cout << "\tzimwriterfs source code: https://github.com/openzim/zimwriterfs" 163 | << std::endl; 164 | std::cout << "\tZIM format: https://openzim.org" << std::endl; 165 | std::cout << std::endl; 166 | } 167 | 168 | /* Main program entry point */ 169 | int main(int argc, char** argv) 170 | { 171 | int minChunkSize = 2048; 172 | 173 | /* Argument parsing */ 174 | static struct option long_options[] 175 | = {{"help", no_argument, 0, 'h'}, 176 | {"verbose", no_argument, 0, 'v'}, 177 | {"version", no_argument, 0, 'V'}, 178 | {"welcome", required_argument, 0, 'w'}, 179 | {"minchunksize", required_argument, 0, 'm'}, 180 | {"name", required_argument, 0, 'n'}, 181 | {"source", required_argument, 0, 'e'}, 182 | {"flavour", required_argument, 0, 'o'}, 183 | {"scraper", required_argument, 0, 's'}, 184 | {"redirects", required_argument, 0, 'r'}, 185 | {"inflateHtml", no_argument, 0, 'x'}, 186 | {"uniqueNamespace", no_argument, 0, 'u'}, 187 | {"favicon", required_argument, 0, 'f'}, 188 | {"language", required_argument, 0, 'l'}, 189 | {"title", required_argument, 0, 't'}, 190 | {"tags", required_argument, 0, 'a'}, 191 | {"description", required_argument, 0, 'd'}, 192 | {"creator", required_argument, 0, 'c'}, 193 | {"publisher", required_argument, 0, 'p'}, 194 | {"withoutFTIndex", no_argument, 0, 'j'}, 195 | 196 | // Only for backward compatibility 197 | {"withFullTextIndex", no_argument, 0, 'i'}, 198 | 199 | {0, 0, 0, 0}}; 200 | int option_index = 0; 201 | int c; 202 | 203 | do { 204 | c = getopt_long( 205 | argc, argv, "hVvijxuw:m:f:t:d:c:l:p:r:e:n:", long_options, &option_index); 206 | 207 | if (c != -1) { 208 | switch (c) { 209 | case 'a': 210 | tags = optarg; 211 | break; 212 | case 'V': 213 | version(); 214 | exit(0); 215 | break; 216 | case 'h': 217 | usage(); 218 | exit(0); 219 | break; 220 | case 'v': 221 | verboseFlag = true; 222 | break; 223 | case 'x': 224 | inflateHtmlFlag = true; 225 | break; 226 | case 'c': 227 | creator = optarg; 228 | break; 229 | case 'd': 230 | description = optarg; 231 | break; 232 | case 'f': 233 | favicon = optarg; 234 | break; 235 | case 'i': 236 | withoutFTIndex = false; 237 | break; 238 | case 'j': 239 | withoutFTIndex = true; 240 | break; 241 | case 'l': 242 | language = optarg; 243 | break; 244 | case 'm': 245 | minChunkSize = atoi(optarg); 246 | break; 247 | case 'n': 248 | name = optarg; 249 | break; 250 | case 'e': 251 | source = optarg; 252 | break; 253 | case 'o': 254 | flavour = optarg; 255 | break; 256 | case 's': 257 | scraper = optarg; 258 | break; 259 | case 'p': 260 | publisher = optarg; 261 | break; 262 | case 'r': 263 | redirectsPath = optarg; 264 | break; 265 | case 't': 266 | title = optarg; 267 | break; 268 | case 'u': 269 | uniqueNamespace = true; 270 | break; 271 | case 'w': 272 | welcome = optarg; 273 | break; 274 | } 275 | } 276 | } while (c != -1); 277 | 278 | while (optind < argc) { 279 | if (directoryPath.empty()) { 280 | directoryPath = argv[optind++]; 281 | } else if (zimPath.empty()) { 282 | zimPath = argv[optind++]; 283 | } else { 284 | break; 285 | } 286 | } 287 | 288 | if (directoryPath.empty() || zimPath.empty() || creator.empty() 289 | || publisher.empty() 290 | || description.empty() 291 | || language.empty() 292 | || welcome.empty() 293 | || favicon.empty()) { 294 | if (argc > 1) 295 | std::cerr << "zimwriterfs: too few arguments!" << std::endl; 296 | usage(); 297 | exit(1); 298 | } 299 | 300 | /* Check arguments */ 301 | if (directoryPath[directoryPath.length() - 1] == '/') { 302 | directoryPath = directoryPath.substr(0, directoryPath.length() - 1); 303 | } 304 | 305 | /* Check metadata */ 306 | if (!fileExists(directoryPath + "/" + welcome)) { 307 | std::cerr << "zimwriterfs: unable to find welcome page at '" 308 | << directoryPath << "/" << welcome 309 | << "'. --welcome path/value must be relative to HTML_DIRECTORY." 310 | << std::endl; 311 | exit(1); 312 | } 313 | 314 | if (!fileExists(directoryPath + "/" + favicon)) { 315 | std::cerr << "zimwriterfs: unable to find favicon at " << directoryPath 316 | << "/" << favicon 317 | << "'. --favicon path/value must be relative to HTML_DIRECTORY." 318 | << std::endl; 319 | exit(1); 320 | } 321 | 322 | /* System tags */ 323 | tags += tags.empty() ? "" : ";"; 324 | if (withoutFTIndex) { 325 | tags += "_ftindex:no"; 326 | } else { 327 | tags += "_ftindex:yes"; 328 | tags += ";_ftindex"; // For backward compatibility 329 | } 330 | 331 | ZimCreatorFS zimCreator(welcome, isVerbose()); 332 | 333 | zimCreator.setMinChunkSize(minChunkSize); 334 | zimCreator.setIndexing(!withoutFTIndex, language); 335 | zimCreator.startZimCreation(zimPath); 336 | 337 | zimCreator.addMetadata("Language", language); 338 | zimCreator.addMetadata("Publisher", publisher); 339 | zimCreator.addMetadata("Creator", creator); 340 | zimCreator.addMetadata("Title", title); 341 | zimCreator.addMetadata("Description", description); 342 | zimCreator.addMetadata("Name", name); 343 | zimCreator.addMetadata("Source", source); 344 | zimCreator.addMetadata("Flavour", flavour); 345 | zimCreator.addMetadata("Scraper", scraper); 346 | zimCreator.addMetadata("Tags", tags); 347 | zimCreator.addArticle(std::make_shared<MetadataDateArticle>()); 348 | zimCreator.addArticle(std::make_shared<MetadataFaviconArticle>(zim::writer::Url('I', favicon))); 349 | 350 | /* Init */ 351 | magic = magic_open(MAGIC_MIME); 352 | magic_load(magic, NULL); 353 | pthread_mutex_init(&verboseMutex, NULL); 354 | 355 | /* Directory visitor */ 356 | MimetypeCounter mimetypeCounter; 357 | zimCreator.add_customHandler(&mimetypeCounter); 358 | zimCreator.visitDirectory(directoryPath); 359 | 360 | /* Check redirects file and read it if necessary*/ 361 | if (!redirectsPath.empty()) { 362 | if (!fileExists(redirectsPath)) { 363 | std::cerr << "zimwriterfs: unable to find redirects TSV file at '" 364 | << redirectsPath << "'. Verify --redirects path/value." 365 | << std::endl; 366 | exit(1); 367 | } else { 368 | if (isVerbose()) 369 | std::cout << "Reading redirects TSV file " << redirectsPath << "..." 370 | << std::endl; 371 | 372 | zimCreator.add_redirectArticles_from_file(redirectsPath); 373 | } 374 | } 375 | zimCreator.finishZimCreation(); 376 | 377 | magic_close(magic); 378 | /* Destroy mutex */ 379 | pthread_mutex_destroy(&verboseMutex); 380 | } 381 | -------------------------------------------------------------------------------- /src/tools.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2016 Emmanuel Engelhart <kelson@kiwix.org> 3 | * Copyright 2016 Matthieu Gautier <mgautier@kymeria.fr> 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software 17 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 18 | * MA 02110-1301, USA. 19 | */ 20 | 21 | #include "tools.h" 22 | 23 | #include <dirent.h> 24 | #include <magic.h> 25 | #include <string.h> 26 | #include <sys/stat.h> 27 | #include <zlib.h> 28 | #include <cerrno> 29 | #include <fstream> 30 | #include <iostream> 31 | #include <sstream> 32 | #include <stdexcept> 33 | #include <vector> 34 | #include <memory> 35 | 36 | #include <unicode/translit.h> 37 | #include <unicode/ucnv.h> 38 | 39 | #ifdef _WIN32 40 | #define SEPARATOR "\\" 41 | #else 42 | #define SEPARATOR "/" 43 | #endif 44 | 45 | /* Init file extensions hash */ 46 | static std::map<std::string, std::string> _create_extMimeTypes() 47 | { 48 | std::map<std::string, std::string> extMimeTypes; 49 | extMimeTypes["HTML"] = "text/html"; 50 | extMimeTypes["html"] = "text/html"; 51 | extMimeTypes["HTM"] = "text/html"; 52 | extMimeTypes["htm"] = "text/html"; 53 | extMimeTypes["PNG"] = "image/png"; 54 | extMimeTypes["png"] = "image/png"; 55 | extMimeTypes["TIFF"] = "image/tiff"; 56 | extMimeTypes["tiff"] = "image/tiff"; 57 | extMimeTypes["TIF"] = "image/tiff"; 58 | extMimeTypes["tif"] = "image/tiff"; 59 | extMimeTypes["JPEG"] = "image/jpeg"; 60 | extMimeTypes["jpeg"] = "image/jpeg"; 61 | extMimeTypes["JPG"] = "image/jpeg"; 62 | extMimeTypes["jpg"] = "image/jpeg"; 63 | extMimeTypes["GIF"] = "image/gif"; 64 | extMimeTypes["gif"] = "image/gif"; 65 | extMimeTypes["SVG"] = "image/svg+xml"; 66 | extMimeTypes["svg"] = "image/svg+xml"; 67 | extMimeTypes["TXT"] = "text/plain"; 68 | extMimeTypes["txt"] = "text/plain"; 69 | extMimeTypes["XML"] = "text/xml"; 70 | extMimeTypes["xml"] = "text/xml"; 71 | extMimeTypes["EPUB"] = "application/epub+zip"; 72 | extMimeTypes["epub"] = "application/epub+zip"; 73 | extMimeTypes["PDF"] = "application/pdf"; 74 | extMimeTypes["pdf"] = "application/pdf"; 75 | extMimeTypes["OGG"] = "audio/ogg"; 76 | extMimeTypes["ogg"] = "audio/ogg"; 77 | extMimeTypes["OGV"] = "video/ogg"; 78 | extMimeTypes["ogv"] = "video/ogg"; 79 | extMimeTypes["JS"] = "application/javascript"; 80 | extMimeTypes["js"] = "application/javascript"; 81 | extMimeTypes["JSON"] = "application/json"; 82 | extMimeTypes["json"] = "application/json"; 83 | extMimeTypes["CSS"] = "text/css"; 84 | extMimeTypes["css"] = "text/css"; 85 | extMimeTypes["otf"] = "application/vnd.ms-opentype"; 86 | extMimeTypes["OTF"] = "application/vnd.ms-opentype"; 87 | extMimeTypes["eot"] = "application/vnd.ms-fontobject"; 88 | extMimeTypes["EOT"] = "application/vnd.ms-fontobject"; 89 | extMimeTypes["ttf"] = "application/font-ttf"; 90 | extMimeTypes["TTF"] = "application/font-ttf"; 91 | extMimeTypes["woff"] = "application/font-woff"; 92 | extMimeTypes["WOFF"] = "application/font-woff"; 93 | extMimeTypes["woff2"] = "application/font-woff2"; 94 | extMimeTypes["WOFF2"] = "application/font-woff2"; 95 | extMimeTypes["vtt"] = "text/vtt"; 96 | extMimeTypes["VTT"] = "text/vtt"; 97 | extMimeTypes["webm"] = "video/webm"; 98 | extMimeTypes["WEBM"] = "video/webm"; 99 | extMimeTypes["mp4"] = "video/mp4"; 100 | extMimeTypes["MP4"] = "video/mp4"; 101 | extMimeTypes["doc"] = "application/msword"; 102 | extMimeTypes["DOC"] = "application/msword"; 103 | extMimeTypes["docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; 104 | extMimeTypes["DOCX"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; 105 | extMimeTypes["ppt"] = "application/vnd.ms-powerpoint"; 106 | extMimeTypes["PPT"] = "application/vnd.ms-powerpoint"; 107 | extMimeTypes["odt"] = "application/vnd.oasis.opendocument.text"; 108 | extMimeTypes["ODT"] = "application/vnd.oasis.opendocument.text"; 109 | extMimeTypes["odp"] = "application/vnd.oasis.opendocument.text"; 110 | extMimeTypes["ODP"] = "application/vnd.oasis.opendocument.text"; 111 | extMimeTypes["zip"] = "application/zip"; 112 | extMimeTypes["ZIP"] = "application/zip"; 113 | extMimeTypes["wasm"] = "application/wasm"; 114 | extMimeTypes["WASM"] = "application/wasm"; 115 | 116 | return extMimeTypes; 117 | } 118 | 119 | static std::map<std::string, std::string> extMimeTypes = _create_extMimeTypes(); 120 | 121 | static std::map<std::string, std::string> fileMimeTypes; 122 | 123 | extern std::string directoryPath; 124 | extern bool inflateHtmlFlag; 125 | extern bool uniqueNamespace; 126 | extern magic_t magic; 127 | 128 | /* Decompress an STL string using zlib and return the original data. */ 129 | inline std::string inflateString(const std::string& str) 130 | { 131 | z_stream zs; // z_stream is zlib's control structure 132 | memset(&zs, 0, sizeof(zs)); 133 | 134 | if (inflateInit(&zs) != Z_OK) 135 | throw(std::runtime_error("inflateInit failed while decompressing.")); 136 | 137 | zs.next_in = (Bytef*)str.data(); 138 | zs.avail_in = str.size(); 139 | 140 | int ret; 141 | char outbuffer[32768]; 142 | std::string outstring; 143 | 144 | // get the decompressed bytes blockwise using repeated calls to inflate 145 | do { 146 | zs.next_out = reinterpret_cast<Bytef*>(outbuffer); 147 | zs.avail_out = sizeof(outbuffer); 148 | 149 | ret = inflate(&zs, 0); 150 | 151 | if (outstring.size() < zs.total_out) { 152 | outstring.append(outbuffer, zs.total_out - outstring.size()); 153 | } 154 | } while (ret == Z_OK); 155 | 156 | inflateEnd(&zs); 157 | 158 | if (ret != Z_STREAM_END) { // an error occurred that was not EOF 159 | std::ostringstream oss; 160 | oss << "Exception during zlib decompression: (" << ret << ") " << zs.msg; 161 | throw(std::runtime_error(oss.str())); 162 | } 163 | 164 | return outstring; 165 | } 166 | 167 | inline bool seemsToBeHtml(const std::string& path) 168 | { 169 | if (path.find_last_of(".") != std::string::npos) { 170 | std::string mimeType = path.substr(path.find_last_of(".") + 1); 171 | if (extMimeTypes.find(mimeType) != extMimeTypes.end()) { 172 | return "text/html" == extMimeTypes[mimeType]; 173 | } 174 | } 175 | 176 | return false; 177 | } 178 | 179 | std::string getFileContent(const std::string& path) 180 | { 181 | std::ifstream in(path, std::ios::binary| std::ios::ate); 182 | if (in) { 183 | std::string contents; 184 | contents.resize(in.tellg()); 185 | in.seekg(0, std::ios::beg); 186 | in.read(&contents[0], contents.size()); 187 | in.close(); 188 | 189 | /* Inflate if necessary */ 190 | if (inflateHtmlFlag && seemsToBeHtml(path)) { 191 | try { 192 | contents = inflateString(contents); 193 | } catch (...) { 194 | std::cerr << "Can not initialize inflate stream for: " << path 195 | << std::endl; 196 | } 197 | } 198 | return (contents); 199 | } 200 | std::cerr << "zimwriterfs: unable to open file at path: " << path 201 | << std::endl; 202 | throw(errno); 203 | } 204 | 205 | unsigned int getFileSize(const std::string& path) 206 | { 207 | struct stat filestatus; 208 | stat(path.c_str(), &filestatus); 209 | return filestatus.st_size; 210 | } 211 | 212 | bool fileExists(const std::string& path) 213 | { 214 | bool flag = false; 215 | std::fstream fin; 216 | fin.open(path.c_str(), std::ios::in); 217 | if (fin.is_open()) { 218 | flag = true; 219 | } 220 | fin.close(); 221 | return flag; 222 | } 223 | 224 | /* base64 */ 225 | static const std::string base64_chars 226 | = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 227 | "abcdefghijklmnopqrstuvwxyz" 228 | "0123456789+/"; 229 | 230 | std::string base64_encode(unsigned char const* bytes_to_encode, 231 | unsigned int in_len) 232 | { 233 | std::string ret; 234 | int i = 0; 235 | int j = 0; 236 | unsigned char char_array_3[3]; 237 | unsigned char char_array_4[4]; 238 | 239 | while (in_len--) { 240 | char_array_3[i++] = *(bytes_to_encode++); 241 | if (i == 3) { 242 | char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; 243 | char_array_4[1] 244 | = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); 245 | char_array_4[2] 246 | = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); 247 | char_array_4[3] = char_array_3[2] & 0x3f; 248 | 249 | for (i = 0; (i < 4); i++) 250 | ret += base64_chars[char_array_4[i]]; 251 | i = 0; 252 | } 253 | } 254 | 255 | if (i) { 256 | for (j = i; j < 3; j++) 257 | char_array_3[j] = '\0'; 258 | 259 | char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; 260 | char_array_4[1] 261 | = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); 262 | char_array_4[2] 263 | = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); 264 | char_array_4[3] = char_array_3[2] & 0x3f; 265 | 266 | for (j = 0; (j < i + 1); j++) 267 | ret += base64_chars[char_array_4[j]]; 268 | 269 | while ((i++ < 3)) 270 | ret += '='; 271 | } 272 | 273 | return ret; 274 | } 275 | 276 | static char charFromHex(std::string a) 277 | { 278 | std::istringstream Blat(a); 279 | int Z; 280 | Blat >> std::hex >> Z; 281 | return char(Z); 282 | } 283 | 284 | std::string decodeUrl(const std::string& originalUrl) 285 | { 286 | std::string url = originalUrl; 287 | std::string::size_type pos = 0; 288 | while ((pos = url.find('%', pos)) != std::string::npos 289 | && pos + 2 < url.length()) { 290 | url.replace(pos, 3, 1, charFromHex(url.substr(pos + 1, 2))); 291 | ++pos; 292 | } 293 | return url; 294 | } 295 | 296 | std::string removeLastPathElement(const std::string& path, 297 | const bool removePreSeparator, 298 | const bool removePostSeparator) 299 | { 300 | std::string newPath = path; 301 | size_t offset = newPath.find_last_of(SEPARATOR); 302 | 303 | if (removePreSeparator && offset == newPath.length() - 1) { 304 | newPath = newPath.substr(0, offset); 305 | offset = newPath.find_last_of(SEPARATOR); 306 | } 307 | newPath = removePostSeparator ? newPath.substr(0, offset) 308 | : newPath.substr(0, offset + 1); 309 | 310 | return newPath; 311 | } 312 | 313 | /* Split string in a token array */ 314 | std::vector<std::string> split(const std::string& str, 315 | const std::string& delims = " *-") 316 | { 317 | std::string::size_type lastPos = str.find_first_not_of(delims, 0); 318 | std::string::size_type pos = str.find_first_of(delims, lastPos); 319 | std::vector<std::string> tokens; 320 | 321 | while (std::string::npos != pos || std::string::npos != lastPos) { 322 | tokens.push_back(str.substr(lastPos, pos - lastPos)); 323 | lastPos = str.find_first_not_of(delims, pos); 324 | pos = str.find_first_of(delims, lastPos); 325 | } 326 | 327 | return tokens; 328 | } 329 | 330 | std::vector<std::string> split(const char* lhs, const char* rhs) 331 | { 332 | const std::string m1(lhs), m2(rhs); 333 | return split(m1, m2); 334 | } 335 | 336 | std::vector<std::string> split(const char* lhs, const std::string& rhs) 337 | { 338 | return split(lhs, rhs.c_str()); 339 | } 340 | 341 | std::vector<std::string> split(const std::string& lhs, const char* rhs) 342 | { 343 | return split(lhs.c_str(), rhs); 344 | } 345 | 346 | /* Warning: the relative path must be with slashes */ 347 | std::string computeAbsolutePath(const std::string& path, 348 | const std::string& relativePath) 349 | { 350 | /* Remove leaf part of the path if not already a directory */ 351 | std::string absolutePath = path[path.length() - 1] == '/' 352 | ? path 353 | : removeLastPathElement(path, false, false); 354 | 355 | /* Go through relative path */ 356 | std::vector<std::string> relativePathElements; 357 | std::stringstream relativePathStream(relativePath); 358 | std::string relativePathItem; 359 | while (std::getline(relativePathStream, relativePathItem, '/')) { 360 | if (relativePathItem == "..") { 361 | absolutePath = removeLastPathElement(absolutePath, true, false); 362 | } else if (!relativePathItem.empty() && relativePathItem != ".") { 363 | absolutePath += relativePathItem; 364 | absolutePath += "/"; 365 | } 366 | } 367 | 368 | /* Remove wront trailing / */ 369 | return absolutePath.substr(0, absolutePath.length() - 1); 370 | } 371 | 372 | /* Warning: the relative path must be with slashes */ 373 | std::string computeRelativePath(const std::string path, 374 | const std::string absolutePath) 375 | { 376 | std::vector<std::string> pathParts = split(path, "/"); 377 | std::vector<std::string> absolutePathParts = split(absolutePath, "/"); 378 | 379 | unsigned int commonCount = 0; 380 | while (commonCount < pathParts.size() 381 | && commonCount < absolutePathParts.size() 382 | && pathParts[commonCount] == absolutePathParts[commonCount]) { 383 | if (!pathParts[commonCount].empty()) { 384 | commonCount++; 385 | } 386 | } 387 | 388 | std::string relativePath; 389 | for (unsigned int i = commonCount; i < pathParts.size() - 1; i++) { 390 | relativePath += "../"; 391 | } 392 | 393 | for (unsigned int i = commonCount; i < absolutePathParts.size(); i++) { 394 | relativePath += absolutePathParts[i]; 395 | relativePath += i + 1 < absolutePathParts.size() ? "/" : ""; 396 | } 397 | 398 | return relativePath; 399 | } 400 | 401 | static bool isLocalUrl(const std::string url) 402 | { 403 | if (url.find(":") != std::string::npos) { 404 | return (!(url.find("://") != std::string::npos || url.find("//") == 0 405 | || url.find("tel:") == 0 406 | || url.find("geo:") == 0 407 | || url.find("javascript:") == 0 408 | || url.find("mailto:") == 0)); 409 | } 410 | return true; 411 | } 412 | 413 | std::string extractRedirectUrlFromHtml(const GumboVector* head_children) 414 | { 415 | std::string url; 416 | 417 | for (unsigned int i = 0; i < head_children->length; ++i) { 418 | GumboNode* child = (GumboNode*)(head_children->data[i]); 419 | if (child->type == GUMBO_NODE_ELEMENT 420 | && child->v.element.tag == GUMBO_TAG_META) { 421 | GumboAttribute* attribute; 422 | if ((attribute 423 | = gumbo_get_attribute(&child->v.element.attributes, "http-equiv")) 424 | != NULL) { 425 | if (!strcmp(attribute->value, "refresh")) { 426 | if ((attribute 427 | = gumbo_get_attribute(&child->v.element.attributes, "content")) 428 | != NULL) { 429 | std::string targetUrl = attribute->value; 430 | std::size_t found = targetUrl.find("URL=") != std::string::npos 431 | ? targetUrl.find("URL=") 432 | : targetUrl.find("url="); 433 | if (found != std::string::npos) { 434 | url = targetUrl.substr(found + 4); 435 | } else { 436 | throw std::string( 437 | "Unable to find the redirect/refresh target url from the " 438 | "HTML DOM"); 439 | } 440 | } 441 | } 442 | } 443 | } 444 | } 445 | 446 | return url; 447 | } 448 | 449 | void getLinks(GumboNode* node, std::map<std::string, bool>& links) 450 | { 451 | if (node->type != GUMBO_NODE_ELEMENT) { 452 | return; 453 | } 454 | 455 | GumboAttribute* attribute = NULL; 456 | attribute = gumbo_get_attribute(&node->v.element.attributes, "href"); 457 | if (attribute == NULL) { 458 | attribute = gumbo_get_attribute(&node->v.element.attributes, "src"); 459 | } 460 | if (attribute == NULL) { 461 | attribute = gumbo_get_attribute(&node->v.element.attributes, "poster"); 462 | } 463 | 464 | if (attribute != NULL && isLocalUrl(attribute->value)) { 465 | links[attribute->value] = true; 466 | } 467 | 468 | GumboVector* children = &node->v.element.children; 469 | for (unsigned int i = 0; i < children->length; ++i) { 470 | getLinks(static_cast<GumboNode*>(children->data[i]), links); 471 | } 472 | } 473 | 474 | void replaceStringInPlaceOnce(std::string& subject, 475 | const std::string& search, 476 | const std::string& replace) 477 | { 478 | size_t pos = subject.find(search, 0); 479 | if (pos != std::string::npos) { 480 | subject.replace(pos, search.length(), replace); 481 | } 482 | } 483 | 484 | void replaceStringInPlace(std::string& subject, 485 | const std::string& search, 486 | const std::string& replace) 487 | { 488 | size_t pos = 0; 489 | while ((pos = subject.find(search, pos)) != std::string::npos) { 490 | subject.replace(pos, search.length(), replace); 491 | pos += replace.length(); 492 | } 493 | 494 | return; 495 | } 496 | 497 | void stripTitleInvalidChars(std::string& str) 498 | { 499 | /* Remove unicode orientation invisible characters */ 500 | replaceStringInPlace(str, "\u202A", ""); 501 | replaceStringInPlace(str, "\u202C", ""); 502 | } 503 | 504 | std::string getMimeTypeForFile(const std::string& filename) 505 | { 506 | std::string mimeType; 507 | 508 | /* Try to get the mimeType from the file extension */ 509 | auto index_of_last_dot = filename.find_last_of("."); 510 | if (index_of_last_dot != std::string::npos) { 511 | mimeType = filename.substr(index_of_last_dot + 1); 512 | try { 513 | return extMimeTypes.at(mimeType); 514 | } catch (std::out_of_range&) {} 515 | } 516 | 517 | /* Try to get the mimeType from the cache */ 518 | try { 519 | return fileMimeTypes.at(filename); 520 | } catch (std::out_of_range&) {} 521 | 522 | /* Try to get the mimeType with libmagic */ 523 | try { 524 | std::string path = directoryPath + "/" + filename; 525 | mimeType = std::string(magic_file(magic, path.c_str())); 526 | if (mimeType.find(";") != std::string::npos) { 527 | mimeType = mimeType.substr(0, mimeType.find(";")); 528 | } 529 | fileMimeTypes[filename] = mimeType; 530 | } catch (...) { } 531 | if (mimeType.empty()) { 532 | return "application/octet-stream"; 533 | } else { 534 | return mimeType; 535 | } 536 | } 537 | 538 | std::string getNamespaceForMimeType(const std::string& mimeType) 539 | { 540 | if (uniqueNamespace || mimeType.find("text") == 0 || mimeType.empty()) { 541 | if (uniqueNamespace || mimeType.find("text/html") == 0 542 | || mimeType.empty()) { 543 | return "A"; 544 | } else { 545 | return "-"; 546 | } 547 | } else { 548 | if (mimeType == "application/font-ttf" 549 | || mimeType == "application/font-woff" 550 | || mimeType == "application/font-woff2" 551 | || mimeType == "application/vnd.ms-opentype" 552 | || mimeType == "application/vnd.ms-fontobject" 553 | || mimeType == "application/javascript" 554 | || mimeType == "application/json") { 555 | return "-"; 556 | } else { 557 | return "I"; 558 | } 559 | } 560 | } 561 | 562 | inline std::string removeLocalTagAndParameters(const std::string& url) 563 | { 564 | std::string retVal = url; 565 | std::size_t found; 566 | 567 | /* Remove URL arguments */ 568 | found = retVal.find("?"); 569 | if (found != std::string::npos) { 570 | retVal = retVal.substr(0, found); 571 | } 572 | 573 | /* Remove local tag */ 574 | found = retVal.find("#"); 575 | if (found != std::string::npos) { 576 | retVal = retVal.substr(0, found); 577 | } 578 | 579 | return retVal; 580 | } 581 | 582 | std::string computeNewUrl(const std::string& aid, const std::string& baseUrl, const std::string& targetUrl) 583 | { 584 | std::string filename = computeAbsolutePath(aid, targetUrl); 585 | std::string targetMimeType 586 | = getMimeTypeForFile(decodeUrl(removeLocalTagAndParameters(filename))); 587 | std::string newUrl 588 | = "/" + getNamespaceForMimeType(targetMimeType) + "/" + filename; 589 | return computeRelativePath(baseUrl, newUrl); 590 | } 591 | 592 | std::string removeAccents(const std::string& text) 593 | { 594 | ucnv_setDefaultName("UTF-8"); 595 | static UErrorCode status = U_ZERO_ERROR; 596 | static std::unique_ptr<icu::Transliterator> removeAccentsTrans(icu::Transliterator::createInstance( 597 | "Lower; NFD; [:M:] remove; NFC", UTRANS_FORWARD, status)); 598 | icu::UnicodeString ustring(text.c_str()); 599 | removeAccentsTrans->transliterate(ustring); 600 | std::string unaccentedText; 601 | ustring.toUTF8String(unaccentedText); 602 | return unaccentedText; 603 | } 604 | 605 | void remove_all(const std::string& path) 606 | { 607 | DIR* dir; 608 | 609 | /* It's a directory, remove all its entries first */ 610 | if ((dir = opendir(path.c_str())) != NULL) { 611 | struct dirent* ent; 612 | while ((ent = readdir(dir)) != NULL) { 613 | if (strcmp(ent->d_name, ".") and strcmp(ent->d_name, "..")) { 614 | std::string childPath = path + SEPARATOR + ent->d_name; 615 | remove_all(childPath); 616 | } 617 | } 618 | closedir(dir); 619 | rmdir(path.c_str()); 620 | } 621 | 622 | /* It's a file */ 623 | else { 624 | remove(path.c_str()); 625 | } 626 | } 627 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see <http://www.gnu.org/licenses/>. 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | <http://www.gnu.org/licenses/>. 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | <http://www.gnu.org/philosophy/why-not-lgpl.html>. 675 | --------------------------------------------------------------------------------