pax_global_header00006660000000000000000000000064126047611220014513gustar00rootroot0000000000000052 comment=8f115078cd669571b857fadac6b809e4d70a71b4 s3fs-fuse-1.79+git90-g8f11507/000077500000000000000000000000001260476112200153015ustar00rootroot00000000000000s3fs-fuse-1.79+git90-g8f11507/.gitignore000066400000000000000000000005061260476112200172720ustar00rootroot00000000000000*.o /Makefile /Makefile.in /aclocal.m4 /autom4te.cache/ /config.guess /config.log /config.status /config.sub /configure /depcomp /test-driver /compile /doc/Makefile /doc/Makefile.in /install-sh /missing /src/.deps/ /src/Makefile /src/Makefile.in /src/s3fs /src/test_* /test/.deps/ /test/Makefile /test/Makefile.in /test/*.log s3fs-fuse-1.79+git90-g8f11507/.mailmap000066400000000000000000000007231260476112200167240ustar00rootroot00000000000000Adrian Petrescu Adrian Petrescu Ben Lemasurier Dan Moore Randy Rizun Randy Rizun Takeshi Nakatani s3fs-fuse-1.79+git90-g8f11507/.travis.yml000066400000000000000000000007251260476112200174160ustar00rootroot00000000000000language: cpp dist: trusty cache: apt before_install: - sudo apt-get update -qq - sudo apt-get install -qq libfuse-dev cppcheck script: - ./autogen.sh - ./configure - make - make cppcheck - make check -C src # Travis granted s3fs access to their upcoming alpha testing stack which may # allow us to use FUSE. # TODO: Travis changed their infrastructure some time in June 2015 such that # this does not work currently #- modprobe fuse #- make check -C test s3fs-fuse-1.79+git90-g8f11507/AUTHORS000066400000000000000000000006361260476112200163560ustar00rootroot000000000000001. Randy Rizun Wrote from scratch the initial version of S3FS. 2. Dan Moore Patches and improvements. 3. Adrian Petrescu Converted the project to be autotools-based. 4. Ben LeMasurier Bugfixes, performance and other improvements. 5. Takeshi Nakatani Bugfixes, performance and other improvements. s3fs-fuse-1.79+git90-g8f11507/COPYING000066400000000000000000000431031260476112200163350ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. s3fs-fuse-1.79+git90-g8f11507/ChangeLog000066400000000000000000000204471260476112200170620ustar00rootroot00000000000000ChangeLog for S3FS ------------------ Version 1.79 -- Jul 19, 2015 issue #60 - Emit user-friendly log messages on failed CheckBucket requests issue #62 - Remove stray chars from source files issue #63 - Fix spelling errors issue #68 - FreeBSD issue issue #69 - Address clang always true warnings issue #73 - Small gitignore fixes issue #74 - url: handle scheme omission issue #83 - Changed option processing to use strtol() to get a umask issue #93 - Add simple unit tests for trim functions issue #100 - CURL handles not properly initialized to use DNS or SSL session caching issue #101 - Optimized function "bool directory_empty()" issue #103 - Remove prefix option in s3fs man page - issue#87 issue #104 - fix rename before close issue #116 - Supported signature version 4 issue #119 - Added new mp_umask option about issue#107, pr#110 issue #124 - Fallback to v2 signatures correctly. issue #130 - refactor integration tests create/cleanup file issue #131 - Test ls issue #132 - Use S3Proxy to run integration tests issue #134 - Include Content-Type in complete MPU V2 signature issue #135 - Correct V4 signature for initiate multipart upload issue #136 - Small fixes to integration tests issue #137 - Add test for multi-part upload issue #138 - Fixed bugs, not turn use_cache off and ty to load to end - issue#97 issue #143 - Fixed a bug no use_cache case about fixed #138 - issue#141 issue #144 - Add Travis configuration issue #146 - add exit handler to cleanup on failures issue #147 - Use S3Proxy 1.4.0-SNAPSHOT issue #150 - Fixed a bug not handling fsync - #145 issue #154 - Fixed url-encoding for ampersand etc on sigv4 - Improvement/#149 issue #155 - Fixed a bug: unable to mount bucket subdirectory issue #156 - Fixed a bug about ssl session sharing with libcurl older 7.23.0 - issue#126 issue #159 - Upgrade to S3Proxy 1.4.0 issue #164 - send the correct Host header when using -o url issue #165 - Auth v4 refactor issue #167 - Increased default connecting/reading/writing timeout value issue #168 - switch to use region specific endpoints to compute correct v4 signature issue #170 - Reviewed and fixed response codes print in curl.cpp - #157 issue #171 - Support buckets with mixed-case names issue #173 - Run integration tests via Travis issue #176 - configure.ac: detect target, if target is darwin (OSX), then #176 issue #177 - Add .mailmap issue #178 - Update .gitignore issue #184 - Add usage information for multipart_size issue #185 - Correct obvious typos in usage and README issue #190 - Add a no_check_certificate option. issue #194 - Tilda in a file-name breaks things (EPERM) issue #198 - Disasble integration tests for Travis issue #199 - Supported extended attributes(retry) issue #200 - fixed fallback to sigv2 for bucket create and GCS issue #202 - Specialize {set,get}xattr for OS X issue #204 - Add integration test for xattr issue #207 - Fixed a few small spelling issues. Version 1.78 -- Sep 15, 2014 issue #29 - Possible to create Debian/Ubuntu packages?(googlecode issue 109) issue 417(googlecode) - Password file with DOS format is not handled properly issue #41 - Failed making signature issue #40 - Moving a directory containing more than 1000 files truncates the directory issue #49 - use_sse is ignored when creating new files issue #39 - Support for SSE-C issue #50 - Cannot find pkg-config when configured with any SSL backend except openssl Version 1.77 -- Apr 19, 2014 issue 405(googlecode) - enable_content_md5 Input/output error issue #14 - s3fs -u should return 0 if there are no lost multiparts issue #16 - empty file is written to s3 issue #18 - s3fs crashes with segfault issue #22 - Fix typos in docs for max_stat_cache_size issue #23 - curl ssl problems issue #28 - Address signedness warning in FdCache::Init Version 1.76 -- Jan 21, 2014 issue #5 - du shows incorrect usage stats issue #8 - version in configure.ac is 1.74 for release 1.75 Version 1.75 -- Jan 6, 2014 issue #1 - Using %20 instead of the plus (+) sign for encoding spaces issue #3 - Fixed local timezone was incorrectly being applied to IAM and Last-Modified dates. issue #4 - Fix compilation error on MacOSX with missing const Version 1.74 -- Nov 24, 2013 This version is initial version on Github, same as on GoogleCodes(s3fs). https://github.com/s3fs-fuse/s3fs-fuse/releases/tag/v1.74 see more detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.74.tar.gz Version 1.73 -- Aug 23, 2013 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.73.tar.gz Version 1.72 -- Aug 10, 2013 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.72.tar.gz Version 1.71 -- Jun 15, 2013 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.71.tar.gz Version 1.70 -- Jun 01, 2013 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.70.tar.gz Version 1.69 -- May 15, 2013 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.69.tar.gz Version 1.68 -- Apr 30, 2013 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.68.tar.gz Version 1.67 -- Apr 13, 2013 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.67.tar.gz Version 1.66 -- Apr 06, 2013 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.66.tar.gz Version 1.65 -- Mar 30, 2013 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.65.tar.gz Version 1.64 -- Mar 23, 2013 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.64.tar.gz Version 1.63 -- Feb 24, 2013 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.63.tar.gz Version 1.62 -- Jan 27, 2013 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.62.tar.gz Version 1.61 -- Aug 30, 2011 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.61.tar.gz Version 1.60 -- Aug 29, 2011 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.60.tar.gz Version 1.59 -- Jul 28, 2011 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.59.tar.gz Version 1.58 -- Jul 19, 2011 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.58.tar.gz Version 1.57 -- Jul 07, 2011 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.57.tar.gz Version 1.56 -- Jul 07, 2011 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.56.tar.gz Version 1.55 -- Jul 02, 2011 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.55.tar.gz Version 1.54 -- Jun 25, 2011 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.54.tar.gz Version 1.53 -- Jun 22, 2011 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.53.tar.gz Version 1.40 -- Feb 11, 2011 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.40.tar.gz Version 1.33 -- Dec 30, 2010 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.33.tar.gz Version 1.25 -- Dec 16, 2010 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.25.tar.gz Version 1.19 -- Dec 2, 2010 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.19.tar.gz Version 1.16 -- Nov 22, 2010 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.16.tar.gz Version 1.10 -- Nov 6, 2010 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.10.tar.gz Version 1.02 -- Oct 29, 2010 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.02.tar.gz Version 1.01 -- Oct 28, 2010 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.01.tar.gz Version 1.0 -- Oct 24, 2010 see detail on googlecodes: http://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.0.tar.gz ------ Version 1.1 -- Mon Oct 18 2010 Dan Moore reopens the project and fixes various issues that had accumulated in the tracker. Adrian Petrescu converts the project to autotools and posts it to GitHub. Version 1.0 -- 2008 Randy Rizun releases a basic version of S3FS on Google Code. s3fs-fuse-1.79+git90-g8f11507/INSTALL000066400000000000000000000363321260476112200163410ustar00rootroot00000000000000Installation Instructions ************************* Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc. Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without warranty of any kind. Basic Installation ================== Briefly, the shell commands `./configure; make; make install' should configure, build, and install this package. The following more-detailed instructions are generic; see the `README' file for instructions specific to this package. Some packages provide this `INSTALL' file but do not implement all of the features documented below. The lack of an optional feature in a given package is not necessarily a bug. More recommendations for GNU packages can be found in *note Makefile Conventions: (standards)Makefile Conventions. The `configure' shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a `Makefile' in each directory of the package. It may also create one or more `.h' files containing system-dependent definitions. Finally, it creates a shell script `config.status' that you can run in the future to recreate the current configuration, and a file `config.log' containing compiler output (useful mainly for debugging `configure'). It can also use an optional file (typically called `config.cache' and enabled with `--cache-file=config.cache' or simply `-C') that saves the results of its tests to speed up reconfiguring. Caching is disabled by default to prevent problems with accidental use of stale cache files. If you need to do unusual things to compile the package, please try to figure out how `configure' could check whether to do them, and mail diffs or instructions to the address given in the `README' so they can be considered for the next release. If you are using the cache, and at some point `config.cache' contains results you don't want to keep, you may remove or edit it. The file `configure.ac' (or `configure.in') is used to create `configure' by a program called `autoconf'. You need `configure.ac' if you want to change it or regenerate `configure' using a newer version of `autoconf'. The simplest way to compile this package is: 1. `cd' to the directory containing the package's source code and type `./configure' to configure the package for your system. Running `configure' might take a while. While running, it prints some messages telling which features it is checking for. 2. Type `make' to compile the package. 3. Optionally, type `make check' to run any self-tests that come with the package, generally using the just-built uninstalled binaries. 4. Type `make install' to install the programs and any data files and documentation. When installing into a prefix owned by root, it is recommended that the package be configured and built as a regular user, and only the `make install' phase executed with root privileges. 5. Optionally, type `make installcheck' to repeat any self-tests, but this time using the binaries in their final installed location. This target does not install anything. Running this target as a regular user, particularly if the prior `make install' required root privileges, verifies that the installation completed correctly. 6. You can remove the program binaries and object files from the source code directory by typing `make clean'. To also remove the files that `configure' created (so you can compile the package for a different kind of computer), type `make distclean'. There is also a `make maintainer-clean' target, but that is intended mainly for the package's developers. If you use it, you may have to get all sorts of other programs in order to regenerate files that came with the distribution. 7. Often, you can also type `make uninstall' to remove the installed files again. In practice, not all packages have tested that uninstallation works correctly, even though it is required by the GNU Coding Standards. 8. Some packages, particularly those that use Automake, provide `make distcheck', which can by used by developers to test that all other targets like `make install' and `make uninstall' work correctly. This target is generally not run by end users. Compilers and Options ===================== Some systems require unusual options for compilation or linking that the `configure' script does not know about. Run `./configure --help' for details on some of the pertinent environment variables. You can give `configure' initial values for configuration parameters by setting variables in the command line or in the environment. Here is an example: ./configure CC=c99 CFLAGS=-g LIBS=-lposix *Note Defining Variables::, for more details. Compiling For Multiple Architectures ==================================== You can compile the package for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you can use GNU `make'. `cd' to the directory where you want the object files and executables to go and run the `configure' script. `configure' automatically checks for the source code in the directory that `configure' is in and in `..'. This is known as a "VPATH" build. With a non-GNU `make', it is safer to compile the package for one architecture at a time in the source code directory. After you have installed the package for one architecture, use `make distclean' before reconfiguring for another architecture. On MacOS X 10.5 and later systems, you can create libraries and executables that work on multiple system types--known as "fat" or "universal" binaries--by specifying multiple `-arch' options to the compiler but only a single `-arch' option to the preprocessor. Like this: ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CPP="gcc -E" CXXCPP="g++ -E" This is not guaranteed to produce working output in all cases, you may have to build one architecture at a time and combine the results using the `lipo' tool if you have problems. Installation Names ================== By default, `make install' installs the package's commands under `/usr/local/bin', include files under `/usr/local/include', etc. You can specify an installation prefix other than `/usr/local' by giving `configure' the option `--prefix=PREFIX', where PREFIX must be an absolute file name. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you pass the option `--exec-prefix=PREFIX' to `configure', the package uses PREFIX as the prefix for installing programs and libraries. Documentation and other data files still use the regular prefix. In addition, if you use an unusual directory layout you can give options like `--bindir=DIR' to specify different values for particular kinds of files. Run `configure --help' for a list of the directories you can set and what kinds of files go in them. In general, the default for these options is expressed in terms of `${prefix}', so that specifying just `--prefix' will affect all of the other directory specifications that were not explicitly provided. The most portable way to affect installation locations is to pass the correct locations to `configure'; however, many packages provide one or both of the following shortcuts of passing variable assignments to the `make install' command line to change installation locations without having to reconfigure or recompile. The first method involves providing an override variable for each affected directory. For example, `make install prefix=/alternate/directory' will choose an alternate location for all directory configuration variables that were expressed in terms of `${prefix}'. Any directories that were specified during `configure', but not in terms of `${prefix}', must each be overridden at install time for the entire installation to be relocated. The approach of makefile variable overrides for each directory variable is required by the GNU Coding Standards, and ideally causes no recompilation. However, some platforms have known limitations with the semantics of shared libraries that end up requiring recompilation when using this method, particularly noticeable in packages that use GNU Libtool. The second method involves providing the `DESTDIR' variable. For example, `make install DESTDIR=/alternate/directory' will prepend `/alternate/directory' before all installation names. The approach of `DESTDIR' overrides is not required by the GNU Coding Standards, and does not work on platforms that have drive letters. On the other hand, it does better at avoiding recompilation issues, and works well even when some directory options were not specified in terms of `${prefix}' at `configure' time. Optional Features ================= If the package supports it, you can cause programs to be installed with an extra prefix or suffix on their names by giving `configure' the option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. Some packages pay attention to `--enable-FEATURE' options to `configure', where FEATURE indicates an optional part of the package. They may also pay attention to `--with-PACKAGE' options, where PACKAGE is something like `gnu-as' or `x' (for the X Window System). The `README' should mention any `--enable-' and `--with-' options that the package recognizes. For packages that use the X Window System, `configure' can usually find the X include and library files automatically, but if it doesn't, you can use the `configure' options `--x-includes=DIR' and `--x-libraries=DIR' to specify their locations. Some packages offer the ability to configure how verbose the execution of `make' will be. For these packages, running `./configure --enable-silent-rules' sets the default to minimal output, which can be overridden with `make V=1'; while running `./configure --disable-silent-rules' sets the default to verbose, which can be overridden with `make V=0'. Particular systems ================== On HP-UX, the default C compiler is not ANSI C compatible. If GNU CC is not installed, it is recommended to use the following options in order to use an ANSI C compiler: ./configure CC="cc -Ae -D_XOPEN_SOURCE=500" and if that doesn't work, install pre-built binaries of GCC for HP-UX. On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot parse its `' header file. The option `-nodtk' can be used as a workaround. If GNU CC is not installed, it is therefore recommended to try ./configure CC="cc" and if that doesn't work, try ./configure CC="cc -nodtk" On Solaris, don't put `/usr/ucb' early in your `PATH'. This directory contains several dysfunctional programs; working variants of these programs are available in `/usr/bin'. So, if you need `/usr/ucb' in your `PATH', put it _after_ `/usr/bin'. On Haiku, software installed for all users goes in `/boot/common', not `/usr/local'. It is recommended to use the following options: ./configure --prefix=/boot/common Specifying the System Type ========================== There may be some features `configure' cannot figure out automatically, but needs to determine by the type of machine the package will run on. Usually, assuming the package is built to be run on the _same_ architectures, `configure' can figure that out, but if it prints a message saying it cannot guess the machine type, give it the `--build=TYPE' option. TYPE can either be a short name for the system type, such as `sun4', or a canonical name which has the form: CPU-COMPANY-SYSTEM where SYSTEM can have one of these forms: OS KERNEL-OS See the file `config.sub' for the possible values of each field. If `config.sub' isn't included in this package, then this package doesn't need to know the machine type. If you are _building_ compiler tools for cross-compiling, you should use the option `--target=TYPE' to select the type of system they will produce code for. If you want to _use_ a cross compiler, that generates code for a platform different from the build platform, you should specify the "host" platform (i.e., that on which the generated programs will eventually be run) with `--host=TYPE'. Sharing Defaults ================ If you want to set default values for `configure' scripts to share, you can create a site shell script called `config.site' that gives default values for variables like `CC', `cache_file', and `prefix'. `configure' looks for `PREFIX/share/config.site' if it exists, then `PREFIX/etc/config.site' if it exists. Or, you can set the `CONFIG_SITE' environment variable to the location of the site script. A warning: not all `configure' scripts look for a site script. Defining Variables ================== Variables not defined in a site shell script can be set in the environment passed to `configure'. However, some packages may run configure again during the build, and the customized values of these variables may be lost. In order to avoid this problem, you should set them in the `configure' command line, using `VAR=value'. For example: ./configure CC=/usr/local2/bin/gcc causes the specified `gcc' to be used as the C compiler (unless it is overridden in the site shell script). Unfortunately, this technique does not work for `CONFIG_SHELL' due to an Autoconf bug. Until the bug is fixed you can use this workaround: CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash `configure' Invocation ====================== `configure' recognizes the following options to control how it operates. `--help' `-h' Print a summary of all of the options to `configure', and exit. `--help=short' `--help=recursive' Print a summary of the options unique to this package's `configure', and exit. The `short' variant lists options used only in the top level, while the `recursive' variant lists options also present in any nested packages. `--version' `-V' Print the version of Autoconf used to generate the `configure' script, and exit. `--cache-file=FILE' Enable the cache: use and save the results of the tests in FILE, traditionally `config.cache'. FILE defaults to `/dev/null' to disable caching. `--config-cache' `-C' Alias for `--cache-file=config.cache'. `--quiet' `--silent' `-q' Do not print messages saying which checks are being made. To suppress all normal output, redirect it to `/dev/null' (any error messages will still be shown). `--srcdir=DIR' Look for the package's source code in directory DIR. Usually `configure' can determine that directory automatically. `--prefix=DIR' Use DIR as the installation prefix. *note Installation Names:: for more details, including other options available for fine-tuning the installation locations. `--no-create' `-n' Run the configure checks, but stop before creating any output files. `configure' also accepts some other, not widely useful, options. Run `configure --help' for more details. s3fs-fuse-1.79+git90-g8f11507/Makefile.am000066400000000000000000000027601260476112200173420ustar00rootroot00000000000000###################################################################### # s3fs - FUSE-based file system backed by Amazon S3 # # Copyright 2007-2008 Randy Rizun # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ###################################################################### SUBDIRS=src test doc EXTRA_DIST=doc default_commit_hash dist-hook: rm -rf `find $(distdir)/doc -type d -name .svn` rm -f `find $(distdir)/doc -type f -name Makefile` release : dist ../utils/release.sh ../utils/release.sh $(DIST_ARCHIVES) cppcheck: cppcheck --quiet --error-exitcode=1 \ -U CURLE_PEER_FAILED_VERIFICATION \ --enable=all \ --suppress=missingIncludeSystem \ --suppress=unsignedLessThanZero \ --suppress=unusedFunction \ --suppress=variableScope \ src/ test/ s3fs-fuse-1.79+git90-g8f11507/README.md000066400000000000000000000061331260476112200165630ustar00rootroot00000000000000s3fs ==== s3fs allows Linux and Mac OS X to mount an S3 bucket via FUSE. s3fs preserves the native object format for files, allowing use of other tools like [s3cmd](http://s3tools.org/s3cmd). Features -------- * large subset of POSIX including reading/writing files, directories, symlinks, mode, uid/gid, and extended attributes * compatible with Amazon S3, Google Cloud Storage, and other S3-based object stores * large files via multi-part upload * renames via server-side copy * optional server-side encryption * data integrity via MD5 hashes * in-memory metadata caching * local disk data caching * user-specified regions, including Amazon GovCloud * authenticate via v2 or v4 signatures Installation ------------ Ensure you have all the dependencies: On Ubuntu 14.04: ``` sudo apt-get install automake autotools-dev g++ git libcurl4-gnutls-dev libfuse-dev libssl-dev libxml2-dev make pkg-config ``` On CentOS 7: ``` sudo yum install automake fuse-devel gcc-c++ git libcurl-devel libxml2-devel make openssl-devel ``` Compile from master via the following commands: ``` git clone https://github.com/s3fs-fuse/s3fs-fuse.git cd s3fs-fuse ./autogen.sh ./configure make sudo make install ``` Examples -------- Enter your S3 identity and credential in a file `/path/to/passwd`: ``` echo MYIDENTITY:MYCREDENTIAL > /path/to/passwd ``` Make sure the file has proper permissions (if you get 'permissions' error when mounting) `/path/to/passwd`: ``` chmod 600 /path/to/passwd ``` Run s3fs with an existing bucket `mybucket` and directory `/path/to/mountpoint`: ``` s3fs mybucket /path/to/mountpoint -o passwd_file=/path/to/passwd ``` If you encounter any errors, enable debug output: ``` s3fs mybucket /path/to/mountpoint -o passwd_file=/path/to/passwd -d -d -f -o f2 -o curldbg ``` You can also mount on boot by entering the following line to `/etc/fstab`: ``` s3fs#mybucket /path/to/mountpoint fuse _netdev,allow_other 0 0 ``` Limitations ----------- Generally S3 cannot offer the same performance or semantics as a local file system. More specifically: * random writes or appends to files require rewriting the entire file * metadata operations such as listing directories have poor performance due to network latency * [eventual consistency](https://en.wikipedia.org/wiki/Eventual_consistency) can temporarily yield stale data * no atomic renames of files or directories * no coordination between multiple clients mounting the same bucket * no hard links References ---------- * [s3backer](https://github.com/archiecobbs/s3backer) - mount an S3 bucket as a single file * [s3fs-python](https://fedorahosted.org/s3fs/) - an older and less complete implementation written in Python * [S3Proxy](https://github.com/andrewgaul/s3proxy) - combine with s3fs to mount EMC Atmos, Microsoft Azure, and OpenStack Swift buckets * [s3ql](https://bitbucket.org/nikratio/s3ql/) - similar to s3fs but uses its own object format * [YAS3FS](https://github.com/danilop/yas3fs) - similar to s3fs but uses SNS to allow multiple clients to mount a bucket License ------- Copyright (C) 2010 Randy Rizun Licensed under the GNU GPL version 2 s3fs-fuse-1.79+git90-g8f11507/autogen.sh000077500000000000000000000023111260476112200172770ustar00rootroot00000000000000#! /bin/sh # This file is part of S3FS. # # Copyright 2009, 2010 Free Software Foundation, Inc. # # S3FS is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # S3FS is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses/. # # See the file ChangeLog for a revision history. echo "--- Make commit hash file -------" SHORTHASH="unknown" type git > /dev/null 2>&1 if [ $? -eq 0 -a -d .git ]; then RESULT=`git rev-parse --short HEAD` if [ $? -eq 0 ]; then SHORTHASH=${RESULT} fi fi echo ${SHORTHASH} > default_commit_hash echo "--- Finished commit hash file ---" echo "--- Start autotools -------------" aclocal \ && autoheader \ && automake --add-missing \ && autoconf echo "--- Finished autotools ----------" exit 0 s3fs-fuse-1.79+git90-g8f11507/configure.ac000066400000000000000000000161651260476112200176000ustar00rootroot00000000000000###################################################################### # s3fs - FUSE-based file system backed by Amazon S3 # # Copyright 2007-2008 Randy Rizun # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ###################################################################### dnl Process this file with autoconf to produce a configure script. AC_PREREQ(2.59) AC_INIT(s3fs, 1.79) AC_CONFIG_HEADER([config.h]) AC_CANONICAL_SYSTEM AM_INIT_AUTOMAKE([foreign]) AC_PROG_CXX AC_PROG_CC CXXFLAGS="$CXXFLAGS -Wall -D_FILE_OFFSET_BITS=64" dnl ---------------------------------------------- dnl For OSX dnl ---------------------------------------------- case "$target" in *-darwin* ) # Do something specific for mac min_fuse_version=2.7.3 ;; *) # Default Case # assume other supported linux system min_fuse_version=2.8.4 ;; esac dnl ---------------------------------------------- dnl Choice SSL library dnl ---------------------------------------------- auth_lib=na nettle_lib=no dnl dnl nettle library dnl AC_MSG_CHECKING([s3fs build with nettle(GnuTLS)]) AC_ARG_WITH( nettle, [AS_HELP_STRING([--with-nettle], [s3fs build with nettle in GnuTLS(default no)])], [ case "${withval}" in yes) AC_MSG_RESULT(yes) nettle_lib=yes ;; *) AC_MSG_RESULT(no) ;; esac ], [ AC_MSG_RESULT(no) ]) dnl dnl use openssl library for ssl dnl AC_MSG_CHECKING([s3fs build with OpenSSL]) AC_ARG_WITH( openssl, [AS_HELP_STRING([--with-openssl], [s3fs build with OpenSSL(default is no)])], [ case "${withval}" in yes) AC_MSG_RESULT(yes) AS_IF( [test $nettle_lib = no], [auth_lib=openssl], [AC_MSG_ERROR([could not set openssl with nettle, nettle is only for gnutls library])]) ;; *) AC_MSG_RESULT(no) ;; esac ], [ AC_MSG_RESULT(no) ]) dnl dnl use GnuTLS library for ssl dnl AC_MSG_CHECKING([s3fs build with GnuTLS]) AC_ARG_WITH( gnutls, [AS_HELP_STRING([--with-gnutls], [s3fs build with GnuTLS(default is no)])], [ case "${withval}" in yes) AC_MSG_RESULT(yes) AS_IF( [test $auth_lib = na], [ AS_IF( [test $nettle_lib = no], [auth_lib=gnutls], [auth_lib=nettle]) ], [AC_MSG_ERROR([could not set gnutls because already set another ssl library])]) ;; *) AC_MSG_RESULT(no) ;; esac ], [ AC_MSG_RESULT(no) ]) dnl dnl use nss library for ssl dnl AC_MSG_CHECKING([s3fs build with NSS]) AC_ARG_WITH( nss, [AS_HELP_STRING([--with-nss], [s3fs build with NSS(default is no)])], [ case "${withval}" in yes) AC_MSG_RESULT(yes) AS_IF( [test $auth_lib = na], [ AS_IF( [test $nettle_lib = no], [auth_lib=nss], [AC_MSG_ERROR([could not set openssl with nettle, nettle is only for gnutls library])]) ], [AC_MSG_ERROR([could not set nss because already set another ssl library])]) ;; *) AC_MSG_RESULT(no) ;; esac ], [ AC_MSG_RESULT(no) ]) AS_IF( [test $auth_lib = na], AS_IF( [test $nettle_lib = no], [auth_lib=openssl], [AC_MSG_ERROR([could not set nettle without GnuTLS library])] ) ) dnl dnl For PKG_CONFIG before checking nss/gnutls. dnl this is redundant checking, but we need checking before following. dnl PKG_CHECK_MODULES([common_lib_checking], [fuse >= ${min_fuse_version} libcurl >= 7.0 libxml-2.0 >= 2.6]) AC_MSG_CHECKING([compile s3fs with]) case "${auth_lib}" in openssl) AC_MSG_RESULT(OpenSSL) PKG_CHECK_MODULES([DEPS], [fuse >= ${min_fuse_version} libcurl >= 7.0 libxml-2.0 >= 2.6 libcrypto >= 0.9]) ;; gnutls) AC_MSG_RESULT(GnuTLS-gcrypt) gnutls_nettle="" AC_CHECK_LIB(gnutls, gcry_control, [gnutls_nettle=0]) AS_IF([test "$gnutls_nettle" = ""], [AC_CHECK_LIB(gcrypt, gcry_control, [gnutls_nettle=0])]) AS_IF([test $gnutls_nettle = 0], [ PKG_CHECK_MODULES([DEPS], [fuse >= ${min_fuse_version} libcurl >= 7.0 libxml-2.0 >= 2.6 gnutls >= 2.12.0 ]) LIBS="-lgnutls -lgcrypt $LIBS" AC_MSG_CHECKING([gnutls is build with]) AC_MSG_RESULT(gcrypt) ], [AC_MSG_ERROR([GnuTLS found, but gcrypt not found])]) ;; nettle) AC_MSG_RESULT(GnuTLS-nettle) gnutls_nettle="" AC_CHECK_LIB(gnutls, nettle_MD5Init, [gnutls_nettle=1]) AS_IF([test "$gnutls_nettle" = ""], [AC_CHECK_LIB(nettle, nettle_MD5Init, [gnutls_nettle=1])]) AS_IF([test $gnutls_nettle = 1], [ PKG_CHECK_MODULES([DEPS], [fuse >= ${min_fuse_version} libcurl >= 7.0 libxml-2.0 >= 2.6 nettle >= 2.7.1 ]) LIBS="-lgnutls -lnettle $LIBS" AC_MSG_CHECKING([gnutls is build with]) AC_MSG_RESULT(nettle) ], [AC_MSG_ERROR([GnuTLS found, but nettle not found])]) ;; nss) AC_MSG_RESULT(NSS) PKG_CHECK_MODULES([DEPS], [fuse >= ${min_fuse_version} libcurl >= 7.0 libxml-2.0 >= 2.6 nss >= 3.15.0 ]) ;; *) AC_MSG_ERROR([unknown ssl library type.]) ;; esac AM_CONDITIONAL([USE_SSL_OPENSSL], [test "$auth_lib" = openssl]) AM_CONDITIONAL([USE_SSL_GNUTLS], [test "$auth_lib" = gnutls -o "$auth_lib" = nettle]) AM_CONDITIONAL([USE_GNUTLS_NETTLE], [test "$auth_lib" = nettle]) AM_CONDITIONAL([USE_SSL_NSS], [test "$auth_lib" = nss]) dnl ---------------------------------------------- dnl check functions dnl ---------------------------------------------- dnl malloc_trim function AC_CHECK_FUNCS([malloc_trim]) dnl ---------------------------------------------- dnl output files dnl ---------------------------------------------- AC_CONFIG_FILES(Makefile src/Makefile test/Makefile doc/Makefile) dnl ---------------------------------------------- dnl short commit hash dnl ---------------------------------------------- AC_CHECK_PROG([GITCMD], [git —version], [yes], [no]) AC_CHECK_FILE([.git], [DOTGITDIR=yes], [DOTGITDIR=no]) AC_MSG_CHECKING([github short commit hash]) if test “x${GITCMD}” = “xyes” -a “x${DOTGITDIR}” = “xyes”; then GITCOMMITHASH=`git rev-parse --short HEAD` elif test -f default_commit_hash; then GITCOMMITHASH=`cat default_commit_hash` else GITCOMMITHASH="unknown" fi AC_MSG_RESULT([${GITCOMMITHASH}]) AC_DEFINE_UNQUOTED([COMMIT_HASH_VAL], ["${GITCOMMITHASH}"], [short commit hash value on github]) dnl ---------------------------------------------- dnl put dnl ---------------------------------------------- AC_OUTPUT dnl ---------------------------------------------- dnl end configuration dnl ---------------------------------------------- s3fs-fuse-1.79+git90-g8f11507/doc/000077500000000000000000000000001260476112200160465ustar00rootroot00000000000000s3fs-fuse-1.79+git90-g8f11507/doc/Makefile.am000066400000000000000000000017321260476112200201050ustar00rootroot00000000000000###################################################################### # s3fs - FUSE-based file system backed by Amazon S3 # # Copyright 2007-2008 Randy Rizun # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ###################################################################### dist_man1_MANS = man/s3fs.1 s3fs-fuse-1.79+git90-g8f11507/doc/man/000077500000000000000000000000001260476112200166215ustar00rootroot00000000000000s3fs-fuse-1.79+git90-g8f11507/doc/man/s3fs.1000066400000000000000000000326601260476112200175700ustar00rootroot00000000000000.TH S3FS "1" "February 2011" "S3FS" "User Commands" .SH NAME S3FS \- FUSE-based file system backed by Amazon S3 .SH SYNOPSIS .SS mounting .TP \fBs3fs bucket[:/path] mountpoint \fP [options] .SS unmounting .TP \fBumount mountpoint .SS utility mode ( remove interrupted multipart uploading objects ) .TP \fBs3fs \-u bucket .SH DESCRIPTION s3fs is a FUSE filesystem that allows you to mount an Amazon S3 bucket as a local filesystem. It stores files natively and transparently in S3 (i.e., you can use other programs to access the same files). .SH AUTHENTICATION The s3fs password file has this format (use this format if you have only one set of credentials): .RS 4 \fBaccessKeyId\fP:\fBsecretAccessKey\fP .RE If you have more than one set of credentials, this syntax is also recognized: .RS 4 \fBbucketName\fP:\fBaccessKeyId\fP:\fBsecretAccessKey\fP .RE .PP Password files can be stored in two locations: .RS 4 \fB/etc/passwd-s3fs\fP [0640] \fB$HOME/.passwd-s3fs\fP [0600] .RE .SH OPTIONS .SS "general options" .TP \fB\-h\fR \fB\-\-help\fR print help .TP \fB\ \fR \fB\-\-version\fR print version .TP \fB\-f\fR FUSE foreground option - do not run as daemon. .TP \fB\-s\fR FUSE singlethreaded option (disables multi-threaded operation) .SS "mount options" .TP All s3fs options must given in the form where "opt" is: = .TP \fB\-o\fR default_acl (default="private") the default canned acl to apply to all written S3 objects, e.g., "public-read". Any created files will have this canned acl. Any updated files will also have this canned acl applied! .TP \fB\-o\fR retries (default="2") number of times to retry a failed S3 transaction. .TP \fB\-o\fR use_cache (default="" which means disabled) local folder to use for local file cache. .TP \fB\-o\fR del_cache - delete local file cache delete local file cache when s3fs starts and exits. .TP \fB\-o\fR storage_class (default is standard) store object with specified storage class. this option replaces the old option use_rrs. Possible values: standard, standard_ia, and reduced_redundancy. .TP \fB\-o\fR use_rrs (default is disable) use Amazon's Reduced Redundancy Storage. this option can not be specified with use_sse. (can specify use_rrs=1 for old version) this option has been replaced by new storage_class option. .TP \fB\-o\fR use_sse (default is disable) Specify three type Amazon's Server-Site Encryption: SSE-S3, SSE-C or SSE-KMS. SSE-S3 uses Amazon S3-managed encryption keys, SSE-C uses customer-provided encryption keys, and SSE-KMS uses the master key which you manage in AWS KMS. You can specify "use_sse" or "use_sse=1" enables SSE-S3 type (use_sse=1 is old type parameter). Case of setting SSE-C, you can specify "use_sse=custom", "use_sse=custom:" or "use_sse="(only specified is old type parameter). You can use "c" for short "custom". The custom key file must be 600 permission. The file can have some lines, each line is one SSE-C key. The first line in file is used as Customer-Provided Encryption Keys for uploading and changing headers etc. If there are some keys after first line, those are used downloading object which are encrypted by not first key. So that, you can keep all SSE-C keys in file, that is SSE-C key history. If you specify "custom"("c") without file path, you need to set custom key by load_sse_c option or AWSSSECKEYS environment.(AWSSSECKEYS environment has some SSE-C keys with ":" separator.) This option is used to decide the SSE type. So that if you do not want to encrypt a object at uploading, but you need to decrypt encrypted object at downloaing, you can use load_sse_c option instead of this option. For setting SSE-KMS, specify "use_sse=kmsid" or "use_sse=kmsid:". You can use "k" for short "kmsid". If you san specify SSE-KMS type with your in AWS KMS, you can set it after "kmsid:"(or "k:"). If you specify only "kmsid"("k"), you need to set AWSSSEKMSID environment which value is . You must be careful about that you can not use the KMS id which is not same EC2 region. .TP \fB\-o\fR load_sse_c - specify SSE-C keys Specify the custom-provided encription keys file path for decrypting at duwnloading. If you use the custom-provided encription key at uploading, you specify with "use_sse=custom". The file has many lines, one line means one custom key. So that you can keep all SSE-C keys in file, that is SSE-C key history. AWSSSECKEYS environment is as same as this file contents. .TP \fB\-o\fR passwd_file (default="") specify the path to the password file, which which takes precedence over the password in $HOME/.passwd-s3fs and /etc/passwd-s3fs .TP \fB\-o\fR ahbe_conf (default="" which means disabled) This option specifies the configuration file path which file is the additional HTTP header by file(object) extension. The configuration file format is below: ----------- line = [file suffix] HTTP-header [HTTP-values] file suffix = file(object) suffix, if this field is empty, it means "*"(all object). HTTP-header = additional HTTP header name HTTP-values = additional HTTP header value ----------- Sample: ----------- .gz Content-Encoding gzip .Z Content-Encoding compress X-S3FS-MYHTTPHEAD myvalue ----------- A sample configuration file is uploaded in "test" directory. If you specify this option for set "Content-Encoding" HTTP header, please take care for RFC 2616. .TP \fB\-o\fR public_bucket (default="" which means disabled) anonymously mount a public bucket when set to 1, ignores the $HOME/.passwd-s3fs and /etc/passwd-s3fs files. .TP \fB\-o\fR connect_timeout (default="300" seconds) time to wait for connection before giving up. .TP \fB\-o\fR readwrite_timeout (default="60" seconds) time to wait between read/write activity before giving up. .TP \fB\-o\fR max_stat_cache_size (default="1000" entries (about 4MB)) maximum number of entries in the stat cache .TP \fB\-o\fR stat_cache_expire (default is no expire) specify expire time(seconds) for entries in the stat cache .TP \fB\-o\fR enable_noobj_cache (default is disable) enable cache entries for the object which does not exist. s3fs always has to check whether file(or sub directory) exists under object(path) when s3fs does some command, since s3fs has recognized a directory which does not exist and has files or sub directories under itself. It increases ListBucket request and makes performance bad. You can specify this option for performance, s3fs memorizes in stat cache that the object(file or directory) does not exist. .TP \fB\-o\fR no_check_certificate (by default this option is disabled) do not check ssl certificate. server certificate won't be checked against the available certificate authorities. .TP \fB\-o\fR nodnscache - disable dns cache. s3fs is always using dns cache, this option make dns cache disable. .TP \fB\-o\fR nosscache - disable ssl session cache. s3fs is always using ssl session cache, this option make ssl session cache disable. .TP \fB\-o\fR multireq_max (default="20") maximum number of parallel request for listing objects. .TP \fB\-o\fR parallel_count (default="5") number of parallel request for uploading big objects. s3fs uploads large object(default:over 20MB) by multipart post request, and sends parallel requests. This option limits parallel request count which s3fs requests at once. It is necessary to set this value depending on a CPU and a network band. This option is lated to fd_page_size option and affects it. .TP \fB\-o\fR fd_page_size(default="52428800"(50MB)) number of internal management page size for each file descriptor. For delayed reading and writing by s3fs, s3fs manages pages which is separated from object. Each pages has a status that data is already loaded(or not loaded yet). This option should not be changed when you don't have a trouble with performance. This value is changed automatically by parallel_count and multipart_size values(fd_page_size value = parallel_count * multipart_size). .TP \fB\-o\fR multipart_size(default="10"(10MB)) number of one part size in multipart uploading request. The default size is 10MB(10485760byte), this value is minimum size. Specify number of MB and over 10(MB). This option is lated to fd_page_size option and affects it. .TP \fB\-o\fR url (default="http://s3.amazonaws.com") sets the url to use to access Amazon S3. If you want to use HTTPS, then you can set url=https://s3.amazonaws.com .TP \fB\-o\fR endpoint (default="us-east-1") sets the endpoint to use. If this option is not specified, s3fs uses "us-east-1" region as the default. If the s3fs could not connect to the region specified by this option, s3fs could not run. But if you do not specify this option, and if you can not connect with the default region, s3fs will retry to automatically connect to the other region. So s3fs can know the correct region name, because s3fs can find it in an error from the S3 server. .TP \fB\-o\fR sigv2 (default is signature version 4) sets signing AWS requests by sing Signature Version 2. .TP \fB\-o\fR mp_umask (default is "0000") sets umask for the mount point directory. If allow_other option is not set, s3fs allows access to the mount point only to the owner. In the opposite case s3fs allows access to all users as the default. But if you set the allow_other with this option, you can controll the permission permissions of the mount point by this option like umask. .TP \fB\-o\fR nomultipart - disable multipart uploads .TP \fB\-o\fR enable_content_md5 ( default is disable ) verifying uploaded data without multipart by content-md5 header. Enable to send "Content-MD5" header when uploading a object without multipart posting. If this option is enabled, it has some influences on a performance of s3fs when uploading small object. Because s3fs always checks MD5 when uploading large object, this option does not affect on large object. .TP \fB\-o\fR iam_role ( default is no role ) set the IAM Role that will supply the credentials from the instance meta-data. .TP \fB\-o\fR noxmlns - disable registing xml name space. disable registing xml name space for response of ListBucketResult and ListVersionsResult etc. Default name space is looked up from "http://s3.amazonaws.com/doc/2006-03-01". This option should not be specified now, because s3fs looks up xmlns automatically after v1.66. .TP \fB\-o\fR nocopyapi - for other incomplete compatibility object storage. For a distributed object storage which is compatibility S3 API without PUT(copy api). If you set this option, s3fs do not use PUT with "x-amz-copy-source"(copy api). Because traffic is increased 2-3 times by this option, we do not recommend this. .TP \fB\-o\fR norenameapi - for other incomplete compatibility object storage. For a distributed object storage which is compatibility S3 API without PUT(copy api). This option is a subset of nocopyapi option. The nocopyapi option does not use copy-api for all command(ex. chmod, chown, touch, mv, etc), but this option does not use copy-api for only rename command(ex. mv). If this option is specified with nocopapi, the s3fs ignores it. .TP \fB\-o\fR use_path_request_style (use legacy API calling style) Enble compatibility with S3-like APIs which do not support the virtual-host request style, by using the older path request style. .TP \fB\-o\fR dbglevel (default="crit") Set the debug message level. set value as crit(critical), err(error), warn(warning), info(information) to debug level. default debug level is critical. If s3fs run with "-d" option, the debug level is set information. When s3fs catch the signal SIGUSR2, the debug level is bumpup. .TP \fB\-o\fR curldbg - put curl debug message Put the debug message from libcurl when this option is specified. .SH FUSE/MOUNT OPTIONS .TP Most of the generic mount options described in 'man mount' are supported (ro, rw, suid, nosuid, dev, nodev, exec, noexec, atime, noatime, sync async, dirsync). Filesystems are mounted with '\-onodev,nosuid' by default, which can only be overridden by a privileged user. .TP There are many FUSE specific mount options that can be specified. e.g. allow_other. See the FUSE README for the full set. .SH NOTES .TP Maximum file size=64GB (limited by s3fs, not Amazon). .TP If enabled via the "use_cache" option, s3fs automatically maintains a local cache of files in the folder specified by use_cache. Whenever s3fs needs to read or write a file on S3, it first downloads the entire file locally to the folder specified by use_cache and operates on it. When fuse_release() is called, s3fs will re-upload the file to S3 if it has been changed. s3fs uses md5 checksums to minimize downloads from S3. .TP The folder specified by use_cache is just a local cache. It can be deleted at any time. s3fs rebuilds it on demand. .TP Local file caching works by calculating and comparing md5 checksums (ETag HTTP header). .TP s3fs leverages /etc/mime.types to "guess" the "correct" content-type based on file name extension. This means that you can copy a website to S3 and serve it up directly from S3 with correct content-types! .SH BUGS Due to S3's "eventual consistency" limitations, file creation can and will occasionally fail. Even after a successful create, subsequent reads can fail for an indeterminate time, even after one or more successful reads. Create and read enough files and you will eventually encounter this failure. This is not a flaw in s3fs and it is not something a FUSE wrapper like s3fs can work around. The retries option does not address this issue. Your application must either tolerate or compensate for these failures, for example by retrying creates or reads. .SH AUTHOR s3fs has been written by Randy Rizun . s3fs-fuse-1.79+git90-g8f11507/src/000077500000000000000000000000001260476112200160705ustar00rootroot00000000000000s3fs-fuse-1.79+git90-g8f11507/src/Makefile.am000066400000000000000000000030621260476112200201250ustar00rootroot00000000000000###################################################################### # s3fs - FUSE-based file system backed by Amazon S3 # # Copyright 2007-2008 Randy Rizun # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ###################################################################### bin_PROGRAMS=s3fs AM_CPPFLAGS = $(DEPS_CFLAGS) if USE_GNUTLS_NETTLE AM_CPPFLAGS += -DUSE_GNUTLS_NETTLE endif s3fs_SOURCES = s3fs.cpp s3fs.h curl.cpp curl.h cache.cpp cache.h string_util.cpp string_util.h s3fs_util.cpp s3fs_util.h fdcache.cpp fdcache.h common_auth.cpp s3fs_auth.h common.h if USE_SSL_OPENSSL s3fs_SOURCES += openssl_auth.cpp endif if USE_SSL_GNUTLS s3fs_SOURCES += gnutls_auth.cpp endif if USE_SSL_NSS s3fs_SOURCES += nss_auth.cpp endif s3fs_LDADD = $(DEPS_LIBS) noinst_PROGRAMS = test_string_util test_string_util_SOURCES = string_util.cpp test_string_util.cpp test_util.h TESTS = test_string_util s3fs-fuse-1.79+git90-g8f11507/src/cache.cpp000066400000000000000000000270301260476112200176410ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "cache.h" #include "s3fs.h" #include "s3fs_util.h" #include "string_util.h" using namespace std; //------------------------------------------------------------------- // Static //------------------------------------------------------------------- StatCache StatCache::singleton; pthread_mutex_t StatCache::stat_cache_lock; //------------------------------------------------------------------- // Constructor/Destructor //------------------------------------------------------------------- StatCache::StatCache() : IsExpireTime(false), ExpireTime(0), CacheSize(1000), IsCacheNoObject(false) { if(this == StatCache::getStatCacheData()){ stat_cache.clear(); pthread_mutex_init(&(StatCache::stat_cache_lock), NULL); }else{ assert(false); } } StatCache::~StatCache() { if(this == StatCache::getStatCacheData()){ Clear(); pthread_mutex_destroy(&(StatCache::stat_cache_lock)); }else{ assert(false); } } //------------------------------------------------------------------- // Methods //------------------------------------------------------------------- unsigned long StatCache::GetCacheSize(void) const { return CacheSize; } unsigned long StatCache::SetCacheSize(unsigned long size) { unsigned long old = CacheSize; CacheSize = size; return old; } time_t StatCache::GetExpireTime(void) const { return (IsExpireTime ? ExpireTime : (-1)); } time_t StatCache::SetExpireTime(time_t expire) { time_t old = ExpireTime; ExpireTime = expire; IsExpireTime = true; return old; } time_t StatCache::UnsetExpireTime(void) { time_t old = IsExpireTime ? ExpireTime : (-1); ExpireTime = 0; IsExpireTime = false; return old; } bool StatCache::SetCacheNoObject(bool flag) { bool old = IsCacheNoObject; IsCacheNoObject = flag; return old; } void StatCache::Clear(void) { pthread_mutex_lock(&StatCache::stat_cache_lock); for(stat_cache_t::iterator iter = stat_cache.begin(); iter != stat_cache.end(); stat_cache.erase(iter++)){ if((*iter).second){ delete (*iter).second; } } S3FS_MALLOCTRIM(0); pthread_mutex_unlock(&StatCache::stat_cache_lock); } bool StatCache::GetStat(string& key, struct stat* pst, headers_t* meta, bool overcheck, const char* petag, bool* pisforce) { bool is_delete_cache = false; string strpath = key; pthread_mutex_lock(&StatCache::stat_cache_lock); stat_cache_t::iterator iter = stat_cache.end(); if(overcheck && '/' != strpath[strpath.length() - 1]){ strpath += "/"; iter = stat_cache.find(strpath.c_str()); } if(iter == stat_cache.end()){ strpath = key; iter = stat_cache.find(strpath.c_str()); } if(iter != stat_cache.end() && (*iter).second){ stat_cache_entry* ent = (*iter).second; if(!IsExpireTime|| (ent->cache_date + ExpireTime) >= time(NULL)){ if(ent->noobjcache){ pthread_mutex_unlock(&StatCache::stat_cache_lock); if(!IsCacheNoObject){ // need to delete this cache. DelStat(strpath); }else{ // noobjcache = true means no object. } return false; } // hit without checking etag if(petag){ string stretag = ent->meta["ETag"]; if('\0' != petag[0] && 0 != strcmp(petag, stretag.c_str())){ is_delete_cache = true; } } if(is_delete_cache){ // not hit by different ETag S3FS_PRN_DBG("stat cache not hit by ETag[path=%s][time=%jd][hit count=%lu][ETag(%s)!=(%s)]", strpath.c_str(), (intmax_t)(ent->cache_date), ent->hit_count, petag ? petag : "null", ent->meta["ETag"].c_str()); }else{ // hit S3FS_PRN_DBG("stat cache hit [path=%s][time=%jd][hit count=%lu]", strpath.c_str(), (intmax_t)(ent->cache_date), ent->hit_count); if(pst!= NULL){ *pst= ent->stbuf; } if(meta != NULL){ *meta = ent->meta; } if(pisforce != NULL){ (*pisforce) = ent->isforce; } ent->hit_count++; ent->cache_date = time(NULL); pthread_mutex_unlock(&StatCache::stat_cache_lock); return true; } }else{ // timeout is_delete_cache = true; } } pthread_mutex_unlock(&StatCache::stat_cache_lock); if(is_delete_cache){ DelStat(strpath); } return false; } bool StatCache::IsNoObjectCache(string& key, bool overcheck) { bool is_delete_cache = false; string strpath = key; if(!IsCacheNoObject){ return false; } pthread_mutex_lock(&StatCache::stat_cache_lock); stat_cache_t::iterator iter = stat_cache.end(); if(overcheck && '/' != strpath[strpath.length() - 1]){ strpath += "/"; iter = stat_cache.find(strpath.c_str()); } if(iter == stat_cache.end()){ strpath = key; iter = stat_cache.find(strpath.c_str()); } if(iter != stat_cache.end() && (*iter).second) { if(!IsExpireTime|| ((*iter).second->cache_date + ExpireTime) >= time(NULL)){ if((*iter).second->noobjcache){ // noobjcache = true means no object. (*iter).second->cache_date = time(NULL); pthread_mutex_unlock(&StatCache::stat_cache_lock); return true; } }else{ // timeout is_delete_cache = true; } } pthread_mutex_unlock(&StatCache::stat_cache_lock); if(is_delete_cache){ DelStat(strpath); } return false; } bool StatCache::AddStat(std::string& key, headers_t& meta, bool forcedir) { if(CacheSize< 1){ return true; } S3FS_PRN_INFO3("add stat cache entry[path=%s]", key.c_str()); pthread_mutex_lock(&StatCache::stat_cache_lock); bool found = stat_cache.end() != stat_cache.find(key); bool do_truncate = stat_cache.size() > CacheSize; pthread_mutex_unlock(&StatCache::stat_cache_lock); if(found){ DelStat(key.c_str()); }else{ if(do_truncate){ if(!TruncateCache()){ return false; } } } // make new stat_cache_entry* ent = new stat_cache_entry(); if(!convert_header_to_stat(key.c_str(), meta, &(ent->stbuf), forcedir)){ delete ent; return false; } ent->hit_count = 0; ent->cache_date = time(NULL); // Set time. ent->isforce = forcedir; ent->noobjcache = false; ent->meta.clear(); //copy only some keys for(headers_t::iterator iter = meta.begin(); iter != meta.end(); ++iter){ string tag = lower(iter->first); string value = iter->second; if(tag == "content-type"){ ent->meta[iter->first] = value; }else if(tag == "content-length"){ ent->meta[iter->first] = value; }else if(tag == "etag"){ ent->meta[iter->first] = value; }else if(tag == "last-modified"){ ent->meta[iter->first] = value; }else if(tag.substr(0, 5) == "x-amz"){ ent->meta[tag] = value; // key is lower case for "x-amz" } } // add pthread_mutex_lock(&StatCache::stat_cache_lock); stat_cache[key] = ent; pthread_mutex_unlock(&StatCache::stat_cache_lock); return true; } bool StatCache::AddNoObjectCache(string& key) { if(!IsCacheNoObject){ return true; // pretend successful } if(CacheSize < 1){ return true; } S3FS_PRN_INFO3("add no object cache entry[path=%s]", key.c_str()); pthread_mutex_lock(&StatCache::stat_cache_lock); bool found = stat_cache.end() != stat_cache.find(key); bool do_truncate = stat_cache.size() > CacheSize; pthread_mutex_unlock(&StatCache::stat_cache_lock); if(found){ DelStat(key.c_str()); }else{ if(do_truncate){ if(!TruncateCache()){ return false; } } } // make new stat_cache_entry* ent = new stat_cache_entry(); memset(&(ent->stbuf), 0, sizeof(struct stat)); ent->hit_count = 0; ent->cache_date = time(NULL); // Set time. ent->isforce = false; ent->noobjcache = true; ent->meta.clear(); // add pthread_mutex_lock(&StatCache::stat_cache_lock); stat_cache[key] = ent; pthread_mutex_unlock(&StatCache::stat_cache_lock); return true; } bool StatCache::TruncateCache(void) { pthread_mutex_lock(&StatCache::stat_cache_lock); if(stat_cache.empty()){ pthread_mutex_unlock(&StatCache::stat_cache_lock); return true; } time_t lowest_time = time(NULL) + 1; stat_cache_t::iterator iter_to_delete = stat_cache.end(); stat_cache_t::iterator iter; for(iter = stat_cache.begin(); iter != stat_cache.end(); ++iter) { if((*iter).second){ if(lowest_time > (*iter).second->cache_date){ lowest_time = (*iter).second->cache_date; iter_to_delete = iter; } } } if(stat_cache.end() != iter_to_delete){ S3FS_PRN_DBG("truncate stat cache[path=%s]", (*iter_to_delete).first.c_str()); if((*iter_to_delete).second){ delete (*iter_to_delete).second; } stat_cache.erase(iter_to_delete); S3FS_MALLOCTRIM(0); } pthread_mutex_unlock(&StatCache::stat_cache_lock); return true; } bool StatCache::DelStat(const char* key) { if(!key){ return false; } S3FS_PRN_INFO3("delete stat cache entry[path=%s]", key); pthread_mutex_lock(&StatCache::stat_cache_lock); stat_cache_t::iterator iter; if(stat_cache.end() != (iter = stat_cache.find(string(key)))){ if((*iter).second){ delete (*iter).second; } stat_cache.erase(iter); } if(0 < strlen(key) && 0 != strcmp(key, "/")){ string strpath = key; if('/' == strpath[strpath.length() - 1]){ // If there is "path" cache, delete it. strpath = strpath.substr(0, strpath.length() - 1); }else{ // If there is "path/" cache, delete it. strpath += "/"; } if(stat_cache.end() != (iter = stat_cache.find(strpath.c_str()))){ if((*iter).second){ delete (*iter).second; } stat_cache.erase(iter); } } S3FS_MALLOCTRIM(0); pthread_mutex_unlock(&StatCache::stat_cache_lock); return true; } //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- bool convert_header_to_stat(const char* path, headers_t& meta, struct stat* pst, bool forcedir) { if(!path || !pst){ return false; } memset(pst, 0, sizeof(struct stat)); pst->st_nlink = 1; // see fuse FAQ // mode pst->st_mode = get_mode(meta, path, true, forcedir); // blocks if(S_ISREG(pst->st_mode)){ pst->st_blocks = get_blocks(pst->st_size); } pst->st_blksize = 4096; // mtime pst->st_mtime = get_mtime(meta); // size pst->st_size = get_size(meta); // uid/gid pst->st_uid = get_uid(meta); pst->st_gid = get_gid(meta); return true; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/cache.h000066400000000000000000000075771260476112200173240ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef S3FS_CACHE_H_ #define S3FS_CACHE_H_ #include "common.h" // // Struct // struct stat_cache_entry { struct stat stbuf; unsigned long hit_count; time_t cache_date; headers_t meta; bool isforce; bool noobjcache; // Flag: cache is no object for no listing. stat_cache_entry() : hit_count(0), cache_date(0), isforce(false), noobjcache(false) { memset(&stbuf, 0, sizeof(struct stat)); meta.clear(); } }; typedef std::map stat_cache_t; // key=path // // Class // class StatCache { private: static StatCache singleton; static pthread_mutex_t stat_cache_lock; stat_cache_t stat_cache; bool IsExpireTime; time_t ExpireTime; unsigned long CacheSize; bool IsCacheNoObject; private: void Clear(void); bool GetStat(std::string& key, struct stat* pst, headers_t* meta, bool overcheck, const char* petag, bool* pisforce); // Truncate stat cache bool TruncateCache(void); public: StatCache(); ~StatCache(); // Reference singleton static StatCache* getStatCacheData(void) { return &singleton; } // Attribute unsigned long GetCacheSize(void) const; unsigned long SetCacheSize(unsigned long size); time_t GetExpireTime(void) const; time_t SetExpireTime(time_t expire); time_t UnsetExpireTime(void); bool SetCacheNoObject(bool flag); bool EnableCacheNoObject(void) { return SetCacheNoObject(true); } bool DisableCacheNoObject(void) { return SetCacheNoObject(false); } bool GetCacheNoObject(void) const { return IsCacheNoObject; } // Get stat cache bool GetStat(std::string& key, struct stat* pst, headers_t* meta, bool overcheck = true, bool* pisforce = NULL) { return GetStat(key, pst, meta, overcheck, NULL, pisforce); } bool GetStat(std::string& key, struct stat* pst, bool overcheck = true) { return GetStat(key, pst, NULL, overcheck, NULL, NULL); } bool GetStat(std::string& key, headers_t* meta, bool overcheck = true) { return GetStat(key, NULL, meta, overcheck, NULL, NULL); } bool HasStat(std::string& key, bool overcheck = true) { return GetStat(key, NULL, NULL, overcheck, NULL, NULL); } bool HasStat(std::string& key, const char* etag, bool overcheck = true) { return GetStat(key, NULL, NULL, overcheck, etag, NULL); } // Cache For no object bool IsNoObjectCache(std::string& key, bool overcheck = true); bool AddNoObjectCache(std::string& key); // Add stat cache bool AddStat(std::string& key, headers_t& meta, bool forcedir = false); // Delete stat cache bool DelStat(const char* key); bool DelStat(std::string& key) { return DelStat(key.c_str()); } }; // // Functions // bool convert_header_to_stat(const char* path, headers_t& meta, struct stat* pst, bool forcedir = false); #endif // S3FS_CACHE_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/common.h000066400000000000000000000131721260476112200175350ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef S3FS_COMMON_H_ #define S3FS_COMMON_H_ #include "../config.h" // // Macro // #define SAFESTRPTR(strptr) (strptr ? strptr : "") // // Debug level // enum s3fs_log_level{ S3FS_LOG_CRIT = 0, // LOG_CRIT S3FS_LOG_ERR = 1, // LOG_ERR S3FS_LOG_WARN = 3, // LOG_WARNING S3FS_LOG_INFO = 7, // LOG_INFO S3FS_LOG_DBG = 15 // LOG_DEBUG }; // // Debug macros // #define IS_S3FS_LOG_CRIT() (S3FS_LOG_CRIT == debug_level) #define IS_S3FS_LOG_ERR() (S3FS_LOG_ERR == (debug_level & S3FS_LOG_DBG)) #define IS_S3FS_LOG_WARN() (S3FS_LOG_WARN == (debug_level & S3FS_LOG_DBG)) #define IS_S3FS_LOG_INFO() (S3FS_LOG_INFO == (debug_level & S3FS_LOG_DBG)) #define IS_S3FS_LOG_DBG() (S3FS_LOG_DBG == (debug_level & S3FS_LOG_DBG)) #define S3FS_LOG_LEVEL_TO_SYSLOG(level) \ ( S3FS_LOG_DBG == (level & S3FS_LOG_DBG) ? LOG_DEBUG : \ S3FS_LOG_INFO == (level & S3FS_LOG_DBG) ? LOG_INFO : \ S3FS_LOG_WARN == (level & S3FS_LOG_DBG) ? LOG_WARNING : \ S3FS_LOG_ERR == (level & S3FS_LOG_DBG) ? LOG_ERR : LOG_CRIT ) #define S3FS_LOG_LEVEL_STRING(level) \ ( S3FS_LOG_DBG == (level & S3FS_LOG_DBG) ? "[DBG] " : \ S3FS_LOG_INFO == (level & S3FS_LOG_DBG) ? "[INF] " : \ S3FS_LOG_WARN == (level & S3FS_LOG_DBG) ? "[WAN] " : \ S3FS_LOG_ERR == (level & S3FS_LOG_DBG) ? "[ERR] " : "[CRT] " ) #define S3FS_LOG_NEST_MAX 4 #define S3FS_LOG_NEST(nest) (nest < S3FS_LOG_NEST_MAX ? s3fs_log_nest[nest] : s3fs_log_nest[S3FS_LOG_NEST_MAX - 1]) #define S3FS_LOW_LOGPRN(level, fmt, ...) \ if(S3FS_LOG_CRIT == level || (S3FS_LOG_CRIT != debug_level && level == (debug_level & level))){ \ if(foreground){ \ fprintf(stdout, "%s%s(%d): " fmt "%s\n", S3FS_LOG_LEVEL_STRING(level), __func__, __LINE__, __VA_ARGS__); \ }else{ \ syslog(S3FS_LOG_LEVEL_TO_SYSLOG(level), "%s(%d): " fmt "%s", __func__, __LINE__, __VA_ARGS__); \ } \ } #define S3FS_LOW_LOGPRN2(level, nest, fmt, ...) \ if(S3FS_LOG_CRIT == level || (S3FS_LOG_CRIT != debug_level && level == (debug_level & level))){ \ if(foreground){ \ fprintf(stdout, "%s%s%s(%d): " fmt "%s\n", S3FS_LOG_LEVEL_STRING(level), S3FS_LOG_NEST(nest), __func__, __LINE__, __VA_ARGS__); \ }else{ \ syslog(S3FS_LOG_LEVEL_TO_SYSLOG(level), "%s" fmt "%s", S3FS_LOG_NEST(nest), __VA_ARGS__); \ } \ } #define S3FS_LOW_LOGPRN_EXIT(fmt, ...) \ if(foreground){ \ fprintf(stderr, "s3fs: " fmt "%s\n", __VA_ARGS__); \ }else{ \ syslog(S3FS_LOG_CRIT, "s3fs: " fmt "%s", __VA_ARGS__); \ } // [NOTE] // small trick for VA_ARGS // #define S3FS_PRN_EXIT(fmt, ...) S3FS_LOW_LOGPRN_EXIT(fmt, ##__VA_ARGS__, "") #define S3FS_PRN_CRIT(fmt, ...) S3FS_LOW_LOGPRN(S3FS_LOG_CRIT, fmt, ##__VA_ARGS__, "") #define S3FS_PRN_ERR(fmt, ...) S3FS_LOW_LOGPRN(S3FS_LOG_ERR, fmt, ##__VA_ARGS__, "") #define S3FS_PRN_WARN(fmt, ...) S3FS_LOW_LOGPRN(S3FS_LOG_WARN, fmt, ##__VA_ARGS__, "") #define S3FS_PRN_DBG(fmt, ...) S3FS_LOW_LOGPRN(S3FS_LOG_DBG, fmt, ##__VA_ARGS__, "") #define S3FS_PRN_INFO(fmt, ...) S3FS_LOW_LOGPRN2(S3FS_LOG_INFO, 0, fmt, ##__VA_ARGS__, "") #define S3FS_PRN_INFO0(fmt, ...) S3FS_LOG_INFO(fmt, __VA_ARGS__) #define S3FS_PRN_INFO1(fmt, ...) S3FS_LOW_LOGPRN2(S3FS_LOG_INFO, 1, fmt, ##__VA_ARGS__, "") #define S3FS_PRN_INFO2(fmt, ...) S3FS_LOW_LOGPRN2(S3FS_LOG_INFO, 2, fmt, ##__VA_ARGS__, "") #define S3FS_PRN_INFO3(fmt, ...) S3FS_LOW_LOGPRN2(S3FS_LOG_INFO, 3, fmt, ##__VA_ARGS__, "") #define S3FS_PRN_CURL(fmt, ...) S3FS_LOW_LOGPRN2(S3FS_LOG_CRIT, 0, fmt, ##__VA_ARGS__, "") // // Typedef // typedef std::map headers_t; // // Header "x-amz-meta-xattr" is for extended attributes. // This header is url encoded string which is json formated. // x-amz-meta-xattr:urlencod({"xattr-1":"base64(value-1)","xattr-2":"base64(value-2)","xattr-3":"base64(value-3)"}) // typedef struct xattr_value{ unsigned char* pvalue; size_t length; explicit xattr_value(unsigned char* pval = NULL, size_t len = 0) : pvalue(pval), length(len) {} ~xattr_value() { if(pvalue){ free(pvalue); } } }XATTRVAL, *PXATTRVAL; typedef std::map xattrs_t; // // Global valiables // extern bool foreground; extern bool nomultipart; extern bool pathrequeststyle; extern std::string program_name; extern std::string service_path; extern std::string host; extern std::string bucket; extern std::string mount_prefix; extern std::string endpoint; extern s3fs_log_level debug_level; extern const char* s3fs_log_nest[S3FS_LOG_NEST_MAX]; #endif // S3FS_COMMON_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/common_auth.cpp000066400000000000000000000046371260476112200211170ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include "s3fs_auth.h" #include "string_util.h" using namespace std; //------------------------------------------------------------------- // Utility Function //------------------------------------------------------------------- string s3fs_get_content_md5(int fd) { unsigned char* md5hex; char* base64; string Signature; if(NULL == (md5hex = s3fs_md5hexsum(fd, 0, -1))){ return string(""); } if(NULL == (base64 = s3fs_base64(md5hex, get_md5_digest_length()))){ return string(""); // ENOMEM } free(md5hex); Signature = base64; free(base64); return Signature; } string s3fs_md5sum(int fd, off_t start, ssize_t size) { size_t digestlen = get_md5_digest_length(); unsigned char* md5hex; if(NULL == (md5hex = s3fs_md5hexsum(fd, start, size))){ return string(""); } std::string md5 = s3fs_hex(md5hex, digestlen); free(md5hex); return md5; } string s3fs_sha256sum(int fd, off_t start, ssize_t size) { size_t digestlen = get_sha256_digest_length(); char sha256[2 * digestlen + 1]; char hexbuf[3]; unsigned char* sha256hex; if(NULL == (sha256hex = s3fs_sha256hexsum(fd, start, size))){ return string(""); } memset(sha256, 0, 2 * digestlen + 1); for(size_t pos = 0; pos < digestlen; pos++){ snprintf(hexbuf, 3, "%02x", sha256hex[pos]); strncat(sha256, hexbuf, 2); } free(sha256hex); return string(sha256); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/curl.cpp000066400000000000000000003701661260476112200175560ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "common.h" #include "curl.h" #include "string_util.h" #include "s3fs.h" #include "s3fs_util.h" #include "s3fs_auth.h" using namespace std; static const std::string empty_payload_hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; //------------------------------------------------------------------- // Utilities //------------------------------------------------------------------- // [TODO] // This function uses tempolary file, but should not use it. // For not using it, we implement function in each auth file(openssl, nss. gnutls). // static bool make_md5_from_string(const char* pstr, string& md5) { if(!pstr || '\0' == pstr[0]){ S3FS_PRN_ERR("Parameter is wrong."); return false; } FILE* fp; if(NULL == (fp = tmpfile())){ S3FS_PRN_ERR("Could not make tmpfile."); return false; } size_t length = strlen(pstr); if(length != fwrite(pstr, sizeof(char), length, fp)){ S3FS_PRN_ERR("Failed to write tmpfile."); fclose(fp); return false; } int fd; if(0 != fflush(fp) || 0 != fseek(fp, 0L, SEEK_SET) || -1 == (fd = fileno(fp))){ S3FS_PRN_ERR("Failed to make MD5."); fclose(fp); return false; } // base64 md5 md5 = s3fs_get_content_md5(fd); if(0 == md5.length()){ S3FS_PRN_ERR("Failed to make MD5."); fclose(fp); return false; } fclose(fp); return true; } static string url_to_host(const std::string &url) { S3FS_PRN_INFO3("url is %s", url.c_str()); static const string http = "http://"; static const string https = "https://"; std::string host; if (url.compare(0, http.size(), http) == 0) { host = url.substr(http.size()); } else if (url.compare(0, https.size(), https) == 0) { host = url.substr(https.size()); } else { assert(!"url does not begin with http:// or https://"); } size_t idx; if ((idx = host.find(':')) != string::npos || (idx = host.find('/')) != string::npos) { return host.substr(0, idx); } else { return host; } } static string get_bucket_host() { if(!pathrequeststyle){ return bucket + "." + url_to_host(host); } return url_to_host(host) + "/" + bucket; } #if 0 // noused static string tolower_header_name(const char* head) { string::size_type pos; string name = head; string value(""); if(string::npos != (pos = name.find(':'))){ value= name.substr(pos); name = name.substr(0, pos); } name = lower(name); name += value; return name; } #endif //------------------------------------------------------------------- // Class BodyData //------------------------------------------------------------------- #define BODYDATA_RESIZE_APPEND_MIN (1 * 1024) // 1KB #define BODYDATA_RESIZE_APPEND_MID (1 * 1024 * 1024) // 1MB #define BODYDATA_RESIZE_APPEND_MAX (10 * 1024 * 1024) // 10MB #define AJUST_BLOCK(bytes, block) (((bytes / block) + ((bytes % block) ? 1 : 0)) * block) bool BodyData::Resize(size_t addbytes) { if(IsSafeSize(addbytes)){ return true; } // New size size_t need_size = AJUST_BLOCK((lastpos + addbytes + 1) - bufsize, sizeof(off_t)); if(BODYDATA_RESIZE_APPEND_MAX < bufsize){ need_size = (BODYDATA_RESIZE_APPEND_MAX < need_size ? need_size : BODYDATA_RESIZE_APPEND_MAX); }else if(BODYDATA_RESIZE_APPEND_MID < bufsize){ need_size = (BODYDATA_RESIZE_APPEND_MID < need_size ? need_size : BODYDATA_RESIZE_APPEND_MID); }else if(BODYDATA_RESIZE_APPEND_MIN < bufsize){ need_size = ((bufsize * 2) < need_size ? need_size : (bufsize * 2)); }else{ need_size = (BODYDATA_RESIZE_APPEND_MIN < need_size ? need_size : BODYDATA_RESIZE_APPEND_MIN); } // realloc char* newtext; if(NULL == (newtext = (char*)realloc(text, (bufsize + need_size)))){ S3FS_PRN_CRIT("not enough memory (realloc returned NULL)"); free(text); text = NULL; return false; } text = newtext; bufsize += need_size; return true; } void BodyData::Clear(void) { if(text){ free(text); text = NULL; } lastpos = 0; bufsize = 0; } bool BodyData::Append(void* ptr, size_t bytes) { if(!ptr){ return false; } if(0 == bytes){ return true; } if(!Resize(bytes)){ return false; } memcpy(&text[lastpos], ptr, bytes); lastpos += bytes; text[lastpos] = '\0'; return true; } const char* BodyData::str(void) const { static const char* strnull = ""; if(!text){ return strnull; } return text; } //------------------------------------------------------------------- // Class S3fsCurl //------------------------------------------------------------------- #define MULTIPART_SIZE 10485760 // 10MB #define MAX_MULTI_COPY_SOURCE_SIZE 524288000 // 500MB #define IAM_EXPIRE_MERGIN (20 * 60) // update timming #define IAM_CRED_URL "http://169.254.169.254/latest/meta-data/iam/security-credentials/" #define IAMCRED_ACCESSKEYID "AccessKeyId" #define IAMCRED_SECRETACCESSKEY "SecretAccessKey" #define IAMCRED_ACCESSTOKEN "Token" #define IAMCRED_EXPIRATION "Expiration" #define IAMCRED_KEYCOUNT 4 // [NOTICE] // This symbol is for libcurl under 7.23.0 #ifndef CURLSHE_NOT_BUILT_IN #define CURLSHE_NOT_BUILT_IN 5 #endif pthread_mutex_t S3fsCurl::curl_handles_lock; pthread_mutex_t S3fsCurl::curl_share_lock[SHARE_MUTEX_MAX]; bool S3fsCurl::is_initglobal_done = false; CURLSH* S3fsCurl::hCurlShare = NULL; bool S3fsCurl::is_cert_check = true; // default bool S3fsCurl::is_dns_cache = true; // default bool S3fsCurl::is_ssl_session_cache= true; // default long S3fsCurl::connect_timeout = 300; // default time_t S3fsCurl::readwrite_timeout = 60; // default int S3fsCurl::retries = 3; // default bool S3fsCurl::is_public_bucket = false; string S3fsCurl::default_acl = "private"; storage_class_t S3fsCurl::storage_class = STANDARD; sseckeylist_t S3fsCurl::sseckeys; std::string S3fsCurl::ssekmsid = ""; sse_type_t S3fsCurl::ssetype = SSE_DISABLE; bool S3fsCurl::is_content_md5 = false; bool S3fsCurl::is_verbose = false; string S3fsCurl::AWSAccessKeyId; string S3fsCurl::AWSSecretAccessKey; string S3fsCurl::AWSAccessToken; time_t S3fsCurl::AWSAccessTokenExpire= 0; string S3fsCurl::IAM_role; long S3fsCurl::ssl_verify_hostname = 1; // default(original code...) curltime_t S3fsCurl::curl_times; curlprogress_t S3fsCurl::curl_progress; string S3fsCurl::curl_ca_bundle; mimes_t S3fsCurl::mimeTypes; int S3fsCurl::max_parallel_cnt = 5; // default off_t S3fsCurl::multipart_size = MULTIPART_SIZE; // default bool S3fsCurl::is_sigv4 = true; // default //------------------------------------------------------------------- // Class methods for S3fsCurl //------------------------------------------------------------------- bool S3fsCurl::InitS3fsCurl(const char* MimeFile) { if(0 != pthread_mutex_init(&S3fsCurl::curl_handles_lock, NULL)){ return false; } if(0 != pthread_mutex_init(&S3fsCurl::curl_share_lock[SHARE_MUTEX_DNS], NULL)){ return false; } if(0 != pthread_mutex_init(&S3fsCurl::curl_share_lock[SHARE_MUTEX_SSL_SESSION], NULL)){ return false; } if(!S3fsCurl::InitMimeType(MimeFile)){ return false; } if(!S3fsCurl::InitGlobalCurl()){ return false; } if(!S3fsCurl::InitShareCurl()){ return false; } if(!S3fsCurl::InitCryptMutex()){ return false; } return true; } bool S3fsCurl::DestroyS3fsCurl(void) { int result = true; if(!S3fsCurl::DestroyCryptMutex()){ result = false; } if(!S3fsCurl::DestroyShareCurl()){ result = false; } if(!S3fsCurl::DestroyGlobalCurl()){ result = false; } if(0 != pthread_mutex_destroy(&S3fsCurl::curl_share_lock[SHARE_MUTEX_DNS])){ result = false; } if(0 != pthread_mutex_destroy(&S3fsCurl::curl_share_lock[SHARE_MUTEX_SSL_SESSION])){ result = false; } if(0 != pthread_mutex_destroy(&S3fsCurl::curl_handles_lock)){ result = false; } return result; } bool S3fsCurl::InitGlobalCurl(void) { if(S3fsCurl::is_initglobal_done){ return false; } if(CURLE_OK != curl_global_init(CURL_GLOBAL_ALL)){ S3FS_PRN_ERR("init_curl_global_all returns error."); return false; } S3fsCurl::is_initglobal_done = true; return true; } bool S3fsCurl::DestroyGlobalCurl(void) { if(!S3fsCurl::is_initglobal_done){ return false; } curl_global_cleanup(); S3fsCurl::is_initglobal_done = false; return true; } bool S3fsCurl::InitShareCurl(void) { CURLSHcode nSHCode; if(!S3fsCurl::is_dns_cache && !S3fsCurl::is_ssl_session_cache){ S3FS_PRN_INFO("Curl does not share DNS data."); return true; } if(S3fsCurl::hCurlShare){ S3FS_PRN_WARN("already initiated."); return false; } if(NULL == (S3fsCurl::hCurlShare = curl_share_init())){ S3FS_PRN_ERR("curl_share_init failed"); return false; } if(CURLSHE_OK != (nSHCode = curl_share_setopt(S3fsCurl::hCurlShare, CURLSHOPT_LOCKFUNC, S3fsCurl::LockCurlShare))){ S3FS_PRN_ERR("curl_share_setopt(LOCKFUNC) returns %d(%s)", nSHCode, curl_share_strerror(nSHCode)); return false; } if(CURLSHE_OK != (nSHCode = curl_share_setopt(S3fsCurl::hCurlShare, CURLSHOPT_UNLOCKFUNC, S3fsCurl::UnlockCurlShare))){ S3FS_PRN_ERR("curl_share_setopt(UNLOCKFUNC) returns %d(%s)", nSHCode, curl_share_strerror(nSHCode)); return false; } if(S3fsCurl::is_dns_cache){ nSHCode = curl_share_setopt(S3fsCurl::hCurlShare, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS); if(CURLSHE_OK != nSHCode && CURLSHE_BAD_OPTION != nSHCode && CURLSHE_NOT_BUILT_IN != nSHCode){ S3FS_PRN_ERR("curl_share_setopt(DNS) returns %d(%s)", nSHCode, curl_share_strerror(nSHCode)); return false; }else if(CURLSHE_BAD_OPTION == nSHCode || CURLSHE_NOT_BUILT_IN == nSHCode){ S3FS_PRN_WARN("curl_share_setopt(DNS) returns %d(%s), but continue without shared dns data.", nSHCode, curl_share_strerror(nSHCode)); } } if(S3fsCurl::is_ssl_session_cache){ nSHCode = curl_share_setopt(S3fsCurl::hCurlShare, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION); if(CURLSHE_OK != nSHCode && CURLSHE_BAD_OPTION != nSHCode && CURLSHE_NOT_BUILT_IN != nSHCode){ S3FS_PRN_ERR("curl_share_setopt(SSL SESSION) returns %d(%s)", nSHCode, curl_share_strerror(nSHCode)); return false; }else if(CURLSHE_BAD_OPTION == nSHCode || CURLSHE_NOT_BUILT_IN == nSHCode){ S3FS_PRN_WARN("curl_share_setopt(SSL SESSION) returns %d(%s), but continue without shared ssl session data.", nSHCode, curl_share_strerror(nSHCode)); } } if(CURLSHE_OK != (nSHCode = curl_share_setopt(S3fsCurl::hCurlShare, CURLSHOPT_USERDATA, (void*)&S3fsCurl::curl_share_lock[0]))){ S3FS_PRN_ERR("curl_share_setopt(USERDATA) returns %d(%s)", nSHCode, curl_share_strerror(nSHCode)); return false; } return true; } bool S3fsCurl::DestroyShareCurl(void) { if(!S3fsCurl::hCurlShare){ if(!S3fsCurl::is_dns_cache && !S3fsCurl::is_ssl_session_cache){ return true; } S3FS_PRN_WARN("already destroy share curl."); return false; } if(CURLSHE_OK != curl_share_cleanup(S3fsCurl::hCurlShare)){ return false; } S3fsCurl::hCurlShare = NULL; return true; } void S3fsCurl::LockCurlShare(CURL* handle, curl_lock_data nLockData, curl_lock_access laccess, void* useptr) { if(!hCurlShare){ return; } pthread_mutex_t* lockmutex = static_cast(useptr); if(CURL_LOCK_DATA_DNS == nLockData){ pthread_mutex_lock(&lockmutex[SHARE_MUTEX_DNS]); }else if(CURL_LOCK_DATA_SSL_SESSION == nLockData){ pthread_mutex_lock(&lockmutex[SHARE_MUTEX_SSL_SESSION]); } } void S3fsCurl::UnlockCurlShare(CURL* handle, curl_lock_data nLockData, void* useptr) { if(!hCurlShare){ return; } pthread_mutex_t* lockmutex = static_cast(useptr); if(CURL_LOCK_DATA_DNS == nLockData){ pthread_mutex_unlock(&lockmutex[SHARE_MUTEX_DNS]); }else if(CURL_LOCK_DATA_SSL_SESSION == nLockData){ pthread_mutex_unlock(&lockmutex[SHARE_MUTEX_SSL_SESSION]); } } bool S3fsCurl::InitCryptMutex(void) { return s3fs_init_crypt_mutex(); } bool S3fsCurl::DestroyCryptMutex(void) { return s3fs_destroy_crypt_mutex(); } // homegrown timeout mechanism int S3fsCurl::CurlProgress(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow) { CURL* curl = static_cast(clientp); time_t now = time(0); progress_t p(dlnow, ulnow); pthread_mutex_lock(&S3fsCurl::curl_handles_lock); // any progress? if(p != S3fsCurl::curl_progress[curl]){ // yes! S3fsCurl::curl_times[curl] = now; S3fsCurl::curl_progress[curl] = p; }else{ // timeout? if(now - S3fsCurl::curl_times[curl] > readwrite_timeout){ pthread_mutex_unlock(&S3fsCurl::curl_handles_lock); S3FS_PRN_ERR("timeout now: %jd, curl_times[curl]: %jd, readwrite_timeout: %jd", (intmax_t)now, (intmax_t)(S3fsCurl::curl_times[curl]), (intmax_t)readwrite_timeout); return CURLE_ABORTED_BY_CALLBACK; } } pthread_mutex_unlock(&S3fsCurl::curl_handles_lock); return 0; } bool S3fsCurl::InitMimeType(const char* MimeFile) { if(!MimeFile){ MimeFile = "/etc/mime.types"; // default } string line; ifstream MT(MimeFile); if(MT.good()){ while(getline(MT, line)){ if(line[0]=='#'){ continue; } if(line.size() == 0){ continue; } stringstream tmp(line); string mimeType; tmp >> mimeType; while(tmp){ string ext; tmp >> ext; if(ext.size() == 0){ continue; } S3fsCurl::mimeTypes[ext] = mimeType; } } } return true; } // // @param s e.g., "index.html" // @return e.g., "text/html" // string S3fsCurl::LookupMimeType(string name) { string result("application/octet-stream"); string::size_type last_pos = name.find_last_of('.'); string::size_type first_pos = name.find_first_of('.'); string prefix, ext, ext2; // No dots in name, just return if(last_pos == string::npos){ return result; } // extract the last extension if(last_pos != string::npos){ ext = name.substr(1+last_pos, string::npos); } if (last_pos != string::npos) { // one dot was found, now look for another if (first_pos != string::npos && first_pos < last_pos) { prefix = name.substr(0, last_pos); // Now get the second to last file extension string::size_type next_pos = prefix.find_last_of('.'); if (next_pos != string::npos) { ext2 = prefix.substr(1+next_pos, string::npos); } } } // if we get here, then we have an extension (ext) mimes_t::const_iterator iter = S3fsCurl::mimeTypes.find(ext); // if the last extension matches a mimeType, then return // that mime type if (iter != S3fsCurl::mimeTypes.end()) { result = (*iter).second; return result; } // return with the default result if there isn't a second extension if(first_pos == last_pos){ return result; } // Didn't find a mime-type for the first extension // Look for second extension in mimeTypes, return if found iter = S3fsCurl::mimeTypes.find(ext2); if (iter != S3fsCurl::mimeTypes.end()) { result = (*iter).second; return result; } // neither the last extension nor the second-to-last extension // matched a mimeType, return the default mime type return result; } bool S3fsCurl::LocateBundle(void) { // See if environment variable CURL_CA_BUNDLE is set // if so, check it, if it is a good path, then set the // curl_ca_bundle variable to it char *CURL_CA_BUNDLE; if(0 == S3fsCurl::curl_ca_bundle.size()){ CURL_CA_BUNDLE = getenv("CURL_CA_BUNDLE"); if(CURL_CA_BUNDLE != NULL) { // check for existence and readability of the file ifstream BF(CURL_CA_BUNDLE); if(!BF.good()){ S3FS_PRN_ERR("%s: file specified by CURL_CA_BUNDLE environment variable is not readable", program_name.c_str()); return false; } BF.close(); S3fsCurl::curl_ca_bundle.assign(CURL_CA_BUNDLE); return true; } } // not set via environment variable, look in likely locations /////////////////////////////////////////// // from curl's (7.21.2) acinclude.m4 file /////////////////////////////////////////// // dnl CURL_CHECK_CA_BUNDLE // dnl ------------------------------------------------- // dnl Check if a default ca-bundle should be used // dnl // dnl regarding the paths this will scan: // dnl /etc/ssl/certs/ca-certificates.crt Debian systems // dnl /etc/pki/tls/certs/ca-bundle.crt Redhat and Mandriva // dnl /usr/share/ssl/certs/ca-bundle.crt old(er) Redhat // dnl /usr/local/share/certs/ca-root.crt FreeBSD // dnl /etc/ssl/cert.pem OpenBSD // dnl /etc/ssl/certs/ (ca path) SUSE ifstream BF("/etc/pki/tls/certs/ca-bundle.crt"); if(BF.good()){ BF.close(); S3fsCurl::curl_ca_bundle.assign("/etc/pki/tls/certs/ca-bundle.crt"); }else{ S3FS_PRN_ERR("%s: /etc/pki/tls/certs/ca-bundle.crt is not readable", program_name.c_str()); return false; } return true; } size_t S3fsCurl::WriteMemoryCallback(void* ptr, size_t blockSize, size_t numBlocks, void* data) { BodyData* body = static_cast(data); if(!body->Append(ptr, blockSize, numBlocks)){ S3FS_PRN_CRIT("BodyData.Append() returned false."); S3FS_FUSE_EXIT(); return -1; } return (blockSize * numBlocks); } size_t S3fsCurl::ReadCallback(void* ptr, size_t size, size_t nmemb, void* userp) { S3fsCurl* pCurl = reinterpret_cast(userp); if(1 > (size * nmemb)){ return 0; } if(0 >= pCurl->postdata_remaining){ return 0; } int copysize = std::min((int)(size * nmemb), pCurl->postdata_remaining); memcpy(ptr, pCurl->postdata, copysize); pCurl->postdata_remaining = (pCurl->postdata_remaining > copysize ? (pCurl->postdata_remaining - copysize) : 0); pCurl->postdata += static_cast(copysize); return copysize; } size_t S3fsCurl::HeaderCallback(void* data, size_t blockSize, size_t numBlocks, void* userPtr) { headers_t* headers = reinterpret_cast(userPtr); string header(reinterpret_cast(data), blockSize * numBlocks); string key; stringstream ss(header); if(getline(ss, key, ':')){ // Force to lower, only "x-amz" string lkey = key; transform(lkey.begin(), lkey.end(), lkey.begin(), static_cast(std::tolower)); if(lkey.compare(0, 5, "x-amz") == 0){ key = lkey; } string value; getline(ss, value); (*headers)[key] = trim(value); } return blockSize * numBlocks; } size_t S3fsCurl::UploadReadCallback(void* ptr, size_t size, size_t nmemb, void* userp) { S3fsCurl* pCurl = reinterpret_cast(userp); if(1 > (size * nmemb)){ return 0; } if(-1 == pCurl->partdata.fd || 0 >= pCurl->partdata.size){ return 0; } // read size ssize_t copysize = (size * nmemb) < (size_t)pCurl->partdata.size ? (size * nmemb) : (size_t)pCurl->partdata.size; ssize_t readbytes; ssize_t totalread; // read and set for(totalread = 0, readbytes = 0; totalread < copysize; totalread += readbytes){ readbytes = pread(pCurl->partdata.fd, &((char*)ptr)[totalread], (copysize - totalread), pCurl->partdata.startpos + totalread); if(0 == readbytes){ // eof break; }else if(-1 == readbytes){ // error S3FS_PRN_ERR("read file error(%d).", errno); return 0; } } pCurl->partdata.startpos += totalread; pCurl->partdata.size -= totalread; return totalread; } size_t S3fsCurl::DownloadWriteCallback(void* ptr, size_t size, size_t nmemb, void* userp) { S3fsCurl* pCurl = reinterpret_cast(userp); if(1 > (size * nmemb)){ return 0; } if(-1 == pCurl->partdata.fd || 0 >= pCurl->partdata.size){ return 0; } // write size ssize_t copysize = (size * nmemb) < (size_t)pCurl->partdata.size ? (size * nmemb) : (size_t)pCurl->partdata.size; ssize_t writebytes; ssize_t totalwrite; // write for(totalwrite = 0, writebytes = 0; totalwrite < copysize; totalwrite += writebytes){ writebytes = pwrite(pCurl->partdata.fd, &((char*)ptr)[totalwrite], (copysize - totalwrite), pCurl->partdata.startpos + totalwrite); if(0 == writebytes){ // eof? break; }else if(-1 == writebytes){ // error S3FS_PRN_ERR("write file error(%d).", errno); return 0; } } pCurl->partdata.startpos += totalwrite; pCurl->partdata.size -= totalwrite; return totalwrite; } bool S3fsCurl::SetCheckCertificate(bool isCertCheck) { bool old = S3fsCurl::is_cert_check; S3fsCurl::is_cert_check = isCertCheck; return old; } bool S3fsCurl::SetDnsCache(bool isCache) { bool old = S3fsCurl::is_dns_cache; S3fsCurl::is_dns_cache = isCache; return old; } bool S3fsCurl::SetSslSessionCache(bool isCache) { bool old = S3fsCurl::is_ssl_session_cache; S3fsCurl::is_ssl_session_cache = isCache; return old; } long S3fsCurl::SetConnectTimeout(long timeout) { long old = S3fsCurl::connect_timeout; S3fsCurl::connect_timeout = timeout; return old; } time_t S3fsCurl::SetReadwriteTimeout(time_t timeout) { time_t old = S3fsCurl::readwrite_timeout; S3fsCurl::readwrite_timeout = timeout; return old; } int S3fsCurl::SetRetries(int count) { int old = S3fsCurl::retries; S3fsCurl::retries = count; return old; } bool S3fsCurl::SetPublicBucket(bool flag) { bool old = S3fsCurl::is_public_bucket; S3fsCurl::is_public_bucket = flag; return old; } string S3fsCurl::SetDefaultAcl(const char* acl) { string old = S3fsCurl::default_acl; S3fsCurl::default_acl = acl ? acl : ""; return old; } storage_class_t S3fsCurl::SetStorageClass(storage_class_t storage_class) { storage_class_t old = S3fsCurl::storage_class; S3fsCurl::storage_class = storage_class; return old; } bool S3fsCurl::PushbackSseKeys(string& onekey) { onekey = trim(onekey); if(0 == onekey.size()){ return false; } if('#' == onekey[0]){ return false; } // make base64 char* pbase64_key; if(NULL == (pbase64_key = s3fs_base64((unsigned char*)onekey.c_str(), onekey.length()))){ S3FS_PRN_ERR("Failed to convert base64 from SSE-C key %s", onekey.c_str()); return false; } string base64_key = pbase64_key; free(pbase64_key); // make MD5 string strMd5; if(!make_md5_from_string(onekey.c_str(), strMd5)){ S3FS_PRN_ERR("Could not make MD5 from SSE-C keys(%s).", onekey.c_str()); return false; } // mapped MD5 = SSE Key sseckeymap_t md5map; md5map.clear(); md5map[strMd5] = base64_key; S3fsCurl::sseckeys.push_back(md5map); return true; } sse_type_t S3fsCurl::SetSseType(sse_type_t type) { sse_type_t old = S3fsCurl::ssetype; S3fsCurl::ssetype = type; return old; } bool S3fsCurl::SetSseCKeys(const char* filepath) { if(!filepath){ S3FS_PRN_ERR("SSE-C keys filepath is empty."); return false; } struct stat st; if(0 != stat(filepath, &st)){ S3FS_PRN_ERR("could not open use_sse keys file(%s).", filepath); return false; } if(st.st_mode & (S_IXUSR | S_IRWXG | S_IRWXO)){ S3FS_PRN_ERR("use_sse keys file %s should be 0600 permissions.", filepath); return false; } S3fsCurl::sseckeys.clear(); ifstream ssefs(filepath); if(!ssefs.good()){ S3FS_PRN_ERR("Could not open SSE-C keys file(%s).", filepath); return false; } string line; while(getline(ssefs, line)){ S3fsCurl::PushbackSseKeys(line); } if(0 == S3fsCurl::sseckeys.size()){ S3FS_PRN_ERR("There is no SSE Key in file(%s).", filepath); return false; } return true; } bool S3fsCurl::SetSseKmsid(const char* kmsid) { if(!kmsid || '\0' == kmsid[0]){ S3FS_PRN_ERR("SSE-KMS kms id is empty."); return false; } S3fsCurl::ssekmsid = kmsid; return true; } // [NOTE] // Because SSE is set by some options and environment, // this function check the integrity of the SSE data finally. bool S3fsCurl::FinalCheckSse(void) { if(SSE_DISABLE == S3fsCurl::ssetype){ S3fsCurl::ssekmsid.erase(); }else if(SSE_S3 == S3fsCurl::ssetype){ S3fsCurl::ssekmsid.erase(); }else if(SSE_C == S3fsCurl::ssetype){ if(0 == S3fsCurl::sseckeys.size()){ S3FS_PRN_ERR("sse type is SSE-C, but there is no custom key."); return false; } S3fsCurl::ssekmsid.erase(); }else if(SSE_KMS == S3fsCurl::ssetype){ if(S3fsCurl::ssekmsid.empty()){ S3FS_PRN_ERR("sse type is SSE-KMS, but there is no specified kms id."); return false; } if(!S3fsCurl::IsSignatureV4()){ S3FS_PRN_ERR("sse type is SSE-KMS, but signature type is not v4. SSE-KMS require signature v4."); return false; } }else{ S3FS_PRN_ERR("sse type is unknown(%d).", S3fsCurl::ssetype); return false; } return true; } bool S3fsCurl::LoadEnvSseCKeys(void) { char* envkeys = getenv("AWSSSECKEYS"); if(NULL == envkeys){ // nothing to do return true; } S3fsCurl::sseckeys.clear(); istringstream fullkeys(envkeys); string onekey; while(getline(fullkeys, onekey, ':')){ S3fsCurl::PushbackSseKeys(onekey); } if(0 == S3fsCurl::sseckeys.size()){ S3FS_PRN_ERR("There is no SSE Key in environment(AWSSSECKEYS=%s).", envkeys); return false; } return true; } bool S3fsCurl::LoadEnvSseKmsid(void) { char* envkmsid = getenv("AWSSSEKMSID"); if(NULL == envkmsid){ // nothing to do return true; } return S3fsCurl::SetSseKmsid(envkmsid); } // // If md5 is empty, returns first(current) sse key. // bool S3fsCurl::GetSseKey(string& md5, string& ssekey) { for(sseckeylist_t::const_iterator iter = S3fsCurl::sseckeys.begin(); iter != S3fsCurl::sseckeys.end(); ++iter){ if(0 == md5.length() || md5 == (*iter).begin()->first){ md5 = iter->begin()->first; ssekey = iter->begin()->second; return true; } } return false; } bool S3fsCurl::GetSseKeyMd5(int pos, string& md5) { if(pos < 0){ return false; } if(S3fsCurl::sseckeys.size() <= static_cast(pos)){ return false; } int cnt = 0; for(sseckeylist_t::const_iterator iter = S3fsCurl::sseckeys.begin(); iter != S3fsCurl::sseckeys.end(); ++iter, ++cnt){ if(pos == cnt){ md5 = iter->begin()->first; return true; } } return false; } int S3fsCurl::GetSseKeyCount(void) { return S3fsCurl::sseckeys.size(); } bool S3fsCurl::SetContentMd5(bool flag) { bool old = S3fsCurl::is_content_md5; S3fsCurl::is_content_md5 = flag; return old; } bool S3fsCurl::SetVerbose(bool flag) { bool old = S3fsCurl::is_verbose; S3fsCurl::is_verbose = flag; return old; } bool S3fsCurl::SetAccessKey(const char* AccessKeyId, const char* SecretAccessKey) { if(!AccessKeyId || '\0' == AccessKeyId[0] || !SecretAccessKey || '\0' == SecretAccessKey[0]){ return false; } AWSAccessKeyId = AccessKeyId; AWSSecretAccessKey = SecretAccessKey; return true; } long S3fsCurl::SetSslVerifyHostname(long value) { if(0 != value && 1 != value){ return -1; } long old = S3fsCurl::ssl_verify_hostname; S3fsCurl::ssl_verify_hostname = value; return old; } string S3fsCurl::SetIAMRole(const char* role) { string old = S3fsCurl::IAM_role; S3fsCurl::IAM_role = role ? role : ""; return old; } bool S3fsCurl::SetMultipartSize(off_t size) { size = size * 1024 * 1024; if(size < MULTIPART_SIZE){ return false; } S3fsCurl::multipart_size = size; return true; } int S3fsCurl::SetMaxParallelCount(int value) { int old = S3fsCurl::max_parallel_cnt; S3fsCurl::max_parallel_cnt = value; return old; } bool S3fsCurl::UploadMultipartPostCallback(S3fsCurl* s3fscurl) { if(!s3fscurl){ return false; } // check etag(md5); if(NULL == strstr(s3fscurl->headdata->str(), s3fscurl->partdata.etag.c_str())){ return false; } s3fscurl->partdata.etaglist->at(s3fscurl->partdata.etagpos).assign(s3fscurl->partdata.etag); s3fscurl->partdata.uploaded = true; return true; } S3fsCurl* S3fsCurl::UploadMultipartPostRetryCallback(S3fsCurl* s3fscurl) { if(!s3fscurl){ return NULL; } // parse and get part_num, upload_id. string upload_id; string part_num_str; int part_num; if(!get_keyword_value(s3fscurl->url, "uploadId", upload_id)){ return NULL; } if(!get_keyword_value(s3fscurl->url, "partNumber", part_num_str)){ return NULL; } part_num = atoi(part_num_str.c_str()); if(s3fscurl->retry_count >= S3fsCurl::retries){ S3FS_PRN_ERR("Over retry count(%d) limit(%s:%d).", s3fscurl->retry_count, s3fscurl->path.c_str(), part_num); return NULL; } // duplicate request S3fsCurl* newcurl = new S3fsCurl(s3fscurl->IsUseAhbe()); newcurl->partdata.etaglist = s3fscurl->partdata.etaglist; newcurl->partdata.etagpos = s3fscurl->partdata.etagpos; newcurl->partdata.fd = s3fscurl->partdata.fd; newcurl->partdata.startpos = s3fscurl->b_partdata_startpos; newcurl->partdata.size = s3fscurl->b_partdata_size; newcurl->b_partdata_startpos = s3fscurl->b_partdata_startpos; newcurl->b_partdata_size = s3fscurl->b_partdata_size; newcurl->retry_count = s3fscurl->retry_count + 1; // setup new curl object if(0 != newcurl->UploadMultipartPostSetup(s3fscurl->path.c_str(), part_num, upload_id)){ S3FS_PRN_ERR("Could not duplicate curl object(%s:%d).", s3fscurl->path.c_str(), part_num); delete newcurl; return NULL; } return newcurl; } int S3fsCurl::ParallelMultipartUploadRequest(const char* tpath, headers_t& meta, int fd) { int result; string upload_id; struct stat st; int fd2; etaglist_t list; off_t remaining_bytes; S3fsCurl s3fscurl(true); S3FS_PRN_INFO3("[tpath=%s][fd=%d]", SAFESTRPTR(tpath), fd); // duplicate fd if(-1 == (fd2 = dup(fd)) || 0 != lseek(fd2, 0, SEEK_SET)){ S3FS_PRN_ERR("Could not duplicate file descriptor(errno=%d)", errno); if(-1 != fd2){ close(fd2); } return -errno; } if(-1 == fstat(fd2, &st)){ S3FS_PRN_ERR("Invalid file descriptor(errno=%d)", errno); close(fd2); return -errno; } if(0 != (result = s3fscurl.PreMultipartPostRequest(tpath, meta, upload_id, false))){ close(fd2); return result; } s3fscurl.DestroyCurlHandle(); // cycle through open fd, pulling off 10MB chunks at a time for(remaining_bytes = st.st_size; 0 < remaining_bytes; ){ S3fsMultiCurl curlmulti; int para_cnt; off_t chunk; // Initialize S3fsMultiCurl curlmulti.SetSuccessCallback(S3fsCurl::UploadMultipartPostCallback); curlmulti.SetRetryCallback(S3fsCurl::UploadMultipartPostRetryCallback); // Loop for setup parallel upload(multipart) request. for(para_cnt = 0; para_cnt < S3fsCurl::max_parallel_cnt && 0 < remaining_bytes; para_cnt++, remaining_bytes -= chunk){ // chunk size chunk = remaining_bytes > S3fsCurl::multipart_size ? S3fsCurl::multipart_size : remaining_bytes; // s3fscurl sub object S3fsCurl* s3fscurl_para = new S3fsCurl(true); s3fscurl_para->partdata.fd = fd2; s3fscurl_para->partdata.startpos = st.st_size - remaining_bytes; s3fscurl_para->partdata.size = chunk; s3fscurl_para->b_partdata_startpos = s3fscurl_para->partdata.startpos; s3fscurl_para->b_partdata_size = s3fscurl_para->partdata.size; s3fscurl_para->partdata.add_etag_list(&list); // initiate upload part for parallel if(0 != (result = s3fscurl_para->UploadMultipartPostSetup(tpath, list.size(), upload_id))){ S3FS_PRN_ERR("failed uploading part setup(%d)", result); close(fd2); delete s3fscurl_para; return result; } // set into parallel object if(!curlmulti.SetS3fsCurlObject(s3fscurl_para)){ S3FS_PRN_ERR("Could not make curl object into multi curl(%s).", tpath); close(fd2); delete s3fscurl_para; return -1; } } // Multi request if(0 != (result = curlmulti.Request())){ S3FS_PRN_ERR("error occuered in multi request(errno=%d).", result); break; } // reinit for loop. curlmulti.Clear(); } close(fd2); if(0 != (result = s3fscurl.CompleteMultipartPostRequest(tpath, upload_id, list))){ return result; } return 0; } S3fsCurl* S3fsCurl::ParallelGetObjectRetryCallback(S3fsCurl* s3fscurl) { int result; if(!s3fscurl){ return NULL; } if(s3fscurl->retry_count >= S3fsCurl::retries){ S3FS_PRN_ERR("Over retry count(%d) limit(%s).", s3fscurl->retry_count, s3fscurl->path.c_str()); return NULL; } // duplicate request(setup new curl object) S3fsCurl* newcurl = new S3fsCurl(s3fscurl->IsUseAhbe()); if(0 != (result = newcurl->PreGetObjectRequest(s3fscurl->path.c_str(), s3fscurl->partdata.fd, s3fscurl->partdata.startpos, s3fscurl->partdata.size, s3fscurl->b_ssetype, s3fscurl->b_ssevalue))) { S3FS_PRN_ERR("failed downloading part setup(%d)", result); delete newcurl; return NULL;; } newcurl->retry_count = s3fscurl->retry_count + 1; return newcurl; } int S3fsCurl::ParallelGetObjectRequest(const char* tpath, int fd, off_t start, ssize_t size) { S3FS_PRN_INFO3("[tpath=%s][fd=%d]", SAFESTRPTR(tpath), fd); sse_type_t ssetype; string ssevalue; if(!get_object_sse_type(tpath, ssetype, ssevalue)){ S3FS_PRN_WARN("Failed to get SSE type for file(%s).", SAFESTRPTR(tpath)); } int result = 0; ssize_t remaining_bytes; // cycle through open fd, pulling off 10MB chunks at a time for(remaining_bytes = size; 0 < remaining_bytes; ){ S3fsMultiCurl curlmulti; int para_cnt; off_t chunk; // Initialize S3fsMultiCurl //curlmulti.SetSuccessCallback(NULL); // not need to set success callback curlmulti.SetRetryCallback(S3fsCurl::ParallelGetObjectRetryCallback); // Loop for setup parallel upload(multipart) request. for(para_cnt = 0; para_cnt < S3fsCurl::max_parallel_cnt && 0 < remaining_bytes; para_cnt++, remaining_bytes -= chunk){ // chunk size chunk = remaining_bytes > S3fsCurl::multipart_size ? S3fsCurl::multipart_size : remaining_bytes; // s3fscurl sub object S3fsCurl* s3fscurl_para = new S3fsCurl(); if(0 != (result = s3fscurl_para->PreGetObjectRequest(tpath, fd, (start + size - remaining_bytes), chunk, ssetype, ssevalue))){ S3FS_PRN_ERR("failed downloading part setup(%d)", result); delete s3fscurl_para; return result; } // set into parallel object if(!curlmulti.SetS3fsCurlObject(s3fscurl_para)){ S3FS_PRN_ERR("Could not make curl object into multi curl(%s).", tpath); delete s3fscurl_para; return -1; } } // Multi request if(0 != (result = curlmulti.Request())){ S3FS_PRN_ERR("error occuered in multi request(errno=%d).", result); break; } // reinit for loop. curlmulti.Clear(); } return result; } bool S3fsCurl::ParseIAMCredentialResponse(const char* response, iamcredmap_t& keyval) { if(!response){ return false; } istringstream sscred(response); string oneline; keyval.clear(); while(getline(sscred, oneline, '\n')){ string::size_type pos; string key; string val; if(string::npos != (pos = oneline.find(IAMCRED_ACCESSKEYID))){ key = IAMCRED_ACCESSKEYID; }else if(string::npos != (pos = oneline.find(IAMCRED_SECRETACCESSKEY))){ key = IAMCRED_SECRETACCESSKEY; }else if(string::npos != (pos = oneline.find(IAMCRED_ACCESSTOKEN))){ key = IAMCRED_ACCESSTOKEN; }else if(string::npos != (pos = oneline.find(IAMCRED_EXPIRATION))){ key = IAMCRED_EXPIRATION; }else{ continue; } if(string::npos == (pos = oneline.find(':', pos + key.length()))){ continue; } if(string::npos == (pos = oneline.find('\"', pos))){ continue; } oneline = oneline.substr(pos + sizeof(char)); if(string::npos == (pos = oneline.find('\"'))){ continue; } val = oneline.substr(0, pos); keyval[key] = val; } return true; } bool S3fsCurl::SetIAMCredentials(const char* response) { S3FS_PRN_INFO3("IAM credential response = \"%s\"", response); iamcredmap_t keyval; if(!ParseIAMCredentialResponse(response, keyval)){ return false; } if(IAMCRED_KEYCOUNT != keyval.size()){ return false; } S3fsCurl::AWSAccessKeyId = keyval[string(IAMCRED_ACCESSKEYID)]; S3fsCurl::AWSSecretAccessKey = keyval[string(IAMCRED_SECRETACCESSKEY)]; S3fsCurl::AWSAccessToken = keyval[string(IAMCRED_ACCESSTOKEN)]; S3fsCurl::AWSAccessTokenExpire = cvtIAMExpireStringToTime(keyval[string(IAMCRED_EXPIRATION)].c_str()); return true; } bool S3fsCurl::CheckIAMCredentialUpdate(void) { if(0 == S3fsCurl::IAM_role.size()){ return true; } if(time(NULL) + IAM_EXPIRE_MERGIN <= S3fsCurl::AWSAccessTokenExpire){ return true; } // update S3fsCurl s3fscurl; if(0 != s3fscurl.GetIAMCredentials()){ return false; } return true; } int S3fsCurl::CurlDebugFunc(CURL* hcurl, curl_infotype type, char* data, size_t size, void* userptr) { if(!hcurl){ // something wrong... return 0; } switch(type){ case CURLINFO_TEXT: case CURLINFO_HEADER_IN: case CURLINFO_HEADER_OUT: char* buff; if(NULL == (buff = reinterpret_cast(malloc(size + 2 + 1)))){ // could not allocation memory S3FS_PRN_CRIT("could not allocate memory"); break; } buff[size + 2] = '\0'; sprintf(buff, "%c ", (CURLINFO_TEXT == type ? '*' : CURLINFO_HEADER_IN == type ? '<' : '>')); memcpy(&buff[2], data, size); S3FS_PRN_CURL("%s", buff); // no blocking free(buff); break; case CURLINFO_DATA_IN: case CURLINFO_DATA_OUT: case CURLINFO_SSL_DATA_IN: case CURLINFO_SSL_DATA_OUT: // not put break; default: // why break; } return 0; } //------------------------------------------------------------------- // Methods for S3fsCurl //------------------------------------------------------------------- S3fsCurl::S3fsCurl(bool ahbe) : hCurl(NULL), path(""), base_path(""), saved_path(""), url(""), requestHeaders(NULL), bodydata(NULL), headdata(NULL), LastResponseCode(-1), postdata(NULL), postdata_remaining(0), is_use_ahbe(ahbe), retry_count(0), b_infile(NULL), b_postdata(NULL), b_postdata_remaining(0), b_partdata_startpos(0), b_partdata_size(0), b_ssekey_pos(-1), b_ssevalue(""), b_ssetype(SSE_DISABLE) { type = REQTYPE_UNSET; } S3fsCurl::~S3fsCurl() { DestroyCurlHandle(); } bool S3fsCurl::ResetHandle(void) { curl_easy_reset(hCurl); curl_easy_setopt(hCurl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(hCurl, CURLOPT_FOLLOWLOCATION, true); curl_easy_setopt(hCurl, CURLOPT_CONNECTTIMEOUT, S3fsCurl::connect_timeout); curl_easy_setopt(hCurl, CURLOPT_NOPROGRESS, 0); curl_easy_setopt(hCurl, CURLOPT_PROGRESSFUNCTION, S3fsCurl::CurlProgress); curl_easy_setopt(hCurl, CURLOPT_PROGRESSDATA, hCurl); // curl_easy_setopt(hCurl, CURLOPT_FORBID_REUSE, 1); if(type != REQTYPE_IAMCRED){ // REQTYPE_IAMCRED is always HTTP if(0 == S3fsCurl::ssl_verify_hostname){ curl_easy_setopt(hCurl, CURLOPT_SSL_VERIFYHOST, 0); } if(S3fsCurl::curl_ca_bundle.size() != 0){ curl_easy_setopt(hCurl, CURLOPT_CAINFO, S3fsCurl::curl_ca_bundle.c_str()); } } if((S3fsCurl::is_dns_cache || S3fsCurl::is_ssl_session_cache) && S3fsCurl::hCurlShare){ curl_easy_setopt(hCurl, CURLOPT_SHARE, S3fsCurl::hCurlShare); } if(!S3fsCurl::is_cert_check) { S3FS_PRN_DBG("'no_check_certificate' option in effect.") S3FS_PRN_DBG("The server certificate won't be checked against the available certificate authorities.") curl_easy_setopt(hCurl, CURLOPT_SSL_VERIFYPEER, false); } if(S3fsCurl::is_verbose){ curl_easy_setopt(hCurl, CURLOPT_VERBOSE, true); if(!foreground){ curl_easy_setopt(hCurl, CURLOPT_DEBUGFUNCTION, S3fsCurl::CurlDebugFunc); } } S3fsCurl::curl_times[hCurl] = time(0); S3fsCurl::curl_progress[hCurl] = progress_t(-1, -1); return true; } bool S3fsCurl::CreateCurlHandle(bool force) { pthread_mutex_lock(&S3fsCurl::curl_handles_lock); if(hCurl){ if(!force){ S3FS_PRN_WARN("already create handle."); return false; } if(!DestroyCurlHandle()){ S3FS_PRN_ERR("could not destroy handle."); return false; } S3FS_PRN_INFO3("already has handle, so destroied it."); } if(NULL == (hCurl = curl_easy_init())){ S3FS_PRN_ERR("Failed to create handle."); return false; } type = REQTYPE_UNSET; ResetHandle(); pthread_mutex_unlock(&S3fsCurl::curl_handles_lock); return true; } bool S3fsCurl::DestroyCurlHandle(void) { if(!hCurl){ return false; } pthread_mutex_lock(&S3fsCurl::curl_handles_lock); S3fsCurl::curl_times.erase(hCurl); S3fsCurl::curl_progress.erase(hCurl); curl_easy_cleanup(hCurl); hCurl = NULL; ClearInternalData(); pthread_mutex_unlock(&S3fsCurl::curl_handles_lock); return true; } bool S3fsCurl::ClearInternalData(void) { if(hCurl){ return false; } type = REQTYPE_UNSET; path = ""; base_path = ""; saved_path= ""; url = ""; if(requestHeaders){ curl_slist_free_all(requestHeaders); requestHeaders = NULL; } responseHeaders.clear(); if(bodydata){ delete bodydata; bodydata = NULL; } if(headdata){ delete headdata; headdata = NULL; } LastResponseCode = -1; postdata = NULL; postdata_remaining = 0; retry_count = 0; b_infile = NULL; b_postdata = NULL; b_postdata_remaining = 0; b_partdata_startpos = 0; b_partdata_size = 0; partdata.clear(); S3FS_MALLOCTRIM(0); return true; } bool S3fsCurl::SetUseAhbe(bool ahbe) { bool old = is_use_ahbe; is_use_ahbe = ahbe; return old; } bool S3fsCurl::GetResponseCode(long& responseCode) { if(!hCurl){ return false; } responseCode = -1; if(CURLE_OK != curl_easy_getinfo(hCurl, CURLINFO_RESPONSE_CODE, &LastResponseCode)){ return false; } responseCode = LastResponseCode; return true; } // // Reset all options for retrying // bool S3fsCurl::RemakeHandle(void) { S3FS_PRN_INFO3("Retry request. [type=%d][url=%s][path=%s]", type, url.c_str(), path.c_str()); if(REQTYPE_UNSET == type){ return false; } // rewind file struct stat st; if(b_infile){ rewind(b_infile); if(-1 == fstat(fileno(b_infile), &st)){ S3FS_PRN_WARN("Could not get file stat(fd=%d)", fileno(b_infile)); return false; } } // reinitialize internal data responseHeaders.clear(); if(bodydata){ bodydata->Clear(); } if(headdata){ headdata->Clear(); } LastResponseCode = -1; // count up(only use for multipart) retry_count++; // set from backup postdata = b_postdata; postdata_remaining = b_postdata_remaining; partdata.startpos = b_partdata_startpos; partdata.size = b_partdata_size; // reset handle ResetHandle(); // set options switch(type){ case REQTYPE_DELETE: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); break; case REQTYPE_HEAD: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_NOBODY, true); curl_easy_setopt(hCurl, CURLOPT_FILETIME, true); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); // responseHeaders curl_easy_setopt(hCurl, CURLOPT_HEADERDATA, (void*)&responseHeaders); curl_easy_setopt(hCurl, CURLOPT_HEADERFUNCTION, HeaderCallback); break; case REQTYPE_PUTHEAD: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_INFILESIZE, 0); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); break; case REQTYPE_PUT: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); if(b_infile){ curl_easy_setopt(hCurl, CURLOPT_INFILESIZE_LARGE, static_cast(st.st_size)); curl_easy_setopt(hCurl, CURLOPT_INFILE, b_infile); }else{ curl_easy_setopt(hCurl, CURLOPT_INFILESIZE, 0); } break; case REQTYPE_GET: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, S3fsCurl::DownloadWriteCallback); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)this); break; case REQTYPE_CHKBUCKET: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); break; case REQTYPE_LISTBUCKET: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); break; case REQTYPE_PREMULTIPOST: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_POST, true); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_POSTFIELDSIZE, 0); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); break; case REQTYPE_COMPLETEMULTIPOST: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); curl_easy_setopt(hCurl, CURLOPT_POST, true); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_POSTFIELDSIZE, static_cast(postdata_remaining)); curl_easy_setopt(hCurl, CURLOPT_READDATA, (void*)this); curl_easy_setopt(hCurl, CURLOPT_READFUNCTION, S3fsCurl::ReadCallback); break; case REQTYPE_UPLOADMULTIPOST: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_HEADERDATA, (void*)headdata); curl_easy_setopt(hCurl, CURLOPT_HEADERFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_INFILESIZE_LARGE, static_cast(partdata.size)); curl_easy_setopt(hCurl, CURLOPT_READFUNCTION, S3fsCurl::UploadReadCallback); curl_easy_setopt(hCurl, CURLOPT_READDATA, (void*)this); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); break; case REQTYPE_COPYMULTIPOST: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_HEADERDATA, (void*)headdata); curl_easy_setopt(hCurl, CURLOPT_HEADERFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_INFILESIZE, 0); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); break; case REQTYPE_MULTILIST: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); break; case REQTYPE_IAMCRED: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); break; case REQTYPE_ABORTMULTIUPLOAD: curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); break; default: S3FS_PRN_ERR("request type is unknown(%d)", type); return false; } return true; } // // returns curl return code // int S3fsCurl::RequestPerform(void) { if(IS_S3FS_LOG_DBG()){ char* ptr_url = NULL; curl_easy_getinfo(hCurl, CURLINFO_EFFECTIVE_URL , &ptr_url); S3FS_PRN_DBG("connecting to URL %s", SAFESTRPTR(ptr_url)); } // 1 attempt + retries... for(int retrycnt = S3fsCurl::retries; 0 < retrycnt; retrycnt--){ // Requests CURLcode curlCode = curl_easy_perform(hCurl); // Check result switch(curlCode){ case CURLE_OK: // Need to look at the HTTP response code if(0 != curl_easy_getinfo(hCurl, CURLINFO_RESPONSE_CODE, &LastResponseCode)){ S3FS_PRN_ERR("curl_easy_getinfo failed while trying to retrieve HTTP response code"); return -EIO; } if(400 > LastResponseCode){ S3FS_PRN_INFO3("HTTP response code %ld", LastResponseCode); return 0; } if(500 <= LastResponseCode){ S3FS_PRN_INFO3("HTTP response code %ld", LastResponseCode); sleep(4); break; } // Service response codes which are >= 400 && < 500 switch(LastResponseCode){ case 400: S3FS_PRN_INFO3("HTTP response code 400 was returned, returing EIO."); S3FS_PRN_DBG("Body Text: %s", (bodydata ? bodydata->str() : "")); return -EIO; case 403: S3FS_PRN_INFO3("HTTP response code 403 was returned, returning EPERM"); S3FS_PRN_DBG("Body Text: %s", (bodydata ? bodydata->str() : "")); return -EPERM; case 404: S3FS_PRN_INFO3("HTTP response code 404 was returned, returning ENOENT"); S3FS_PRN_DBG("Body Text: %s", (bodydata ? bodydata->str() : "")); return -ENOENT; default: S3FS_PRN_INFO3("HTTP response code = %ld, returning EIO", LastResponseCode); S3FS_PRN_DBG("Body Text: %s", (bodydata ? bodydata->str() : "")); return -EIO; } break; case CURLE_WRITE_ERROR: S3FS_PRN_ERR("### CURLE_WRITE_ERROR"); sleep(2); break; case CURLE_OPERATION_TIMEDOUT: S3FS_PRN_ERR("### CURLE_OPERATION_TIMEDOUT"); sleep(2); break; case CURLE_COULDNT_RESOLVE_HOST: S3FS_PRN_ERR("### CURLE_COULDNT_RESOLVE_HOST"); sleep(2); break; case CURLE_COULDNT_CONNECT: S3FS_PRN_ERR("### CURLE_COULDNT_CONNECT"); sleep(4); break; case CURLE_GOT_NOTHING: S3FS_PRN_ERR("### CURLE_GOT_NOTHING"); sleep(4); break; case CURLE_ABORTED_BY_CALLBACK: S3FS_PRN_ERR("### CURLE_ABORTED_BY_CALLBACK"); sleep(4); S3fsCurl::curl_times[hCurl] = time(0); break; case CURLE_PARTIAL_FILE: S3FS_PRN_ERR("### CURLE_PARTIAL_FILE"); sleep(4); break; case CURLE_SEND_ERROR: S3FS_PRN_ERR("### CURLE_SEND_ERROR"); sleep(2); break; case CURLE_RECV_ERROR: S3FS_PRN_ERR("### CURLE_RECV_ERROR"); sleep(2); break; case CURLE_SSL_CONNECT_ERROR: S3FS_PRN_ERR("### CURLE_SSL_CONNECT_ERROR"); sleep(2); break; case CURLE_SSL_CACERT: S3FS_PRN_ERR("### CURLE_SSL_CACERT"); // try to locate cert, if successful, then set the // option and continue if(0 == S3fsCurl::curl_ca_bundle.size()){ if(!S3fsCurl::LocateBundle()){ S3FS_PRN_CRIT("could not get CURL_CA_BUNDLE."); exit(EXIT_FAILURE); } break; // retry with CAINFO } S3FS_PRN_CRIT("curlCode: %d msg: %s", curlCode, curl_easy_strerror(curlCode)); exit(EXIT_FAILURE); break; #ifdef CURLE_PEER_FAILED_VERIFICATION case CURLE_PEER_FAILED_VERIFICATION: S3FS_PRN_ERR("### CURLE_PEER_FAILED_VERIFICATION"); first_pos = bucket.find_first_of("."); if(first_pos != string::npos){ S3FS_PRN_INFO("curl returned a CURL_PEER_FAILED_VERIFICATION error"); S3FS_PRN_INFO("security issue found: buckets with periods in their name are incompatible with http"); S3FS_PRN_INFO("This check can be over-ridden by using the -o ssl_verify_hostname=0"); S3FS_PRN_INFO("The certificate will still be checked but the hostname will not be verified."); S3FS_PRN_INFO("A more secure method would be to use a bucket name without periods."); }else{ S3FS_PRN_INFO("my_curl_easy_perform: curlCode: %d -- %s", curlCode, curl_easy_strerror(curlCode)); } exit(EXIT_FAILURE); break; #endif // This should be invalid since curl option HTTP FAILONERROR is now off case CURLE_HTTP_RETURNED_ERROR: S3FS_PRN_ERR("### CURLE_HTTP_RETURNED_ERROR"); if(0 != curl_easy_getinfo(hCurl, CURLINFO_RESPONSE_CODE, &LastResponseCode)){ return -EIO; } S3FS_PRN_INFO3("HTTP response code =%ld", LastResponseCode); // Let's try to retrieve the if(404 == LastResponseCode){ return -ENOENT; } if(500 > LastResponseCode){ return -EIO; } break; // Unknown CURL return code default: S3FS_PRN_CRIT("###curlCode: %d msg: %s", curlCode, curl_easy_strerror(curlCode)); exit(EXIT_FAILURE); break; } S3FS_PRN_INFO("### retrying..."); if(!RemakeHandle()){ S3FS_PRN_INFO("Failed to reset handle and internal data for retrying."); return -EIO; } } S3FS_PRN_ERR("### giving up"); return -EIO; } // // Returns the Amazon AWS signature for the given parameters. // // @param method e.g., "GET" // @param content_type e.g., "application/x-directory" // @param date e.g., get_date_rfc850() // @param resource e.g., "/pub" // string S3fsCurl::CalcSignatureV2(string method, string strMD5, string content_type, string date, string resource) { string Signature; string StringToSign; if(0 < S3fsCurl::IAM_role.size()){ if(!S3fsCurl::CheckIAMCredentialUpdate()){ S3FS_PRN_ERR("Something error occurred in checking IAM credential."); return Signature; // returns empty string, then it occures error. } requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-security-token", S3fsCurl::AWSAccessToken.c_str()); } StringToSign += method + "\n"; StringToSign += strMD5 + "\n"; // md5 StringToSign += content_type + "\n"; StringToSign += date + "\n"; StringToSign += get_canonical_headers(requestHeaders, true); StringToSign += resource; const void* key = S3fsCurl::AWSSecretAccessKey.data(); int key_len = S3fsCurl::AWSSecretAccessKey.size(); const unsigned char* sdata = reinterpret_cast(StringToSign.data()); int sdata_len = StringToSign.size(); unsigned char* md = NULL; unsigned int md_len = 0;; s3fs_HMAC(key, key_len, sdata, sdata_len, &md, &md_len); char* base64; if(NULL == (base64 = s3fs_base64(md, md_len))){ free(md); return string(""); // ENOMEM } free(md); Signature = base64; free(base64); return Signature; } string S3fsCurl::CalcSignature(string method, string canonical_uri, string query_string, string strdate, string payload_hash, string date8601) { string Signature, StringCQ, StringToSign; string uriencode; if(0 < S3fsCurl::IAM_role.size()){ if(!S3fsCurl::CheckIAMCredentialUpdate()){ S3FS_PRN_ERR("Something error occurred in checking IAM credential."); return Signature; // returns empty string, then it occures error. } requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-security-token", S3fsCurl::AWSAccessToken.c_str()); } uriencode = urlEncode(canonical_uri); StringCQ = method + "\n"; if(0 == strcmp(method.c_str(),"HEAD") || 0 == strcmp(method.c_str(),"PUT") || 0 == strcmp(method.c_str(),"DELETE")){ StringCQ += uriencode + "\n" + query_string + "\n"; }else if (0 == strcmp(method.c_str(), "GET") && 0 == strcmp(uriencode.c_str(), "")) { StringCQ +="/\n\n"; }else if (0 == strcmp(method.c_str(), "GET") && 0 == strncmp(uriencode.c_str(), "/", 1)) { StringCQ += uriencode +"\n\n"; }else if (0 == strcmp(method.c_str(), "GET") && 0 != strncmp(uriencode.c_str(), "/", 1)) { StringCQ += "/\n" + urlEncode2(canonical_uri) +"\n"; }else if (0 == strcmp(method.c_str(), "POST")) { StringCQ += uriencode +"\n" + query_string +"\n"; } StringCQ += get_canonical_headers(requestHeaders) + "\n"; StringCQ += get_sorted_header_keys(requestHeaders) + "\n"; StringCQ += payload_hash; char kSecret[128]; unsigned char *kDate, *kRegion, *kService, *kSigning, *sRequest = NULL; unsigned int kDate_len,kRegion_len, kService_len, kSigning_len, sRequest_len = 0; char hexsRequest[64 + 1]; int kSecret_len = snprintf(kSecret, sizeof(kSecret), "AWS4%s", S3fsCurl::AWSSecretAccessKey.c_str()); unsigned int cnt; s3fs_HMAC256(kSecret, kSecret_len, reinterpret_cast(strdate.data()), strdate.size(), &kDate, &kDate_len); s3fs_HMAC256(kDate, kDate_len, reinterpret_cast(endpoint.c_str()), endpoint.size(), &kRegion, &kRegion_len); s3fs_HMAC256(kRegion, kRegion_len, reinterpret_cast("s3"), sizeof("s3") - 1, &kService, &kService_len); s3fs_HMAC256(kService, kService_len, reinterpret_cast("aws4_request"), sizeof("aws4_request") - 1, &kSigning, &kSigning_len); free(kDate); free(kRegion); free(kService); const unsigned char* cRequest = reinterpret_cast(StringCQ.c_str()); unsigned int cRequest_len = StringCQ.size(); s3fs_sha256(cRequest, cRequest_len, &sRequest, &sRequest_len); for(cnt = 0; cnt < sRequest_len; cnt++){ sprintf(&hexsRequest[cnt * 2], "%02x", sRequest[cnt]); } free(sRequest); StringToSign = "AWS4-HMAC-SHA256\n"; StringToSign += date8601 + "\n"; StringToSign += strdate + "/" + endpoint + "/s3/aws4_request\n"; StringToSign += hexsRequest; const unsigned char* cscope = reinterpret_cast(StringToSign.c_str()); unsigned int cscope_len = StringToSign.size(); unsigned char* md = NULL; unsigned int md_len = 0; char hexSig[64 + 1]; s3fs_HMAC256(kSigning, kSigning_len, cscope, cscope_len, &md, &md_len); for(cnt = 0; cnt < md_len; cnt++){ sprintf(&hexSig[cnt * 2], "%02x", md[cnt]); } free(kSigning); free(md); Signature = hexSig; return Signature; } // XML in BodyData has UploadId, Parse XML body for UploadId bool S3fsCurl::GetUploadId(string& upload_id) { bool result = false; if(!bodydata){ return result; } upload_id.clear(); xmlDocPtr doc; if(NULL == (doc = xmlReadMemory(bodydata->str(), bodydata->size(), "", NULL, 0))){ return result; } if(NULL == doc->children){ S3FS_XMLFREEDOC(doc); return result; } for(xmlNodePtr cur_node = doc->children->children; NULL != cur_node; cur_node = cur_node->next){ // For DEBUG // string cur_node_name(reinterpret_cast(cur_node->name)); // printf("cur_node_name: %s\n", cur_node_name.c_str()); if(XML_ELEMENT_NODE == cur_node->type){ string elementName = reinterpret_cast(cur_node->name); // For DEBUG // printf("elementName: %s\n", elementName.c_str()); if(cur_node->children){ if(XML_TEXT_NODE == cur_node->children->type){ if(elementName == "UploadId") { upload_id = reinterpret_cast(cur_node->children->content); result = true; break; } } } } } S3FS_XMLFREEDOC(doc); return result; } void S3fsCurl::insertV4Headers(const string &op, const string &path, const string &query_string, const string &payload_hash) { S3FS_PRN_INFO3("computing signature [%s] [%s] [%s] [%s]", op.c_str(), path.c_str(), query_string.c_str(), payload_hash.c_str()); string strdate; string date8601; get_date_sigv3(strdate, date8601); string contentSHA256 = payload_hash.empty() ? empty_payload_hash : payload_hash; //string canonical_headers, signed_headers; requestHeaders = curl_slist_sort_insert(requestHeaders, "host", get_bucket_host().c_str()); requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-content-sha256", contentSHA256.c_str()); requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-date", date8601.c_str()); if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignature(op, path, query_string, strdate, contentSHA256, date8601); string auth = "AWS4-HMAC-SHA256 Credential=" + AWSAccessKeyId + "/" + strdate + "/" + endpoint + "/s3/aws4_request, SignedHeaders=" + get_sorted_header_keys(requestHeaders) + ", Signature=" + Signature; requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", auth.c_str()); } } int S3fsCurl::DeleteRequest(const char* tpath) { S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(!tpath){ return -1; } if(!CreateCurlHandle(true)){ return -1; } string resource; string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = NULL; responseHeaders.clear(); if(!S3fsCurl::is_sigv4){ string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", NULL); if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignatureV2("DELETE", "", "", date, resource); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", string("AWS " + AWSAccessKeyId + ":" + Signature).c_str()); } }else{ insertV4Headers("DELETE", path, "", ""); } curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); type = REQTYPE_DELETE; return RequestPerform(); } // // Get AccessKeyId/SecretAccessKey/AccessToken/Expiration by IAM role, // and Set these value to class valiable. // int S3fsCurl::GetIAMCredentials(void) { S3FS_PRN_INFO3("[IAM role=%s]", S3fsCurl::IAM_role.c_str()); if(0 == S3fsCurl::IAM_role.size()){ S3FS_PRN_ERR("IAM role name is empty."); return -EIO; } // at first set type for handle type = REQTYPE_IAMCRED; if(!CreateCurlHandle(true)){ return -EIO; } // url url = string(IAM_CRED_URL) + S3fsCurl::IAM_role; requestHeaders = NULL; responseHeaders.clear(); bodydata = new BodyData(); curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); int result = RequestPerform(); // analizing response if(0 == result && !S3fsCurl::SetIAMCredentials(bodydata->str())){ S3FS_PRN_ERR("Something error occurred, could not get IAM credential."); } delete bodydata; bodydata = NULL; return result; } bool S3fsCurl::AddSseRequestHead(sse_type_t ssetype, string& ssevalue, bool is_only_c, bool is_copy) { if(SSE_S3 == ssetype){ if(!is_only_c){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-server-side-encryption", "AES256"); } }else if(SSE_C == ssetype){ string sseckey; if(S3fsCurl::GetSseKey(ssevalue, sseckey)){ if(is_copy){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-copy-source-server-side-encryption-customer-algorithm", "AES256"); requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-copy-source-server-side-encryption-customer-key", sseckey.c_str()); requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-copy-source-server-side-encryption-customer-key-md5", ssevalue.c_str()); }else{ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-server-side-encryption-customer-algorithm", "AES256"); requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-server-side-encryption-customer-key", sseckey.c_str()); requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-server-side-encryption-customer-key-md5", ssevalue.c_str()); } }else{ S3FS_PRN_WARN("Failed to insert SSE-C header."); } }else if(SSE_KMS == ssetype){ if(!is_only_c){ if(ssevalue.empty()){ ssevalue = S3fsCurl::GetSseKmsId(); } requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-server-side-encryption", "aws:kms"); requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-server-side-encryption-aws-kms-key-id", ssevalue.c_str()); } } return true; } // // tpath : target path for head request // bpath : saved into base_path // savedpath : saved into saved_path // ssekey_pos : -1 means "not" SSE-C type // 0 - X means SSE-C type and position for SSE-C key(0 is latest key) // bool S3fsCurl::PreHeadRequest(const char* tpath, const char* bpath, const char* savedpath, int ssekey_pos) { S3FS_PRN_INFO3("[tpath=%s][bpath=%s][save=%s][sseckeypos=%d]", SAFESTRPTR(tpath), SAFESTRPTR(bpath), SAFESTRPTR(savedpath), ssekey_pos); if(!tpath){ return false; } if(!CreateCurlHandle(true)){ return false; } string resource; string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); // libcurl 7.17 does deep copy of url, deep copy "stable" url url = prepare_url(turl.c_str()); path = get_realpath(tpath); base_path = SAFESTRPTR(bpath); saved_path = SAFESTRPTR(savedpath); requestHeaders = NULL; responseHeaders.clear(); // requestHeaders if(0 <= ssekey_pos){ string md5(""); if(!S3fsCurl::GetSseKeyMd5(ssekey_pos, md5) || !AddSseRequestHead(SSE_C, md5, true, false)){ S3FS_PRN_ERR("Failed to set SSE-C headers for sse-c key pos(%d)(=md5(%s)).", ssekey_pos, md5.c_str()); return false; } } b_ssekey_pos = ssekey_pos; if(!S3fsCurl::is_sigv4){ string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", NULL); if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignatureV2("HEAD", "", "", date, resource); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", string("AWS " + AWSAccessKeyId + ":" + Signature).c_str()); } }else{ insertV4Headers("HEAD", path, "", ""); } curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_NOBODY, true); // HEAD curl_easy_setopt(hCurl, CURLOPT_FILETIME, true); // Last-Modified curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); // responseHeaders curl_easy_setopt(hCurl, CURLOPT_HEADERDATA, (void*)&responseHeaders); curl_easy_setopt(hCurl, CURLOPT_HEADERFUNCTION, HeaderCallback); type = REQTYPE_HEAD; return true; } int S3fsCurl::HeadRequest(const char* tpath, headers_t& meta) { int result = -1; S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); // At first, try to get without SSE-C headers if(!PreHeadRequest(tpath) || 0 != (result = RequestPerform())){ // If has SSE-C keys, try to get with all SSE-C keys. for(int pos = 0; static_cast(pos) < S3fsCurl::sseckeys.size(); pos++){ if(!DestroyCurlHandle()){ return result; } if(!PreHeadRequest(tpath, NULL, NULL, pos)){ return result; } if(0 == (result = RequestPerform())){ break; } } if(0 != result){ DestroyCurlHandle(); // not check result. return result; } } // file exists in s3 // fixme: clean this up. meta.clear(); for(headers_t::iterator iter = responseHeaders.begin(); iter != responseHeaders.end(); ++iter){ string key = lower(iter->first); string value = iter->second; if(key == "content-type"){ meta[iter->first] = value; }else if(key == "content-length"){ meta[iter->first] = value; }else if(key == "etag"){ meta[iter->first] = value; }else if(key == "last-modified"){ meta[iter->first] = value; }else if(key.substr(0, 5) == "x-amz"){ meta[key] = value; // key is lower case for "x-amz" } } return 0; } int S3fsCurl::PutHeadRequest(const char* tpath, headers_t& meta, bool is_copy) { S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(!tpath){ return -1; } if(!CreateCurlHandle(true)){ return -1; } string resource; string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = NULL; responseHeaders.clear(); bodydata = new BodyData(); // Make request headers string ContentType; for(headers_t::iterator iter = meta.begin(); iter != meta.end(); ++iter){ string key = lower(iter->first); string value = iter->second; if(key == "content-type"){ ContentType = value; requestHeaders = curl_slist_sort_insert(requestHeaders, iter->first.c_str(), value.c_str()); }else if(key.substr(0, 9) == "x-amz-acl"){ // not set value, but after set it. }else if(key.substr(0, 10) == "x-amz-meta"){ requestHeaders = curl_slist_sort_insert(requestHeaders, iter->first.c_str(), value.c_str()); }else if(key == "x-amz-copy-source"){ requestHeaders = curl_slist_sort_insert(requestHeaders, iter->first.c_str(), value.c_str()); }else if(key == "x-amz-server-side-encryption"){ // skip this header, because this header is specified after logic. }else if(key == "x-amz-server-side-encryption-customer-algorithm"){ // skip this header, because this header is specified with "x-amz-...-customer-key-md5". }else if(is_copy && key == "x-amz-server-side-encryption-customer-key-md5"){ // Only copy mode. if(!AddSseRequestHead(SSE_C, value, true, is_copy)){ S3FS_PRN_WARN("Failed to insert SSE-C header."); } } } // "x-amz-acl", storage class, sse requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-acl", S3fsCurl::default_acl.c_str()); if(REDUCED_REDUNDANCY == GetStorageClass()){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-storage-class", "REDUCED_REDUNDANCY"); } else if(STANDARD_IA == GetStorageClass()){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-storage-class", "STANDARD_IA"); } // SSE string ssevalue(""); if(!AddSseRequestHead(S3fsCurl::GetSseType(), ssevalue, true, false)){ S3FS_PRN_WARN("Failed to set SSE header, but continue..."); } if(is_use_ahbe){ // set additional header by ahbe conf requestHeaders = AdditionalHeader::get()->AddHeader(requestHeaders, tpath); } if(!S3fsCurl::is_sigv4){ string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignatureV2("PUT", "", ContentType, date, resource); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", string("AWS " + AWSAccessKeyId + ":" + Signature).c_str()); } }else{ insertV4Headers("PUT", path, "", ""); } // setopt curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true); // HTTP PUT curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_INFILESIZE, 0); // Content-Length curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); type = REQTYPE_PUTHEAD; S3FS_PRN_INFO3("copying... [path=%s]", tpath); int result = RequestPerform(); delete bodydata; bodydata = NULL; return result; } int S3fsCurl::PutRequest(const char* tpath, headers_t& meta, int fd) { struct stat st; FILE* file = NULL; int fd2; S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(!tpath){ return -1; } if(-1 != fd){ // duplicate fd if(-1 == (fd2 = dup(fd)) || -1 == fstat(fd2, &st) || 0 != lseek(fd2, 0, SEEK_SET) || NULL == (file = fdopen(fd2, "rb"))){ S3FS_PRN_ERR("Could not duplicate file discriptor(errno=%d)", errno); if(-1 != fd2){ close(fd2); } return -errno; } b_infile = file; }else{ // This case is creating zero byte obejct.(calling by create_file_object()) S3FS_PRN_INFO3("create zero byte file object."); } if(!CreateCurlHandle(true)){ if(file){ fclose(file); } return -1; } string resource; string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = NULL; responseHeaders.clear(); bodydata = new BodyData(); // Make request headers string strMD5; if(-1 != fd && S3fsCurl::is_content_md5){ strMD5 = s3fs_get_content_md5(fd); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-MD5", strMD5.c_str()); } string ContentType; for(headers_t::iterator iter = meta.begin(); iter != meta.end(); ++iter){ string key = lower(iter->first); string value = iter->second; if(key == "content-type"){ ContentType = value; requestHeaders = curl_slist_sort_insert(requestHeaders, iter->first.c_str(), value.c_str()); }else if(key.substr(0, 9) == "x-amz-acl"){ // not set value, but after set it. }else if(key.substr(0, 10) == "x-amz-meta"){ requestHeaders = curl_slist_sort_insert(requestHeaders, iter->first.c_str(), value.c_str()); }else if(key == "x-amz-server-side-encryption"){ // skip this header, because this header is specified after logic. }else if(key == "x-amz-server-side-encryption-customer-algorithm"){ // skip this header, because this header is specified after logic. }else if(key == "x-amz-server-side-encryption-customer-key-md5"){ // skip this header, because this header is specified after logic. } } // "x-amz-acl", storage class, sse requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-acl", S3fsCurl::default_acl.c_str()); if(REDUCED_REDUNDANCY == GetStorageClass()){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-storage-class", "REDUCED_REDUNDANCY"); } else if(STANDARD_IA == GetStorageClass()){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-storage-class", "STANDARD_IA"); } // SSE string ssevalue(""); if(!AddSseRequestHead(S3fsCurl::GetSseType(), ssevalue, false, false)){ S3FS_PRN_WARN("Failed to set SSE header, but continue..."); } if(is_use_ahbe){ // set additional header by ahbe conf requestHeaders = AdditionalHeader::get()->AddHeader(requestHeaders, tpath); } if(!S3fsCurl::is_sigv4){ string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignatureV2("PUT", strMD5, ContentType, date, resource); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", string("AWS " + AWSAccessKeyId + ":" + Signature).c_str()); } }else{ string payload_hash = s3fs_sha256sum(fd, 0, -1); insertV4Headers("PUT", path, "", payload_hash); } // setopt curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true); // HTTP PUT curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); if(file){ curl_easy_setopt(hCurl, CURLOPT_INFILESIZE_LARGE, static_cast(st.st_size)); // Content-Length curl_easy_setopt(hCurl, CURLOPT_INFILE, file); }else{ curl_easy_setopt(hCurl, CURLOPT_INFILESIZE, 0); // Content-Length: 0 } type = REQTYPE_PUT; S3FS_PRN_INFO3("uploading... [path=%s][fd=%d][size=%jd]", tpath, fd, (intmax_t)(-1 != fd ? st.st_size : 0)); int result = RequestPerform(); delete bodydata; bodydata = NULL; if(file){ fclose(file); } return result; } int S3fsCurl::PreGetObjectRequest(const char* tpath, int fd, off_t start, ssize_t size, sse_type_t ssetype, string& ssevalue) { S3FS_PRN_INFO3("[tpath=%s][start=%jd][size=%zd]", SAFESTRPTR(tpath), (intmax_t)start, size); if(!tpath || -1 == fd || 0 > start || 0 >= size){ return -1; } if(!CreateCurlHandle(true)){ return -1; } string resource; string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = NULL; responseHeaders.clear(); if(-1 != start && -1 != size){ string range = "bytes="; range += str(start); range += "-"; range += str(start + size - 1); requestHeaders = curl_slist_sort_insert(requestHeaders, "Range", range.c_str()); } // SSE if(!AddSseRequestHead(ssetype, ssevalue, true, false)){ S3FS_PRN_WARN("Failed to set SSE header, but continue..."); } if(!S3fsCurl::is_sigv4){ string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", NULL); if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignatureV2("GET", "", "", date, resource); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", string("AWS " + AWSAccessKeyId + ":" + Signature).c_str()); } }else{ insertV4Headers("GET", path, "", ""); } // setopt curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, S3fsCurl::DownloadWriteCallback); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)this); // set info for callback func. // (use only fd, startpos and size, other member is not used.) partdata.clear(); partdata.fd = fd; partdata.startpos = start; partdata.size = size; b_partdata_startpos = start; b_partdata_size = size; b_ssetype = ssetype; b_ssevalue = ssevalue; b_ssekey_pos = -1; // not use this value for get object. type = REQTYPE_GET; return 0; } int S3fsCurl::GetObjectRequest(const char* tpath, int fd, off_t start, ssize_t size) { int result; S3FS_PRN_INFO3("[tpath=%s][start=%jd][size=%zd]", SAFESTRPTR(tpath), (intmax_t)start, size); if(!tpath){ return -1; } sse_type_t ssetype; string ssevalue; if(!get_object_sse_type(tpath, ssetype, ssevalue)){ S3FS_PRN_WARN("Failed to get SSE type for file(%s).", SAFESTRPTR(tpath)); } if(0 != (result = PreGetObjectRequest(tpath, fd, start, size, ssetype, ssevalue))){ return result; } S3FS_PRN_INFO3("downloading... [path=%s][fd=%d]", tpath, fd); result = RequestPerform(); partdata.clear(); return result; } int S3fsCurl::CheckBucket(void) { S3FS_PRN_INFO3("check a bucket."); if(!CreateCurlHandle(true)){ return -1; } string resource; string turl; MakeUrlResource(get_realpath("/").c_str(), resource, turl); url = prepare_url(turl.c_str()); path = get_realpath("/"); requestHeaders = NULL; responseHeaders.clear(); bodydata = new BodyData(); if(!S3fsCurl::is_sigv4){ string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignatureV2("GET", "", "", date, resource); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", string("AWS " + AWSAccessKeyId + ":" + Signature).c_str()); } }else{ insertV4Headers("GET", path, "", ""); } // setopt curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); type = REQTYPE_CHKBUCKET; int result = RequestPerform(); if (result != 0) { S3FS_PRN_ERR("Check bucket failed, S3 response: %s", (bodydata ? bodydata->str() : "")); } return result; } int S3fsCurl::ListBucketRequest(const char* tpath, const char* query) { S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(!tpath){ return -1; } if(!CreateCurlHandle(true)){ return -1; } string resource; string turl; MakeUrlResource("", resource, turl); // NOTICE: path is "". if(query){ turl += "?"; turl += query; } url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = NULL; responseHeaders.clear(); bodydata = new BodyData(); if(!S3fsCurl::is_sigv4){ string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", NULL); if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignatureV2("GET", "", "", date, (resource + "/")); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", string("AWS " + AWSAccessKeyId + ":" + Signature).c_str()); } }else{ insertV4Headers("GET", query, "", ""); } // setopt curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); type = REQTYPE_LISTBUCKET; return RequestPerform(); } // // Initialize multipart upload // // Example : // POST /example-object?uploads HTTP/1.1 // Host: example-bucket.s3.amazonaws.com // Date: Mon, 1 Nov 2010 20:34:56 GMT // Authorization: AWS VGhpcyBtZXNzYWdlIHNpZ25lZCBieSBlbHZpbmc= // int S3fsCurl::PreMultipartPostRequest(const char* tpath, headers_t& meta, string& upload_id, bool is_copy) { S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(!tpath){ return -1; } if(!CreateCurlHandle(true)){ return -1; } string resource; string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); string query_string = "uploads"; if(S3fsCurl::is_sigv4){ query_string += "="; } turl += "?" + query_string; resource += "?" + query_string; url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = NULL; bodydata = new BodyData(); responseHeaders.clear(); string contype = S3fsCurl::LookupMimeType(string(tpath)); for(headers_t::iterator iter = meta.begin(); iter != meta.end(); ++iter){ string key = lower(iter->first); string value = iter->second; if(key.substr(0, 9) == "x-amz-acl"){ // not set value, but after set it. }else if(key.substr(0, 10) == "x-amz-meta"){ requestHeaders = curl_slist_sort_insert(requestHeaders, iter->first.c_str(), value.c_str()); }else if(key == "x-amz-server-side-encryption"){ // skip this header, because this header is specified after logic. }else if(key == "x-amz-server-side-encryption-customer-algorithm"){ // skip this header, because this header is specified with "x-amz-...-customer-key-md5". }else if(is_copy && key == "x-amz-server-side-encryption-customer-key-md5"){ // Only copy mode. if(!AddSseRequestHead(SSE_C, value, false, is_copy)){ S3FS_PRN_WARN("Failed to insert SSE-C header."); } } } // "x-amz-acl", storage class, sse requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-acl", S3fsCurl::default_acl.c_str()); if(REDUCED_REDUNDANCY == GetStorageClass()){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-storage-class", "REDUCED_REDUNDANCY"); } else if(STANDARD_IA == GetStorageClass()){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-storage-class", "STANDARD_IA"); } // SSE string ssevalue(""); if(!AddSseRequestHead(S3fsCurl::GetSseType(), ssevalue, false, false)){ S3FS_PRN_WARN("Failed to set SSE header, but continue..."); } if(is_use_ahbe){ // set additional header by ahbe conf requestHeaders = AdditionalHeader::get()->AddHeader(requestHeaders, tpath); } if(!S3fsCurl::is_sigv4){ string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); requestHeaders = curl_slist_sort_insert(requestHeaders, "Accept", NULL); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Length", NULL); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", contype.c_str()); if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignatureV2("POST", "", contype, date, resource); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", string("AWS " + AWSAccessKeyId + ":" + Signature).c_str()); } }else{ requestHeaders = curl_slist_sort_insert(requestHeaders, "Accept", NULL); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Length", NULL); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", contype.c_str()); insertV4Headers("POST", path, query_string, ""); } // setopt curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_POST, true); // POST curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_POSTFIELDSIZE, 0); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); type = REQTYPE_PREMULTIPOST; // request int result; if(0 != (result = RequestPerform())){ delete bodydata; bodydata = NULL; return result; } // Parse XML body for UploadId if(!S3fsCurl::GetUploadId(upload_id)){ delete bodydata; bodydata = NULL; return -1; } delete bodydata; bodydata = NULL; return 0; } int S3fsCurl::CompleteMultipartPostRequest(const char* tpath, string& upload_id, etaglist_t& parts) { S3FS_PRN_INFO3("[tpath=%s][parts=%zu]", SAFESTRPTR(tpath), parts.size()); if(!tpath){ return -1; } // make contents string postContent; postContent += "\n"; for(int cnt = 0; cnt < (int)parts.size(); cnt++){ if(0 == parts[cnt].length()){ S3FS_PRN_ERR("%d file part is not finished uploading.", cnt + 1); return -1; } postContent += "\n"; postContent += " " + str(cnt + 1) + "\n"; postContent += " \"" + parts[cnt] + "\"\n"; postContent += "\n"; } postContent += "\n"; // set postdata postdata = reinterpret_cast(postContent.c_str()); b_postdata = postdata; postdata_remaining = postContent.size(); // without null b_postdata_remaining = postdata_remaining; if(!CreateCurlHandle(true)){ return -1; } string resource; string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); string query_string = "uploadId=" + upload_id; turl += "?" + query_string; resource += "?" + query_string; url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = NULL; bodydata = new BodyData(); responseHeaders.clear(); string contype = S3fsCurl::LookupMimeType(string(tpath)); if(!S3fsCurl::is_sigv4){ string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); requestHeaders = curl_slist_sort_insert(requestHeaders, "Accept", NULL); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", contype.c_str()); if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignatureV2("POST", "", contype, date, resource); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", string("AWS " + AWSAccessKeyId + ":" + Signature).c_str()); } }else{ string payload_hash; const unsigned char* cRequest = reinterpret_cast(postContent.c_str()); unsigned int cRequest_len = postContent.size(); unsigned char* sRequest = NULL; unsigned int sRequest_len = 0; char hexsRequest[64 + 1]; unsigned int cnt; s3fs_sha256(cRequest, cRequest_len, &sRequest, &sRequest_len); for(cnt = 0; cnt < sRequest_len; cnt++){ sprintf(&hexsRequest[cnt * 2], "%02x", sRequest[cnt]); } free(sRequest); payload_hash.assign(hexsRequest, &hexsRequest[sRequest_len * 2]); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", get_date_rfc850().c_str()); requestHeaders = curl_slist_sort_insert(requestHeaders, "Accept", NULL); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", contype.c_str()); insertV4Headers("POST", path, query_string, payload_hash); } // setopt curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); curl_easy_setopt(hCurl, CURLOPT_POST, true); // POST curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_POSTFIELDSIZE, static_cast(postdata_remaining)); curl_easy_setopt(hCurl, CURLOPT_READDATA, (void*)this); curl_easy_setopt(hCurl, CURLOPT_READFUNCTION, S3fsCurl::ReadCallback); type = REQTYPE_COMPLETEMULTIPOST; // request int result = RequestPerform(); delete bodydata; bodydata = NULL; postdata = NULL; return result; } int S3fsCurl::MultipartListRequest(string& body) { S3FS_PRN_INFO3("list request(multipart)"); if(!CreateCurlHandle(true)){ return -1; } string resource; string turl; path = get_realpath("/"); MakeUrlResource(path.c_str(), resource, turl); turl += "?uploads"; resource += "?uploads"; url = prepare_url(turl.c_str()); requestHeaders = NULL; responseHeaders.clear(); bodydata = new BodyData(); if(!S3fsCurl::is_sigv4){ string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); requestHeaders = curl_slist_sort_insert(requestHeaders, "Accept", NULL); if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignatureV2("GET", "", "", date, resource); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", string("AWS " + AWSAccessKeyId + ":" + Signature).c_str()); } }else{ insertV4Headers("GET", path, "", ""); } // setopt curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); type = REQTYPE_MULTILIST; int result; if(0 == (result = RequestPerform()) && 0 < bodydata->size()){ body = bodydata->str(); }else{ body = ""; } delete bodydata; bodydata = NULL; return result; } int S3fsCurl::AbortMultipartUpload(const char* tpath, string& upload_id) { S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(!tpath){ return -1; } if(!CreateCurlHandle(true)){ return -1; } string resource; string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); turl += "?uploadId=" + upload_id; resource += "?uploadId=" + upload_id; url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = NULL; responseHeaders.clear(); if(!S3fsCurl::is_sigv4){ string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignatureV2("DELETE", "", "", date, resource); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", string("AWS " + AWSAccessKeyId + ":" + Signature).c_str()); } }else{ insertV4Headers("DELETE", path, "", ""); } curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); type = REQTYPE_ABORTMULTIUPLOAD; return RequestPerform(); } // // PUT /ObjectName?partNumber=PartNumber&uploadId=UploadId HTTP/1.1 // Host: BucketName.s3.amazonaws.com // Date: date // Content-Length: Size // Authorization: Signature // // PUT /my-movie.m2ts?partNumber=1&uploadId=VCVsb2FkIElEIGZvciBlbZZpbmcncyBteS1tb3ZpZS5tMnRzIHVwbG9hZR HTTP/1.1 // Host: example-bucket.s3.amazonaws.com // Date: Mon, 1 Nov 2010 20:34:56 GMT // Content-Length: 10485760 // Content-MD5: pUNXr/BjKK5G2UKvaRRrOA== // Authorization: AWS VGhpcyBtZXNzYWdlIHNpZ25lZGGieSRlbHZpbmc= // int S3fsCurl::UploadMultipartPostSetup(const char* tpath, int part_num, string& upload_id) { S3FS_PRN_INFO3("[tpath=%s][start=%jd][size=%zd][part=%d]", SAFESTRPTR(tpath), (intmax_t)(partdata.startpos), partdata.size, part_num); if(-1 == partdata.fd || -1 == partdata.startpos || -1 == partdata.size){ return -1; } // make md5 and file pointer unsigned char *md5raw = s3fs_md5hexsum(partdata.fd, partdata.startpos, partdata.size); if(md5raw == NULL){ S3FS_PRN_ERR("Could not make md5 for file(part %d)", part_num); return -1; } partdata.etag = s3fs_hex(md5raw, get_md5_digest_length()); char* md5base64p = s3fs_base64(md5raw, get_md5_digest_length()); std::string md5base64 = md5base64p; free(md5base64p); free(md5raw); // create handle if(!CreateCurlHandle(true)){ return -1; } // make request string request_uri = "partNumber=" + str(part_num) + "&uploadId=" + upload_id; string urlargs = "?" + request_uri; string resource; string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); resource += urlargs; turl += urlargs; url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = NULL; bodydata = new BodyData(); headdata = new BodyData(); responseHeaders.clear(); if(!S3fsCurl::is_sigv4){ string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); requestHeaders = curl_slist_sort_insert(requestHeaders, "Accept", NULL); string strMD5; if(S3fsCurl::is_content_md5){ strMD5 = md5base64; requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-MD5", strMD5.c_str()); } if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignatureV2("PUT", strMD5, "", date, resource); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", string("AWS " + AWSAccessKeyId + ":" + Signature).c_str()); } }else{ string payload_hash = s3fs_sha256sum(partdata.fd, partdata.startpos, partdata.size); insertV4Headers("PUT", path, request_uri, payload_hash); } // setopt curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true); // HTTP PUT curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_HEADERDATA, (void*)headdata); curl_easy_setopt(hCurl, CURLOPT_HEADERFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_INFILESIZE_LARGE, static_cast(partdata.size)); // Content-Length curl_easy_setopt(hCurl, CURLOPT_READFUNCTION, S3fsCurl::UploadReadCallback); curl_easy_setopt(hCurl, CURLOPT_READDATA, (void*)this); curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); type = REQTYPE_UPLOADMULTIPOST; return 0; } int S3fsCurl::UploadMultipartPostRequest(const char* tpath, int part_num, string& upload_id) { int result; S3FS_PRN_INFO3("[tpath=%s][start=%jd][size=%zd][part=%d]", SAFESTRPTR(tpath), (intmax_t)(partdata.startpos), partdata.size, part_num); // setup if(0 != (result = S3fsCurl::UploadMultipartPostSetup(tpath, part_num, upload_id))){ return result; } // request if(0 == (result = RequestPerform())){ // check etag if(NULL != strstr(headdata->str(), partdata.etag.c_str())){ partdata.uploaded = true; }else{ result = -1; } } // closing delete bodydata; bodydata = NULL; delete headdata; headdata = NULL; return result; } int S3fsCurl::CopyMultipartPostRequest(const char* from, const char* to, int part_num, string& upload_id, headers_t& meta) { S3FS_PRN_INFO3("[from=%s][to=%s][part=%d]", SAFESTRPTR(from), SAFESTRPTR(to), part_num); if(!from || !to){ return -1; } if(!CreateCurlHandle(true)){ return -1; } string urlargs = "?partNumber=" + str(part_num) + "&uploadId=" + upload_id; string resource; string turl; MakeUrlResource(get_realpath(to).c_str(), resource, turl); resource += urlargs; turl += urlargs; url = prepare_url(turl.c_str()); path = get_realpath(to); requestHeaders = NULL; responseHeaders.clear(); bodydata = new BodyData(); headdata = new BodyData(); // Make request headers string ContentType; for(headers_t::iterator iter = meta.begin(); iter != meta.end(); ++iter){ string key = lower(iter->first); string value = iter->second; if(key == "content-type"){ ContentType = value; requestHeaders = curl_slist_sort_insert(requestHeaders, iter->first.c_str(), value.c_str()); }else if(key == "x-amz-copy-source"){ requestHeaders = curl_slist_sort_insert(requestHeaders, iter->first.c_str(), value.c_str()); }else if(key == "x-amz-copy-source-range"){ requestHeaders = curl_slist_sort_insert(requestHeaders, iter->first.c_str(), value.c_str()); } // NOTICE: x-amz-acl, x-amz-server-side-encryption is not set! } if(!S3fsCurl::is_sigv4){ string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); if(!S3fsCurl::IsPublicBucket()){ string Signature = CalcSignatureV2("PUT", "", ContentType, date, resource); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", string("AWS " + AWSAccessKeyId + ":" + Signature).c_str()); } }else{ insertV4Headers("PUT", path, "", ""); } // setopt curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str()); curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true); // HTTP PUT curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, (void*)bodydata); curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_HEADERDATA, (void*)headdata); curl_easy_setopt(hCurl, CURLOPT_HEADERFUNCTION, WriteMemoryCallback); curl_easy_setopt(hCurl, CURLOPT_INFILESIZE, 0); // Content-Length curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders); type = REQTYPE_COPYMULTIPOST; // request S3FS_PRN_INFO3("copying... [from=%s][to=%s][part=%d]", from, to, part_num); int result = RequestPerform(); if(0 == result){ // parse ETag from response xmlDocPtr doc; if(NULL == (doc = xmlReadMemory(bodydata->str(), bodydata->size(), "", NULL, 0))){ return result; } if(NULL == doc->children){ S3FS_XMLFREEDOC(doc); return result; } for(xmlNodePtr cur_node = doc->children->children; NULL != cur_node; cur_node = cur_node->next){ if(XML_ELEMENT_NODE == cur_node->type){ string elementName = reinterpret_cast(cur_node->name); if(cur_node->children){ if(XML_TEXT_NODE == cur_node->children->type){ if(elementName == "ETag") { string etag = reinterpret_cast(cur_node->children->content); if(etag.size() >= 2 && *etag.begin() == '"' && *etag.rbegin() == '"'){ etag.assign(etag.substr(1, etag.size() - 2)); } partdata.etag.assign(etag); partdata.uploaded = true; } } } } } S3FS_XMLFREEDOC(doc); } delete bodydata; bodydata = NULL; delete headdata; headdata = NULL; return result; } int S3fsCurl::MultipartHeadRequest(const char* tpath, off_t size, headers_t& meta, bool is_copy) { int result; string upload_id; off_t chunk; off_t bytes_remaining; etaglist_t list; stringstream strrange; S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(0 != (result = PreMultipartPostRequest(tpath, meta, upload_id, is_copy))){ return result; } DestroyCurlHandle(); for(bytes_remaining = size, chunk = 0; 0 < bytes_remaining; bytes_remaining -= chunk){ chunk = bytes_remaining > MAX_MULTI_COPY_SOURCE_SIZE ? MAX_MULTI_COPY_SOURCE_SIZE : bytes_remaining; strrange << "bytes=" << (size - bytes_remaining) << "-" << (size - bytes_remaining + chunk - 1); meta["x-amz-copy-source-range"] = strrange.str(); strrange.str(""); strrange.clear(stringstream::goodbit); if(0 != (result = CopyMultipartPostRequest(tpath, tpath, (list.size() + 1), upload_id, meta))){ return result; } list.push_back(partdata.etag); DestroyCurlHandle(); } if(0 != (result = CompleteMultipartPostRequest(tpath, upload_id, list))){ return result; } return 0; } int S3fsCurl::MultipartUploadRequest(const char* tpath, headers_t& meta, int fd, bool is_copy) { int result; string upload_id; struct stat st; int fd2; etaglist_t list; off_t remaining_bytes; off_t chunk; S3FS_PRN_INFO3("[tpath=%s][fd=%d]", SAFESTRPTR(tpath), fd); // duplicate fd if(-1 == (fd2 = dup(fd)) || 0 != lseek(fd2, 0, SEEK_SET)){ S3FS_PRN_ERR("Could not duplicate file descriptor(errno=%d)", errno); if(-1 != fd2){ close(fd2); } return -errno; } if(-1 == fstat(fd2, &st)){ S3FS_PRN_ERR("Invalid file descriptor(errno=%d)", errno); close(fd2); return -errno; } if(0 != (result = PreMultipartPostRequest(tpath, meta, upload_id, is_copy))){ close(fd2); return result; } DestroyCurlHandle(); // cycle through open fd, pulling off 10MB chunks at a time for(remaining_bytes = st.st_size; 0 < remaining_bytes; remaining_bytes -= chunk){ // chunk size chunk = remaining_bytes > S3fsCurl::multipart_size ? S3fsCurl::multipart_size : remaining_bytes; // set partdata.fd = fd2; partdata.startpos = st.st_size - remaining_bytes; partdata.size = chunk; b_partdata_startpos = partdata.startpos; b_partdata_size = partdata.size; // upload part if(0 != (result = UploadMultipartPostRequest(tpath, (list.size() + 1), upload_id))){ S3FS_PRN_ERR("failed uploading part(%d)", result); close(fd2); return result; } list.push_back(partdata.etag); DestroyCurlHandle(); } close(fd2); if(0 != (result = CompleteMultipartPostRequest(tpath, upload_id, list))){ return result; } return 0; } int S3fsCurl::MultipartRenameRequest(const char* from, const char* to, headers_t& meta, off_t size) { int result; string upload_id; off_t chunk; off_t bytes_remaining; etaglist_t list; stringstream strrange; S3FS_PRN_INFO3("[from=%s][to=%s]", SAFESTRPTR(from), SAFESTRPTR(to)); string srcresource; string srcurl; MakeUrlResource(get_realpath(from).c_str(), srcresource, srcurl); meta["Content-Type"] = S3fsCurl::LookupMimeType(string(to)); meta["x-amz-copy-source"] = srcresource; if(0 != (result = PreMultipartPostRequest(to, meta, upload_id, true))){ return result; } DestroyCurlHandle(); for(bytes_remaining = size, chunk = 0; 0 < bytes_remaining; bytes_remaining -= chunk){ chunk = bytes_remaining > MAX_MULTI_COPY_SOURCE_SIZE ? MAX_MULTI_COPY_SOURCE_SIZE : bytes_remaining; strrange << "bytes=" << (size - bytes_remaining) << "-" << (size - bytes_remaining + chunk - 1); meta["x-amz-copy-source-range"] = strrange.str(); strrange.str(""); strrange.clear(stringstream::goodbit); if(0 != (result = CopyMultipartPostRequest(from, to, (list.size() + 1), upload_id, meta))){ return result; } list.push_back(partdata.etag); DestroyCurlHandle(); } if(0 != (result = CompleteMultipartPostRequest(to, upload_id, list))){ return result; } return 0; } //------------------------------------------------------------------- // Class S3fsMultiCurl //------------------------------------------------------------------- #define MAX_MULTI_HEADREQ 20 // default: max request count in readdir curl_multi. //------------------------------------------------------------------- // Class method for S3fsMultiCurl //------------------------------------------------------------------- int S3fsMultiCurl::max_multireq = MAX_MULTI_HEADREQ; int S3fsMultiCurl::SetMaxMultiRequest(int max) { int old = S3fsMultiCurl::max_multireq; S3fsMultiCurl::max_multireq= max; return old; } //------------------------------------------------------------------- // method for S3fsMultiCurl //------------------------------------------------------------------- S3fsMultiCurl::S3fsMultiCurl() : hMulti(NULL), SuccessCallback(NULL), RetryCallback(NULL) { } S3fsMultiCurl::~S3fsMultiCurl() { Clear(); } bool S3fsMultiCurl::ClearEx(bool is_all) { s3fscurlmap_t::iterator iter; for(iter = cMap_req.begin(); iter != cMap_req.end(); cMap_req.erase(iter++)){ CURL* hCurl = (*iter).first; S3fsCurl* s3fscurl = (*iter).second; if(hMulti && hCurl){ curl_multi_remove_handle(hMulti, hCurl); } if(s3fscurl){ s3fscurl->DestroyCurlHandle(); delete s3fscurl; // with destroy curl handle. } } if(hMulti){ curl_multi_cleanup(hMulti); hMulti = NULL; } if(is_all){ for(iter = cMap_all.begin(); iter != cMap_all.end(); cMap_all.erase(iter++)){ S3fsCurl* s3fscurl = (*iter).second; s3fscurl->DestroyCurlHandle(); delete s3fscurl; } } S3FS_MALLOCTRIM(0); return true; } S3fsMultiSuccessCallback S3fsMultiCurl::SetSuccessCallback(S3fsMultiSuccessCallback function) { S3fsMultiSuccessCallback old = SuccessCallback; SuccessCallback = function; return old; } S3fsMultiRetryCallback S3fsMultiCurl::SetRetryCallback(S3fsMultiRetryCallback function) { S3fsMultiRetryCallback old = RetryCallback; RetryCallback = function; return old; } bool S3fsMultiCurl::SetS3fsCurlObject(S3fsCurl* s3fscurl) { if(hMulti){ S3FS_PRN_ERR("Internal error: hMulti is not null"); return false; } if(!s3fscurl){ return false; } if(cMap_all.end() != cMap_all.find(s3fscurl->hCurl)){ return false; } cMap_all[s3fscurl->hCurl] = s3fscurl; return true; } int S3fsMultiCurl::MultiPerform(void) { CURLMcode curlm_code; int still_running; if(!hMulti){ return -1; } // Send multi request. do{ // Start making requests and check running. still_running = 0; do { curlm_code = curl_multi_perform(hMulti, &still_running); } while(curlm_code == CURLM_CALL_MULTI_PERFORM); if(curlm_code != CURLM_OK) { S3FS_PRN_DBG("curl_multi_perform code: %d msg: %s", curlm_code, curl_multi_strerror(curlm_code)); } // Set timer when still running if(still_running) { long milliseconds; fd_set r_fd; fd_set w_fd; fd_set e_fd; FD_ZERO(&r_fd); FD_ZERO(&w_fd); FD_ZERO(&e_fd); if(CURLM_OK != (curlm_code = curl_multi_timeout(hMulti, &milliseconds))){ S3FS_PRN_DBG("curl_multi_timeout code: %d msg: %s", curlm_code, curl_multi_strerror(curlm_code)); } if(milliseconds < 0){ milliseconds = 50; } if(milliseconds > 0) { int max_fd; struct timeval timeout; timeout.tv_sec = 1000 * milliseconds / 1000000; timeout.tv_usec = 1000 * milliseconds % 1000000; if(CURLM_OK != (curlm_code = curl_multi_fdset(hMulti, &r_fd, &w_fd, &e_fd, &max_fd))){ S3FS_PRN_ERR("curl_multi_fdset code: %d msg: %s", curlm_code, curl_multi_strerror(curlm_code)); return -EIO; } if(-1 == select(max_fd + 1, &r_fd, &w_fd, &e_fd, &timeout)){ S3FS_PRN_ERR("failed select - errno(%d)", errno); return -errno; } } } }while(still_running); return 0; } int S3fsMultiCurl::MultiRead(void) { CURLMsg* msg; int remaining_messages; CURL* hCurl = NULL; S3fsCurl* s3fscurl = NULL; S3fsCurl* retrycurl= NULL; while(NULL != (msg = curl_multi_info_read(hMulti, &remaining_messages))){ if(CURLMSG_DONE != msg->msg){ S3FS_PRN_ERR("curl_multi_info_read code: %d", msg->msg); return -EIO; } hCurl = msg->easy_handle; s3fscurlmap_t::iterator iter; if(cMap_req.end() != (iter = cMap_req.find(hCurl))){ s3fscurl = iter->second; }else{ s3fscurl = NULL; } retrycurl= NULL; if(s3fscurl){ bool isRetry = false; if(CURLE_OK == msg->data.result){ long responseCode = -1; if(s3fscurl->GetResponseCode(responseCode)){ if(400 > responseCode){ // add into stat cache if(SuccessCallback && !SuccessCallback(s3fscurl)){ S3FS_PRN_WARN("error from callback function(%s).", s3fscurl->url.c_str()); } }else if(400 == responseCode){ // as possibly in multipart S3FS_PRN_WARN("failed a request(%ld: %s)", responseCode, s3fscurl->url.c_str()); isRetry = true; }else if(404 == responseCode){ // not found S3FS_PRN_ERR("failed a request(%ld: %s)", responseCode, s3fscurl->url.c_str()); }else if(500 == responseCode){ // case of all other result, do retry.(11/13/2013) // because it was found that s3fs got 500 error from S3, but could success // to retry it. S3FS_PRN_WARN("failed a request(%ld: %s)", responseCode, s3fscurl->url.c_str()); isRetry = true; }else{ // Retry in other case. S3FS_PRN_WARN("failed a request(%ld: %s)", responseCode, s3fscurl->url.c_str()); isRetry = true; } }else{ S3FS_PRN_ERR("failed a request(Unknown respons code: %s)", s3fscurl->url.c_str()); } }else{ S3FS_PRN_WARN("failed to read(remaining: %d code: %d msg: %s), so retry this.", remaining_messages, msg->data.result, curl_easy_strerror(msg->data.result)); isRetry = true; } if(!isRetry){ cMap_req.erase(hCurl); curl_multi_remove_handle(hMulti, hCurl); s3fscurl->DestroyCurlHandle(); delete s3fscurl; }else{ cMap_req.erase(hCurl); curl_multi_remove_handle(hMulti, hCurl); // For retry if(RetryCallback){ if(NULL != (retrycurl = RetryCallback(s3fscurl))){ cMap_all[retrycurl->hCurl] = retrycurl; }else{ // Could not set up callback. return -EIO; } } if(s3fscurl != retrycurl){ s3fscurl->DestroyCurlHandle(); delete s3fscurl; } } }else{ assert(false); } } return 0; } int S3fsMultiCurl::Request(void) { int result; CURLMcode curlm_code; S3FS_PRN_INFO3("[count=%zu]", cMap_all.size()); if(hMulti){ S3FS_PRN_DBG("Warning: hMulti is not null, thus clear itself."); ClearEx(false); } // Make request list. // // Send multi request loop( with retry ) // (When many request is sends, sometimes gets "Couldn't connect to server") // while(!cMap_all.empty()){ // populate the multi interface with an initial set of requests if(NULL == (hMulti = curl_multi_init())){ Clear(); return -1; } // set curl handle to multi handle int cnt; s3fscurlmap_t::iterator iter; for(cnt = 0, iter = cMap_all.begin(); cnt < S3fsMultiCurl::max_multireq && iter != cMap_all.end(); cMap_all.erase(iter++), cnt++){ CURL* hCurl = (*iter).first; S3fsCurl* s3fscurl = (*iter).second; if(CURLM_OK != (curlm_code = curl_multi_add_handle(hMulti, hCurl))){ S3FS_PRN_ERR("curl_multi_add_handle code: %d msg: %s", curlm_code, curl_multi_strerror(curlm_code)); Clear(); return -EIO; } cMap_req[hCurl] = s3fscurl; } // Send multi request. if(0 != (result = MultiPerform())){ Clear(); return result; } // Read the result if(0 != (result = MultiRead())){ Clear(); return result; } // Cleanup curl handle in multi handle ClearEx(false); } return 0; } //------------------------------------------------------------------- // Class AdditionalHeader //------------------------------------------------------------------- AdditionalHeader AdditionalHeader::singleton; //------------------------------------------------------------------- // Class AdditionalHeader method //------------------------------------------------------------------- AdditionalHeader::AdditionalHeader() { if(this == AdditionalHeader::get()){ is_enable = false; }else{ assert(false); } } AdditionalHeader::~AdditionalHeader() { if(this == AdditionalHeader::get()){ Unload(); }else{ assert(false); } } bool AdditionalHeader::Load(const char* file) { if(!file){ S3FS_PRN_WARN("file is NULL."); return false; } Unload(); ifstream AH(file); if(!AH.good()){ S3FS_PRN_WARN("Could not open file(%s).", file); return false; } // read file string line; while(getline(AH, line)){ if('#' == line[0]){ continue; } if(0 == line.size()){ continue; } // load a line stringstream ss(line); string key(""); // suffix(key) string head; // additional HTTP header string value; // header value if(0 == isblank(line[0])){ ss >> key; } if(ss){ ss >> head; if(ss && static_cast(ss.tellg()) < line.size()){ value = line.substr(static_cast(ss.tellg()) + 1); } } // check it if(0 == head.size()){ if(0 == key.size()){ continue; } S3FS_PRN_ERR("file format error: %s key(suffix) is no HTTP header value.", key.c_str()); Unload(); return false; } // set charcntlist int keylen = key.size(); charcnt_list_t::iterator iter; for(iter = charcntlist.begin(); iter != charcntlist.end(); ++iter){ if(keylen == (*iter)){ break; } } if(iter == charcntlist.end()){ charcntlist.push_back(keylen); } // set addheader addheader_t::iterator aiter; if(addheader.end() == (aiter = addheader.find(key))){ headerpair_t hpair; hpair[head] = value; addheader[key] = hpair; }else{ aiter->second[head] = value; } // set flag if(!is_enable){ is_enable = true; } } return true; } void AdditionalHeader::Unload(void) { is_enable = false; charcntlist.clear(); addheader.clear(); } bool AdditionalHeader::AddHeader(headers_t& meta, const char* path) const { if(!is_enable){ return true; } if(!path){ S3FS_PRN_WARN("path is NULL."); return false; } int nPathLen = strlen(path); for(charcnt_list_t::const_iterator iter = charcntlist.begin(); iter != charcntlist.end(); ++iter){ // get target character count if(nPathLen < (*iter)){ continue; } // make target suffix(same character count) & find string suffix(&path[nPathLen - (*iter)]); addheader_t::const_iterator aiter; if(addheader.end() == (aiter = addheader.find(suffix))){ continue; } for(headerpair_t::const_iterator piter = aiter->second.begin(); piter != aiter->second.end(); ++piter){ // Adding header meta[(*piter).first] = (*piter).second; } } return true; } struct curl_slist* AdditionalHeader::AddHeader(struct curl_slist* list, const char* path) const { headers_t meta; if(!AddHeader(meta, path)){ return list; } for(headers_t::iterator iter = meta.begin(); iter != meta.end(); ++iter){ // Adding header list = curl_slist_sort_insert(list, iter->first.c_str(), iter->second.c_str()); } meta.clear(); S3FS_MALLOCTRIM(0); return list; } bool AdditionalHeader::Dump(void) const { if(!IS_S3FS_LOG_DBG()){ return true; } // character count list stringstream ssdbg; ssdbg << "Character count list[" << charcntlist.size() << "] = {"; for(charcnt_list_t::const_iterator citer = charcntlist.begin(); citer != charcntlist.end(); ++citer){ ssdbg << " " << (*citer); } ssdbg << " }\n"; // additional header ssdbg << "Additional Header list[" << addheader.size() << "] = {\n"; for(addheader_t::const_iterator aiter = addheader.begin(); aiter != addheader.end(); ++aiter){ string key = (*aiter).first; if(0 == key.size()){ key = "*"; } for(headerpair_t::const_iterator piter = (*aiter).second.begin(); piter != (*aiter).second.end(); ++piter){ ssdbg << " " << key << "\t--->\t" << (*piter).first << ": " << (*piter).second << "\n"; } } ssdbg << "}"; // print all S3FS_PRN_DBG("%s", ssdbg.str().c_str()); return true; } //------------------------------------------------------------------- // Utility functions //------------------------------------------------------------------- // // curl_slist_sort_insert // This function is like curl_slist_append function, but this adds data by a-sorting. // Because AWS signature needs sorted header. // struct curl_slist* curl_slist_sort_insert(struct curl_slist* list, const char* data) { if(!data){ return list; } string strkey = data; string strval = ""; string::size_type pos = strkey.find(':', 0); if(string::npos != pos){ strval = strkey.substr(pos + 1); strkey = strkey.substr(0, pos); } return curl_slist_sort_insert(list, strkey.c_str(), strval.c_str()); } struct curl_slist* curl_slist_sort_insert(struct curl_slist* list, const char* key, const char* value) { struct curl_slist* curpos; struct curl_slist* lastpos; struct curl_slist* new_item; if(!key){ return list; } if(NULL == (new_item = (struct curl_slist*)malloc(sizeof(struct curl_slist)))){ return list; } // key & value are trimed and lower(only key) string strkey = trim(string(key)); string strval = trim(string(value ? value : "")); string strnew = key + string(": ") + strval; if(NULL == (new_item->data = strdup(strnew.c_str()))){ free(new_item); return list; } new_item->next = NULL; for(lastpos = NULL, curpos = list; curpos; lastpos = curpos, curpos = curpos->next){ string strcur = curpos->data; size_t pos; if(string::npos != (pos = strcur.find(':', 0))){ strcur = strcur.substr(0, pos); } int result = strcasecmp(strkey.c_str(), strcur.c_str()); if(0 == result){ // same data, so replace it. if(lastpos){ lastpos->next = new_item; }else{ list = new_item; } new_item->next = curpos->next; free(curpos->data); free(curpos); break; }else if(0 > result){ // add data before curpos. if(lastpos){ lastpos->next = new_item; }else{ list = new_item; } new_item->next = curpos; break; } } if(!curpos){ // append to last pos if(lastpos){ lastpos->next = new_item; }else{ // a case of list is null list = new_item; } } return list; } string get_sorted_header_keys(const struct curl_slist* list) { string sorted_headers; if(!list){ return sorted_headers; } for( ; list; list = list->next){ string strkey = list->data; size_t pos; if(string::npos != (pos = strkey.find(':', 0))){ strkey = strkey.substr(0, pos); } if(0 < sorted_headers.length()){ sorted_headers += ";"; } sorted_headers += lower(strkey); } return sorted_headers; } string get_canonical_headers(const struct curl_slist* list) { string canonical_headers; if(!list){ canonical_headers = "\n"; return canonical_headers; } for( ; list; list = list->next){ string strhead = list->data; size_t pos; if(string::npos != (pos = strhead.find(':', 0))){ string strkey = trim(lower(strhead.substr(0, pos))); string strval = trim(strhead.substr(pos + 1)); strhead = strkey + string(":") + strval; }else{ strhead = trim(lower(strhead)); } canonical_headers += strhead; canonical_headers += "\n"; } return canonical_headers; } string get_canonical_headers(const struct curl_slist* list, bool only_amz) { string canonical_headers; if(!list){ canonical_headers = "\n"; return canonical_headers; } for( ; list; list = list->next){ string strhead = list->data; size_t pos; if(string::npos != (pos = strhead.find(':', 0))){ string strkey = trim(lower(strhead.substr(0, pos))); string strval = trim(strhead.substr(pos + 1)); strhead = strkey + string(":") + strval; }else{ strhead = trim(lower(strhead)); } if(only_amz && strhead.substr(0, 5) != "x-amz"){ continue; } canonical_headers += strhead; canonical_headers += "\n"; } return canonical_headers; } // function for using global values bool MakeUrlResource(const char* realpath, string& resourcepath, string& url) { if(!realpath){ return false; } resourcepath = urlEncode(service_path + bucket + realpath); url = host + resourcepath; return true; } string prepare_url(const char* url) { S3FS_PRN_INFO3("URL is %s", url); string uri; string host; string path; string url_str = str(url); string token = str("/" + bucket); int bucket_pos = url_str.find(token); int bucket_length = token.size(); int uri_length = 0; if(!strncasecmp(url_str.c_str(), "https://", 8)){ uri_length = 8; } else if(!strncasecmp(url_str.c_str(), "http://", 7)) { uri_length = 7; } uri = url_str.substr(0, uri_length); if(!pathrequeststyle){ host = bucket + "." + url_str.substr(uri_length, bucket_pos - uri_length).c_str(); path = url_str.substr((bucket_pos + bucket_length)); }else{ host = url_str.substr(uri_length, bucket_pos - uri_length).c_str(); string part = url_str.substr((bucket_pos + bucket_length)); if('/' != part[0]){ part = "/" + part; } path = "/" + bucket + part; } url_str = uri + host + path; S3FS_PRN_INFO3("URL changed is %s", url_str.c_str()); return str(url_str); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/curl.h000066400000000000000000000464761260476112200172270ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef S3FS_CURL_H_ #define S3FS_CURL_H_ //---------------------------------------------- // class BodyData //---------------------------------------------- // memory class for curl write memory callback // class BodyData { private: char* text; size_t lastpos; size_t bufsize; private: bool IsSafeSize(size_t addbytes) const { return ((lastpos + addbytes + 1) > bufsize ? false : true); } bool Resize(size_t addbytes); public: BodyData() : text(NULL), lastpos(0), bufsize(0) {} ~BodyData() { Clear(); } void Clear(void); bool Append(void* ptr, size_t bytes); bool Append(void* ptr, size_t blockSize, size_t numBlocks) { return Append(ptr, (blockSize * numBlocks)); } const char* str() const; size_t size() const { return lastpos; } }; //---------------------------------------------- // Utility structs & typedefs //---------------------------------------------- typedef std::vector etaglist_t; // Each part information for Multipart upload struct filepart { bool uploaded; // does finish uploading std::string etag; // expected etag value int fd; // base file(temporary full file) descriptor off_t startpos; // seek fd point for uploading ssize_t size; // uploading size etaglist_t* etaglist; // use only parallel upload int etagpos; // use only parallel upload filepart() : uploaded(false), fd(-1), startpos(0), size(-1), etaglist(NULL), etagpos(-1) {} ~filepart() { clear(); } void clear(void) { uploaded = false; etag = ""; fd = -1; startpos = 0; size = -1; etaglist = NULL; etagpos = - 1; } void add_etag_list(etaglist_t* list) { if(list){ list->push_back(std::string("")); etaglist = list; etagpos = list->size() - 1; }else{ etaglist = NULL; etagpos = - 1; } } }; // for progress struct case_insensitive_compare_func { bool operator()(const std::string& a, const std::string& b) const { return strcasecmp(a.c_str(), b.c_str()) < 0; } }; typedef std::map mimes_t; typedef std::pair progress_t; typedef std::map curltime_t; typedef std::map curlprogress_t; class S3fsMultiCurl; //---------------------------------------------- // class S3fsCurl //---------------------------------------------- typedef std::map iamcredmap_t; typedef std::map sseckeymap_t; typedef std::list sseckeylist_t; // strage class(rrs) enum storage_class_t { STANDARD, STANDARD_IA, REDUCED_REDUNDANCY, }; // sse type enum sse_type_t { SSE_DISABLE = 0, // not use server side encrypting SSE_S3, // server side encrypting by S3 key SSE_C, // server side encrypting by custom key SSE_KMS // server side encrypting by kms id }; // share #define SHARE_MUTEX_DNS 0 #define SHARE_MUTEX_SSL_SESSION 1 #define SHARE_MUTEX_MAX 2 // Class for lapping curl // class S3fsCurl { friend class S3fsMultiCurl; private: enum REQTYPE { REQTYPE_UNSET = -1, REQTYPE_DELETE = 0, REQTYPE_HEAD, REQTYPE_PUTHEAD, REQTYPE_PUT, REQTYPE_GET, REQTYPE_CHKBUCKET, REQTYPE_LISTBUCKET, REQTYPE_PREMULTIPOST, REQTYPE_COMPLETEMULTIPOST, REQTYPE_UPLOADMULTIPOST, REQTYPE_COPYMULTIPOST, REQTYPE_MULTILIST, REQTYPE_IAMCRED, REQTYPE_ABORTMULTIUPLOAD }; // class variables static pthread_mutex_t curl_handles_lock; static pthread_mutex_t curl_share_lock[SHARE_MUTEX_MAX]; static bool is_initglobal_done; static CURLSH* hCurlShare; static bool is_cert_check; static bool is_dns_cache; static bool is_ssl_session_cache; static long connect_timeout; static time_t readwrite_timeout; static int retries; static bool is_public_bucket; static std::string default_acl; // TODO: to enum static storage_class_t storage_class; static sseckeylist_t sseckeys; static std::string ssekmsid; static sse_type_t ssetype; static bool is_content_md5; static bool is_verbose; static std::string AWSAccessKeyId; static std::string AWSSecretAccessKey; static std::string AWSAccessToken; static time_t AWSAccessTokenExpire; static std::string IAM_role; static long ssl_verify_hostname; static curltime_t curl_times; static curlprogress_t curl_progress; static std::string curl_ca_bundle; static mimes_t mimeTypes; static int max_parallel_cnt; static off_t multipart_size; static bool is_sigv4; // variables CURL* hCurl; REQTYPE type; // type of request std::string path; // target object path std::string base_path; // base path (for multi curl head request) std::string saved_path; // saved path = cache key (for multi curl head request) std::string url; // target object path(url) struct curl_slist* requestHeaders; headers_t responseHeaders; // header data by HeaderCallback BodyData* bodydata; // body data by WriteMemoryCallback BodyData* headdata; // header data by WriteMemoryCallback long LastResponseCode; const unsigned char* postdata; // use by post method and read callback function. int postdata_remaining; // use by post method and read callback function. filepart partdata; // use by multipart upload/get object callback bool is_use_ahbe; // additional header by extension int retry_count; // retry count for multipart FILE* b_infile; // backup for retrying const unsigned char* b_postdata; // backup for retrying int b_postdata_remaining; // backup for retrying off_t b_partdata_startpos; // backup for retrying ssize_t b_partdata_size; // backup for retrying int b_ssekey_pos; // backup for retrying std::string b_ssevalue; // backup for retrying sse_type_t b_ssetype; // backup for retrying public: // constructor/destructor explicit S3fsCurl(bool ahbe = false); ~S3fsCurl(); private: // class methods static bool InitGlobalCurl(void); static bool DestroyGlobalCurl(void); static bool InitShareCurl(void); static bool DestroyShareCurl(void); static void LockCurlShare(CURL* handle, curl_lock_data nLockData, curl_lock_access laccess, void* useptr); static void UnlockCurlShare(CURL* handle, curl_lock_data nLockData, void* useptr); static bool InitCryptMutex(void); static bool DestroyCryptMutex(void); static int CurlProgress(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow); static bool InitMimeType(const char* MimeFile = NULL); static bool LocateBundle(void); static size_t HeaderCallback(void *data, size_t blockSize, size_t numBlocks, void *userPtr); static size_t WriteMemoryCallback(void *ptr, size_t blockSize, size_t numBlocks, void *data); static size_t ReadCallback(void *ptr, size_t size, size_t nmemb, void *userp); static size_t UploadReadCallback(void *ptr, size_t size, size_t nmemb, void *userp); static size_t DownloadWriteCallback(void* ptr, size_t size, size_t nmemb, void* userp); static bool UploadMultipartPostCallback(S3fsCurl* s3fscurl); static S3fsCurl* UploadMultipartPostRetryCallback(S3fsCurl* s3fscurl); static S3fsCurl* ParallelGetObjectRetryCallback(S3fsCurl* s3fscurl); static bool ParseIAMCredentialResponse(const char* response, iamcredmap_t& keyval); static bool SetIAMCredentials(const char* response); static bool LoadEnvSseCKeys(void); static bool LoadEnvSseKmsid(void); static bool PushbackSseKeys(std::string& onekey); static int CurlDebugFunc(CURL* hcurl, curl_infotype type, char* data, size_t size, void* userptr); // methods bool ResetHandle(void); bool RemakeHandle(void); bool ClearInternalData(void); void insertV4Headers(const std::string &op, const std::string &path, const std::string &query_string, const std::string &payload_hash); std::string CalcSignatureV2(std::string method, std::string strMD5, std::string content_type, std::string date, std::string resource); std::string CalcSignature(std::string method, std::string canonical_uri, std::string query_string, std::string strdate, std::string payload_hash, std::string date8601); bool GetUploadId(std::string& upload_id); int GetIAMCredentials(void); int PreMultipartPostRequest(const char* tpath, headers_t& meta, std::string& upload_id, bool is_copy); int CompleteMultipartPostRequest(const char* tpath, std::string& upload_id, etaglist_t& parts); int UploadMultipartPostSetup(const char* tpath, int part_num, std::string& upload_id); int UploadMultipartPostRequest(const char* tpath, int part_num, std::string& upload_id); int CopyMultipartPostRequest(const char* from, const char* to, int part_num, std::string& upload_id, headers_t& meta); public: // class methods static bool InitS3fsCurl(const char* MimeFile = NULL); static bool DestroyS3fsCurl(void); static int ParallelMultipartUploadRequest(const char* tpath, headers_t& meta, int fd); static int ParallelGetObjectRequest(const char* tpath, int fd, off_t start, ssize_t size); static bool CheckIAMCredentialUpdate(void); // class methods(valiables) static std::string LookupMimeType(std::string name); static bool SetCheckCertificate(bool isCertCheck); static bool SetDnsCache(bool isCache); static bool SetSslSessionCache(bool isCache); static long SetConnectTimeout(long timeout); static time_t SetReadwriteTimeout(time_t timeout); static time_t GetReadwriteTimeout(void) { return S3fsCurl::readwrite_timeout; } static int SetRetries(int count); static bool SetPublicBucket(bool flag); static bool IsPublicBucket(void) { return S3fsCurl::is_public_bucket; } static std::string SetDefaultAcl(const char* acl); static storage_class_t SetStorageClass(storage_class_t storage_class); static storage_class_t GetStorageClass() { return S3fsCurl::storage_class; } static bool LoadEnvSse(void) { return (S3fsCurl::LoadEnvSseCKeys() && S3fsCurl::LoadEnvSseKmsid()); } static sse_type_t SetSseType(sse_type_t type); static sse_type_t GetSseType(void) { return S3fsCurl::ssetype; } static bool IsSseDisable(void) { return (SSE_DISABLE == S3fsCurl::ssetype); } static bool IsSseS3Type(void) { return (SSE_S3 == S3fsCurl::ssetype); } static bool IsSseCType(void) { return (SSE_C == S3fsCurl::ssetype); } static bool IsSseKmsType(void) { return (SSE_KMS == S3fsCurl::ssetype); } static bool FinalCheckSse(void); static bool SetSseCKeys(const char* filepath); static bool SetSseKmsid(const char* kmsid); static bool IsSetSseKmsId(void) { return !S3fsCurl::ssekmsid.empty(); } static const char* GetSseKmsId(void) { return S3fsCurl::ssekmsid.c_str(); } static bool GetSseKey(std::string& md5, std::string& ssekey); static bool GetSseKeyMd5(int pos, std::string& md5); static int GetSseKeyCount(void); static bool SetContentMd5(bool flag); static bool SetVerbose(bool flag); static bool GetVerbose(void) { return S3fsCurl::is_verbose; } static bool SetAccessKey(const char* AccessKeyId, const char* SecretAccessKey); static bool IsSetAccessKeyId(void){ return (0 < S3fsCurl::IAM_role.size() || (0 < S3fsCurl::AWSAccessKeyId.size() && 0 < S3fsCurl::AWSSecretAccessKey.size())); } static long SetSslVerifyHostname(long value); static long GetSslVerifyHostname(void) { return S3fsCurl::ssl_verify_hostname; } static int SetMaxParallelCount(int value); static int GetMaxParallelCount(void) { return S3fsCurl::max_parallel_cnt; } static std::string SetIAMRole(const char* role); static const char* GetIAMRole(void) { return S3fsCurl::IAM_role.c_str(); } static bool SetMultipartSize(off_t size); static off_t GetMultipartSize(void) { return S3fsCurl::multipart_size; } static bool SetSignatureV4(bool isset) { bool bresult = S3fsCurl::is_sigv4; S3fsCurl::is_sigv4 = isset; return bresult; } static bool IsSignatureV4(void) { return S3fsCurl::is_sigv4; } // methods bool CreateCurlHandle(bool force = false); bool DestroyCurlHandle(void); bool AddSseRequestHead(sse_type_t ssetype, std::string& ssevalue, bool is_only_c, bool is_copy); bool GetResponseCode(long& responseCode); int RequestPerform(void); int DeleteRequest(const char* tpath); bool PreHeadRequest(const char* tpath, const char* bpath = NULL, const char* savedpath = NULL, int ssekey_pos = -1); bool PreHeadRequest(std::string& tpath, std::string& bpath, std::string& savedpath, int ssekey_pos = -1) { return PreHeadRequest(tpath.c_str(), bpath.c_str(), savedpath.c_str(), ssekey_pos); } int HeadRequest(const char* tpath, headers_t& meta); int PutHeadRequest(const char* tpath, headers_t& meta, bool is_copy); int PutRequest(const char* tpath, headers_t& meta, int fd); int PreGetObjectRequest(const char* tpath, int fd, off_t start, ssize_t size, sse_type_t ssetype, std::string& ssevalue); int GetObjectRequest(const char* tpath, int fd, off_t start = -1, ssize_t size = -1); int CheckBucket(void); int ListBucketRequest(const char* tpath, const char* query); int MultipartListRequest(std::string& body); int AbortMultipartUpload(const char* tpath, std::string& upload_id); int MultipartHeadRequest(const char* tpath, off_t size, headers_t& meta, bool is_copy); int MultipartUploadRequest(const char* tpath, headers_t& meta, int fd, bool is_copy); int MultipartRenameRequest(const char* from, const char* to, headers_t& meta, off_t size); // methods(valiables) CURL* GetCurlHandle(void) const { return hCurl; } std::string GetPath(void) const { return path; } std::string GetBasePath(void) const { return base_path; } std::string GetSpacialSavedPath(void) const { return saved_path; } std::string GetUrl(void) const { return url; } headers_t* GetResponseHeaders(void) { return &responseHeaders; } BodyData* GetBodyData(void) const { return bodydata; } BodyData* GetHeadData(void) const { return headdata; } long GetLastResponseCode(void) const { return LastResponseCode; } bool SetUseAhbe(bool ahbe); bool EnableUseAhbe(void) { return SetUseAhbe(true); } bool DisableUseAhbe(void) { return SetUseAhbe(false); } bool IsUseAhbe(void) const { return is_use_ahbe; } int GetMultipartRetryCount(void) const { return retry_count; } void SetMultipartRetryCount(int retrycnt) { retry_count = retrycnt; } bool IsOverMultipartRetryCount(void) const { return (retry_count >= S3fsCurl::retries); } int GetLastPreHeadSeecKeyPos(void) const { return b_ssekey_pos; } }; //---------------------------------------------- // class S3fsMultiCurl //---------------------------------------------- // Class for lapping multi curl // typedef std::map s3fscurlmap_t; typedef bool (*S3fsMultiSuccessCallback)(S3fsCurl* s3fscurl); // callback for succeed multi request typedef S3fsCurl* (*S3fsMultiRetryCallback)(S3fsCurl* s3fscurl); // callback for failure and retrying class S3fsMultiCurl { private: static int max_multireq; CURLM* hMulti; s3fscurlmap_t cMap_all; // all of curl requests s3fscurlmap_t cMap_req; // curl requests are sent S3fsMultiSuccessCallback SuccessCallback; S3fsMultiRetryCallback RetryCallback; private: bool ClearEx(bool is_all); int MultiPerform(void); int MultiRead(void); public: S3fsMultiCurl(); ~S3fsMultiCurl(); static int SetMaxMultiRequest(int max); static int GetMaxMultiRequest(void) { return S3fsMultiCurl::max_multireq; } S3fsMultiSuccessCallback SetSuccessCallback(S3fsMultiSuccessCallback function); S3fsMultiRetryCallback SetRetryCallback(S3fsMultiRetryCallback function); bool Clear(void) { return ClearEx(true); } bool SetS3fsCurlObject(S3fsCurl* s3fscurl); int Request(void); }; //---------------------------------------------- // class AdditionalHeader //---------------------------------------------- typedef std::list charcnt_list_t; typedef std::map headerpair_t; typedef std::map addheader_t; class AdditionalHeader { private: static AdditionalHeader singleton; bool is_enable; charcnt_list_t charcntlist; addheader_t addheader; public: // Reference singleton static AdditionalHeader* get(void) { return &singleton; } AdditionalHeader(); ~AdditionalHeader(); bool Load(const char* file); void Unload(void); bool AddHeader(headers_t& meta, const char* path) const; struct curl_slist* AddHeader(struct curl_slist* list, const char* path) const; bool Dump(void) const; }; //---------------------------------------------- // Utility Functions //---------------------------------------------- std::string GetContentMD5(int fd); unsigned char* md5hexsum(int fd, off_t start, ssize_t size); std::string md5sum(int fd, off_t start, ssize_t size); struct curl_slist* curl_slist_sort_insert(struct curl_slist* list, const char* data); struct curl_slist* curl_slist_sort_insert(struct curl_slist* list, const char* key, const char* value); std::string get_sorted_header_keys(const struct curl_slist* list); std::string get_canonical_headers(const struct curl_slist* list, bool only_amz = false); bool MakeUrlResource(const char* realpath, std::string& resourcepath, std::string& url); std::string prepare_url(const char* url); bool get_object_sse_type(const char* path, sse_type_t& ssetype, std::string& ssevalue); // implement in s3fs.cpp #endif // S3FS_CURL_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/fdcache.cpp000066400000000000000000001033461260476112200201600ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2013 Takeshi Nakatani * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "common.h" #include "fdcache.h" #include "s3fs.h" #include "s3fs_util.h" #include "string_util.h" #include "curl.h" using namespace std; //------------------------------------------------ // Symbols //------------------------------------------------ #define MAX_MULTIPART_CNT 10000 // S3 multipart max count #define FDPAGE_SIZE (50 * 1024 * 1024) // 50MB(parallel uploading is 5 parallel(default) * 10 MB) //------------------------------------------------ // CacheFileStat class methods //------------------------------------------------ bool CacheFileStat::MakeCacheFileStatPath(const char* path, string& sfile_path, bool is_create_dir) { // make stat dir top path( "//..stat" ) string top_path = FdManager::GetCacheDir(); top_path += "/."; top_path += bucket; top_path += ".stat"; if(is_create_dir){ int result; if(0 != (result = mkdirp(top_path + mydirname(path), 0777))){ S3FS_PRN_ERR("failed to create dir(%s) by errno(%d).", path, result); return false; } } if(!path || '\0' == path[0]){ sfile_path = top_path; }else{ sfile_path = top_path + SAFESTRPTR(path); } return true; } bool CacheFileStat::CheckCacheFileStatTopDir(void) { if(!FdManager::IsCacheDir()){ return true; } // make stat dir top path( "//..stat" ) string top_path = FdManager::GetCacheDir(); top_path += "/."; top_path += bucket; top_path += ".stat"; return check_exist_dir_permission(top_path.c_str()); } bool CacheFileStat::DeleteCacheFileStat(const char* path) { if(!path || '\0' == path[0]){ return false; } // stat path string sfile_path; if(!CacheFileStat::MakeCacheFileStatPath(path, sfile_path, false)){ S3FS_PRN_ERR("failed to create cache stat file path(%s)", path); return false; } if(0 != unlink(sfile_path.c_str())){ S3FS_PRN_ERR("failed to delete file(%s): errno=%d", path, errno); return false; } return true; } //------------------------------------------------ // CacheFileStat methods //------------------------------------------------ CacheFileStat::CacheFileStat(const char* tpath) : path(""), fd(-1) { if(tpath && '\0' != tpath[0]){ SetPath(tpath, true); } } CacheFileStat::~CacheFileStat() { Release(); } bool CacheFileStat::SetPath(const char* tpath, bool is_open) { if(!tpath || '\0' == tpath[0]){ return false; } if(!Release()){ // could not close old stat file. return false; } if(tpath){ path = tpath; } if(!is_open){ return true; } return Open(); } bool CacheFileStat::Open(void) { if(0 == path.size()){ return false; } if(-1 != fd){ // already opened return true; } // stat path string sfile_path; if(!CacheFileStat::MakeCacheFileStatPath(path.c_str(), sfile_path, true)){ S3FS_PRN_ERR("failed to create cache stat file path(%s)", path.c_str()); return false; } // open if(-1 == (fd = open(sfile_path.c_str(), O_CREAT|O_RDWR, 0600))){ S3FS_PRN_ERR("failed to open cache stat file path(%s) - errno(%d)", path.c_str(), errno); return false; } // lock if(-1 == flock(fd, LOCK_EX)){ S3FS_PRN_ERR("failed to lock cache stat file(%s) - errno(%d)", path.c_str(), errno); close(fd); fd = -1; return false; } // seek top if(0 != lseek(fd, 0, SEEK_SET)){ S3FS_PRN_ERR("failed to lseek cache stat file(%s) - errno(%d)", path.c_str(), errno); flock(fd, LOCK_UN); close(fd); fd = -1; return false; } S3FS_PRN_DBG("file locked(%s - %s)", path.c_str(), sfile_path.c_str()); return true; } bool CacheFileStat::Release(void) { if(-1 == fd){ // already release return true; } // unlock if(-1 == flock(fd, LOCK_UN)){ S3FS_PRN_ERR("failed to unlock cache stat file(%s) - errno(%d)", path.c_str(), errno); return false; } S3FS_PRN_DBG("file unlocked(%s)", path.c_str()); if(-1 == close(fd)){ S3FS_PRN_ERR("failed to close cache stat file(%s) - errno(%d)", path.c_str(), errno); return false; } fd = -1; return true; } //------------------------------------------------ // PageList methods //------------------------------------------------ void PageList::FreeList(fdpage_list_t& list) { for(fdpage_list_t::iterator iter = list.begin(); iter != list.end(); iter = list.erase(iter)){ delete (*iter); } list.clear(); } PageList::PageList(off_t size, bool is_init) { Init(size, is_init); } PageList::~PageList() { Clear(); } off_t PageList::Size(void) const { if(pages.empty()){ return 0; } fdpage_list_t::const_reverse_iterator riter = pages.rbegin(); return ((*riter)->offset + (*riter)->bytes); } int PageList::Resize(off_t size, bool is_init) { off_t total = Size(); if(0 == total){ Init(size, is_init); }else if(total < size){ off_t remain = size - total; // remaining bytes fdpage_list_t::reverse_iterator riter = pages.rbegin(); if((*riter)->bytes < FdManager::GetPageSize()){ // resize last area remain += (*riter)->bytes; // remaining bytes(without last page) (*riter)->bytes = remain > static_cast(FdManager::GetPageSize()) ? FdManager::GetPageSize() : static_cast(remain); // reset page size remain -= (*riter)->bytes; // remaining bytes(after last page) (*riter)->init = is_init; } // add new area for(off_t next = (*riter)->next(); 0 < remain; remain -= size, next += size){ size = remain > static_cast(FdManager::GetPageSize()) ? static_cast(FdManager::GetPageSize()) : remain; fdpage* page = new fdpage(next, size, is_init); pages.push_back(page); } }else if(total > size){ for(fdpage_list_t::reverse_iterator riter = pages.rbegin(); riter != pages.rend(); ++riter){ if((*riter)->offset < size){ (*riter)->bytes = static_cast(size - (*riter)->offset); break; } } } return true; } void PageList::Clear(void) { PageList::FreeList(pages); } int PageList::Init(off_t size, bool is_init) { Clear(); for(off_t total = 0; total < size; total += FdManager::GetPageSize()){ size_t areasize = (total + static_cast(FdManager::GetPageSize())) < size ? FdManager::GetPageSize() : static_cast(size - total); fdpage* page = new fdpage(total, areasize, is_init); pages.push_back(page); } return pages.size(); } bool PageList::IsInit(off_t start, off_t size) { off_t next = start + size; if(pages.empty()){ return false; } // check end fdpage_list_t::reverse_iterator riter = pages.rbegin(); if((*riter)->next() < next){ // size is over end of page list. return false; } for(fdpage_list_t::iterator iter = pages.begin(); iter != pages.end(); ++iter){ if(next <= (*iter)->offset){ break; } if((start <= (*iter)->offset && (*iter)->offset < next) || // start < iter-start < end (start <= (*iter)->end() && (*iter)->end() < next) || // start < iter-end < end ((*iter)->offset <= start && next <= (*iter)->end()) ) // iter-start < start < end < iter-end { if(!(*iter)->init){ return false; } } } return true; } bool PageList::SetInit(off_t start, off_t size, bool is_init) { // check size & resize if(Size() < (start + size)){ Resize(start + size, false); } off_t next = start + size; for(fdpage_list_t::iterator iter = pages.begin(); iter != pages.end(); ++iter){ if((*iter)->end() < start){ // out of area // iter:start < iter:end < start < end continue; }else if(next <= (*iter)->offset){ // out of area // start < end < iter:start < iter:end break; } // area of target overlaps with iter area // iter:start < start < iter:end < end // iter:start < start < end < iter:end // start < iter:start < iter:end < end // start < iter:start < end < iter:end if((*iter)->init != is_init){ (*iter)->init = is_init; } } return true; } bool PageList::FindUninitPage(off_t start, off_t& resstart, size_t& ressize) { for(fdpage_list_t::iterator iter = pages.begin(); iter != pages.end(); ++iter){ if(start <= (*iter)->end()){ if(!(*iter)->init){ resstart = (*iter)->offset; ressize = (*iter)->bytes; return true; } } } return false; } int PageList::GetUninitPages(fdpage_list_t& uninit_list, off_t start, off_t size) { for(fdpage_list_t::iterator iter = pages.begin(); iter != pages.end(); ++iter){ if(start <= (*iter)->end()){ if((start + size) <= (*iter)->offset){ // reach to end break; } // after start pos if(!(*iter)->init){ // found uninitialized area fdpage_list_t::reverse_iterator riter = uninit_list.rbegin(); if(riter != uninit_list.rend() && (*riter)->next() == (*iter)->offset){ // merge to before page (*riter)->bytes += (*iter)->bytes; }else{ fdpage* page = new fdpage((*iter)->offset, (*iter)->bytes, false); uninit_list.push_back(page); } } } } return uninit_list.size(); } bool PageList::Serialize(CacheFileStat& file, bool is_output) { if(!file.Open()){ return false; } if(is_output){ // // put to file // stringstream ssall; ssall << Size(); for(fdpage_list_t::iterator iter = pages.begin(); iter != pages.end(); ++iter){ ssall << "\n" << (*iter)->offset << ":" << (*iter)->bytes << ":" << ((*iter)->init ? "1" : "0"); } string strall = ssall.str(); if(0 >= pwrite(file.GetFd(), strall.c_str(), strall.length(), 0)){ S3FS_PRN_ERR("failed to write stats(%d)", errno); return false; } }else{ // // loading from file // struct stat st; memset(&st, 0, sizeof(struct stat)); if(-1 == fstat(file.GetFd(), &st)){ S3FS_PRN_ERR("fstat is failed. errno(%d)", errno); return false; } if(0 >= st.st_size){ // nothing Init(0, false); return true; } char* ptmp; if(NULL == (ptmp = (char*)calloc(st.st_size + 1, sizeof(char)))){ S3FS_PRN_CRIT("could not allocate memory."); S3FS_FUSE_EXIT(); return false; } // read from file if(0 >= pread(file.GetFd(), ptmp, st.st_size, 0)){ S3FS_PRN_ERR("failed to read stats(%d)", errno); free(ptmp); return false; } string oneline; stringstream ssall(ptmp); // init Clear(); // load(size) if(!getline(ssall, oneline, '\n')){ S3FS_PRN_ERR("failed to parse stats."); free(ptmp); return false; } off_t total = s3fs_strtoofft(oneline.c_str()); // load each part bool is_err = false; while(getline(ssall, oneline, '\n')){ string part; stringstream ssparts(oneline); // offset if(!getline(ssparts, part, ':')){ is_err = true; break; } off_t offset = s3fs_strtoofft(part.c_str()); // size if(!getline(ssparts, part, ':')){ is_err = true; break; } off_t size = s3fs_strtoofft(part.c_str()); // init if(!getline(ssparts, part, ':')){ is_err = true; break; } bool is_init = (1 == s3fs_strtoofft(part.c_str()) ? true : false); // add new area SetInit(offset, size, is_init); } free(ptmp); if(is_err){ S3FS_PRN_ERR("failed to parse stats."); Clear(); return false; } // check size if(total != Size()){ S3FS_PRN_ERR("different size(%jd - %jd).", (intmax_t)total, (intmax_t)Size()); Clear(); return false; } } return true; } void PageList::Dump(void) { int cnt = 0; S3FS_PRN_DBG("pages = {"); for(fdpage_list_t::iterator iter = pages.begin(); iter != pages.end(); ++iter, ++cnt){ S3FS_PRN_DBG(" [%08d] -> {%014jd - %014zu : %s}", cnt, (intmax_t)((*iter)->offset), (*iter)->bytes, (*iter)->init ? "true" : "false"); } S3FS_PRN_DBG("}"); } //------------------------------------------------ // FdEntity methods //------------------------------------------------ FdEntity::FdEntity(const char* tpath, const char* cpath) : is_lock_init(false), refcnt(0), path(SAFESTRPTR(tpath)), cachepath(SAFESTRPTR(cpath)), fd(-1), file(NULL), is_modify(false) { try{ pthread_mutex_init(&fdent_lock, NULL); is_lock_init = true; }catch(exception& e){ S3FS_PRN_CRIT("failed to init mutex"); } } FdEntity::~FdEntity() { Clear(); if(is_lock_init){ try{ pthread_mutex_destroy(&fdent_lock); }catch(exception& e){ S3FS_PRN_CRIT("failed to destroy mutex"); } is_lock_init = false; } } void FdEntity::Clear(void) { AutoLock auto_lock(&fdent_lock); if(file){ if(0 != cachepath.size()){ CacheFileStat cfstat(path.c_str()); if(!pagelist.Serialize(cfstat, true)){ S3FS_PRN_WARN("failed to save cache stat file(%s).", path.c_str()); } } fclose(file); file = NULL; fd = -1; } pagelist.Init(0, false); refcnt = 0; path = ""; cachepath = ""; is_modify = false; } void FdEntity::Close(void) { S3FS_PRN_INFO3("[path=%s][fd=%d][refcnt=%d]", path.c_str(), fd, (-1 != fd ? refcnt - 1 : refcnt)); if(-1 != fd){ AutoLock auto_lock(&fdent_lock); if(0 < refcnt){ refcnt--; } if(0 == refcnt){ if(0 != cachepath.size()){ CacheFileStat cfstat(path.c_str()); if(!pagelist.Serialize(cfstat, true)){ S3FS_PRN_WARN("failed to save cache stat file(%s).", path.c_str()); } } fclose(file); file = NULL; fd = -1; } } } int FdEntity::Dup(void) { S3FS_PRN_INFO3("[path=%s][fd=%d][refcnt=%d]", path.c_str(), fd, (-1 != fd ? refcnt + 1 : refcnt)); if(-1 != fd){ AutoLock auto_lock(&fdent_lock); refcnt++; } return fd; } int FdEntity::Open(off_t size, time_t time) { bool already_opened = false; // already opened fd bool is_csf_loaded = false; // loaded by cache stat file bool is_truncate = false; // need to truncate bool init_value = false; // value for pagelist S3FS_PRN_INFO3("[path=%s][fd=%d][size=%jd][time=%jd]", path.c_str(), fd, (intmax_t)size, (intmax_t)time); if(-1 != fd){ // already opened, needs to increment refcnt. already_opened = true; }else{ // open if(0 != cachepath.size()){ // At first, open & flock stat file. { CacheFileStat cfstat(path.c_str()); is_csf_loaded = pagelist.Serialize(cfstat, false); } // open cache file if(is_csf_loaded && -1 != (fd = open(cachepath.c_str(), O_RDWR))){ // file exists struct stat st; memset(&st, 0, sizeof(struct stat)); if(-1 == fstat(fd, &st)){ S3FS_PRN_ERR("fstat is failed. errno(%d)", errno); fclose(file); file = NULL; fd = -1; return (0 == errno ? -EIO : -errno); } if((-1 != size && size != pagelist.Size()) || st.st_size != pagelist.Size()){ is_csf_loaded = false; // reinitializing if(-1 == size){ size = st.st_size; }else{ is_truncate = true; } }else{ // size OK! --> no initialize after this line. } }else{ // file does not exist -> create & open if(-1 == (fd = open(cachepath.c_str(), O_CREAT|O_RDWR|O_TRUNC, 0600))){ S3FS_PRN_ERR("failed to open file(%s). errno(%d)", cachepath.c_str(), errno); return (0 == errno ? -EIO : -errno); } if(-1 == size){ size = 0; }else{ is_truncate = true; } is_csf_loaded = false; } // make file pointer(for being same tmpfile) if(NULL == (file = fdopen(fd, "wb"))){ S3FS_PRN_ERR("failed to get fileno(%s). errno(%d)", cachepath.c_str(), errno); close(fd); fd = -1; return (0 == errno ? -EIO : -errno); } }else{ // open temporary file if(NULL == (file = tmpfile()) || -1 ==(fd = fileno(file))){ S3FS_PRN_ERR("failed to open tmp file. err(%d)", errno); if(file){ fclose(file); file = NULL; } return (0 == errno ? -EIO : -errno); } if(-1 == size){ size = 0; }else{ is_truncate = true; } } } // truncate if(is_truncate){ if(0 != ftruncate(fd, size) || 0 != fsync(fd)){ S3FS_PRN_ERR("ftruncate(%s) or fsync returned err(%d)", cachepath.c_str(), errno); fclose(file); file = NULL; fd = -1; return (0 == errno ? -EIO : -errno); } } // set mtime if(-1 != time){ if(0 != SetMtime(time)){ S3FS_PRN_ERR("failed to set mtime. errno(%d)", errno); fclose(file); file = NULL; fd = -1; return (0 == errno ? -EIO : -errno); } } // set internal data if(already_opened){ Dup(); }else{ if(!is_csf_loaded){ pagelist.Init(size, init_value); } refcnt = 1; is_modify = false; } return 0; } int FdEntity::SetMtime(time_t time) { S3FS_PRN_INFO3("[path=%s][fd=%d][time=%jd]", path.c_str(), fd, (intmax_t)time); if(-1 == time){ return 0; } if(-1 != fd){ AutoLock auto_lock(&fdent_lock); struct timeval tv[2]; tv[0].tv_sec = time; tv[0].tv_usec= 0L; tv[1].tv_sec = tv[0].tv_sec; tv[1].tv_usec= 0L; if(-1 == futimes(fd, tv)){ S3FS_PRN_ERR("futimes failed. errno(%d)", errno); return -errno; } }else if(0 < cachepath.size()){ // not opened file yet. struct utimbuf n_mtime; n_mtime.modtime = time; n_mtime.actime = time; if(-1 == utime(cachepath.c_str(), &n_mtime)){ S3FS_PRN_ERR("utime failed. errno(%d)", errno); return -errno; } } return 0; } bool FdEntity::GetSize(off_t& size) { if(-1 == fd){ return false; } AutoLock auto_lock(&fdent_lock); size = pagelist.Size(); return true; } bool FdEntity::GetMtime(time_t& time) { struct stat st; if(!GetStats(st)){ return false; } time = st.st_mtime; return true; } bool FdEntity::GetStats(struct stat& st) { if(-1 == fd){ return false; } AutoLock auto_lock(&fdent_lock); memset(&st, 0, sizeof(struct stat)); if(-1 == fstat(fd, &st)){ S3FS_PRN_ERR("fstat failed. errno(%d)", errno); return false; } return true; } bool FdEntity::SetAllStatus(bool is_enable) { S3FS_PRN_INFO3("[path=%s][fd=%d][%s]", path.c_str(), fd, is_enable ? "enable" : "disable"); if(-1 == fd){ return false; } AutoLock auto_lock(&fdent_lock); // get file size struct stat st; memset(&st, 0, sizeof(struct stat)); if(-1 == fstat(fd, &st)){ S3FS_PRN_ERR("fstat is failed. errno(%d)", errno); return false; } // Reinit pagelist.Init(st.st_size, is_enable); return true; } int FdEntity::Load(off_t start, off_t size) { int result = 0; S3FS_PRN_INFO3("[path=%s][fd=%d][offset=%jd][size=%jd]", path.c_str(), fd, (intmax_t)start, (intmax_t)size); if(-1 == fd){ return -EBADF; } AutoLock auto_lock(&fdent_lock); // check loaded area & load fdpage_list_t uninit_list; if(0 < pagelist.GetUninitPages(uninit_list, start, size)){ for(fdpage_list_t::iterator iter = uninit_list.begin(); iter != uninit_list.end(); ++iter){ if(-1 != size && (start + size) <= (*iter)->offset){ break; } // download if((*iter)->bytes >= static_cast(2 * S3fsCurl::GetMultipartSize()) && !nomultipart){ // default 20MB // parallel request // Additional time is needed for large files time_t backup = 0; if(120 > S3fsCurl::GetReadwriteTimeout()){ backup = S3fsCurl::SetReadwriteTimeout(120); } result = S3fsCurl::ParallelGetObjectRequest(path.c_str(), fd, (*iter)->offset, (*iter)->bytes); if(0 != backup){ S3fsCurl::SetReadwriteTimeout(backup); } }else{ // single request S3fsCurl s3fscurl; result = s3fscurl.GetObjectRequest(path.c_str(), fd, (*iter)->offset, (*iter)->bytes); } if(0 != result){ break; } // Set init flag pagelist.SetInit((*iter)->offset, static_cast((*iter)->bytes), true); } PageList::FreeList(uninit_list); } return result; } bool FdEntity::LoadFull(off_t* size, bool force_load) { int result; S3FS_PRN_INFO3("[path=%s][fd=%d]", path.c_str(), fd); if(-1 == fd){ if(0 != Open()){ return false; } } if(force_load){ SetAllDisable(); } // // TODO: possibly do background for delay loading // if(0 != (result = Load(0, pagelist.Size()))){ S3FS_PRN_ERR("could not download, result(%d)", result); return false; } if(is_modify){ AutoLock auto_lock(&fdent_lock); is_modify = false; } if(size){ *size = pagelist.Size(); } return true; } int FdEntity::RowFlush(const char* tpath, headers_t& meta, bool force_sync) { int result; S3FS_PRN_INFO3("[tpath=%s][path=%s][fd=%d]", SAFESTRPTR(tpath), path.c_str(), fd); if(-1 == fd){ return -EBADF; } AutoLock auto_lock(&fdent_lock); if(!force_sync && !is_modify){ // nothing to update. return 0; } /* * Make decision to do multi upload (or not) based upon file size * * According to the AWS spec: * - 1 to 10,000 parts are allowed * - minimum size of parts is 5MB (expect for the last part) * * For our application, we will define minimum part size to be 10MB (10 * 2^20 Bytes) * minimum file size will be 64 GB - 2 ** 36 * * Initially uploads will be done serially * * If file is > 20MB, then multipart will kick in */ if(pagelist.Size() > (MAX_MULTIPART_CNT * S3fsCurl::GetMultipartSize())){ // close f ? return -ENOTSUP; } // seek to head of file. if(0 != lseek(fd, 0, SEEK_SET)){ S3FS_PRN_ERR("lseek error(%d)", errno); return -errno; } if(pagelist.Size() >= (2 * S3fsCurl::GetMultipartSize()) && !nomultipart){ // default 20MB // Additional time is needed for large files time_t backup = 0; if(120 > S3fsCurl::GetReadwriteTimeout()){ backup = S3fsCurl::SetReadwriteTimeout(120); } result = S3fsCurl::ParallelMultipartUploadRequest(tpath ? tpath : path.c_str(), meta, fd); if(0 != backup){ S3fsCurl::SetReadwriteTimeout(backup); } }else{ S3fsCurl s3fscurl(true); result = s3fscurl.PutRequest(tpath ? tpath : path.c_str(), meta, fd); } // seek to head of file. if(0 == result && 0 != lseek(fd, 0, SEEK_SET)){ S3FS_PRN_ERR("lseek error(%d)", errno); return -errno; } if(0 == result){ is_modify = false; } return result; } ssize_t FdEntity::Read(char* bytes, off_t start, size_t size, bool force_load) { int result; ssize_t rsize; S3FS_PRN_INFO3("[path=%s][fd=%d][offset=%jd][size=%zu]", path.c_str(), fd, (intmax_t)start, size); if(-1 == fd){ return -EBADF; } if(force_load){ AutoLock auto_lock(&fdent_lock); pagelist.SetInit(start, static_cast(size), false); } // Loading if(0 != (result = Load(start, size))){ S3FS_PRN_ERR("could not download. start(%jd), size(%zu), errno(%d)", (intmax_t)start, size, result); return -EIO; } // Reading { AutoLock auto_lock(&fdent_lock); if(-1 == (rsize = pread(fd, bytes, size, start))){ S3FS_PRN_ERR("pread failed. errno(%d)", errno); return -errno; } } return rsize; } ssize_t FdEntity::Write(const char* bytes, off_t start, size_t size) { int result; ssize_t wsize; S3FS_PRN_INFO3("[path=%s][fd=%d][offset=%jd][size=%zu]", path.c_str(), fd, (intmax_t)start, size); if(-1 == fd){ return -EBADF; } // Load unitialized area which starts from 0 to (start + size) before writing. if(0 != (result = Load(0, start))){ S3FS_PRN_ERR("failed to load uninitialized area before writing(errno=%d)", result); return static_cast(result); } // Writing { AutoLock auto_lock(&fdent_lock); if(-1 == (wsize = pwrite(fd, bytes, size, start))){ S3FS_PRN_ERR("pwrite failed. errno(%d)", errno); return -errno; } if(!is_modify){ is_modify = true; } if(0 < wsize){ pagelist.SetInit(start, static_cast(wsize), true); } } return wsize; } //------------------------------------------------ // FdManager symbol //------------------------------------------------ // [NOTE] // NOCACHE_PATH_PREFIX symbol needs for not using cache mode. // Now s3fs I/F functions in s3fs.cpp has left the processing // to FdManager and FdEntity class. FdManager class manages // the list of local file stat and file descriptor in conjunction // with the FdEntity class. // When s3fs is not using local cache, it means FdManager must // return new temporary file descriptor at each opening it. // Then FdManager caches fd by key which is dummy file path // instead of real file path. // This process may not be complete, but it is easy way can // be realized. // #define NOCACHE_PATH_PREFIX_FORM " __S3FS_UNEXISTED_PATH_%lx__ / " // important space words for simply //------------------------------------------------ // FdManager class valiable //------------------------------------------------ FdManager FdManager::singleton; pthread_mutex_t FdManager::fd_manager_lock; bool FdManager::is_lock_init(false); string FdManager::cache_dir(""); size_t FdManager::page_size(FDPAGE_SIZE); //------------------------------------------------ // FdManager class methods //------------------------------------------------ bool FdManager::SetCacheDir(const char* dir) { if(!dir || '\0' == dir[0]){ cache_dir = ""; }else{ cache_dir = dir; } return true; } size_t FdManager::SetPageSize(size_t size) { // If already has entries, this function is failed. if(0 < FdManager::get()->fent.size()){ return -1; } size_t old = FdManager::page_size; FdManager::page_size = size; return old; } bool FdManager::DeleteCacheDirectory(void) { if(0 == FdManager::cache_dir.size()){ return true; } string cache_dir; if(!FdManager::MakeCachePath(NULL, cache_dir, false)){ return false; } return delete_files_in_dir(cache_dir.c_str(), true); } int FdManager::DeleteCacheFile(const char* path) { S3FS_PRN_INFO3("[path=%s]", SAFESTRPTR(path)); if(!path){ return -EIO; } if(0 == FdManager::cache_dir.size()){ return 0; } string cache_path = ""; if(!FdManager::MakeCachePath(path, cache_path, false)){ return 0; } int result = 0; if(0 != unlink(cache_path.c_str())){ S3FS_PRN_ERR("failed to delete file(%s): errno=%d", path, errno); result = -errno; } if(!CacheFileStat::DeleteCacheFileStat(path)){ S3FS_PRN_ERR("failed to delete stat file(%s): errno=%d", path, errno); if(0 != errno){ result = -errno; }else{ result = -EIO; } } return result; } bool FdManager::MakeCachePath(const char* path, string& cache_path, bool is_create_dir) { if(0 == FdManager::cache_dir.size()){ cache_path = ""; return true; } string resolved_path(FdManager::cache_dir + "/" + bucket); if(is_create_dir){ int result; if(0 != (result = mkdirp(resolved_path + mydirname(path), 0777))){ S3FS_PRN_ERR("failed to create dir(%s) by errno(%d).", path, result); return false; } } if(!path || '\0' == path[0]){ cache_path = resolved_path; }else{ cache_path = resolved_path + SAFESTRPTR(path); } return true; } bool FdManager::CheckCacheTopDir(void) { if(0 == FdManager::cache_dir.size()){ return true; } string toppath(FdManager::cache_dir + "/" + bucket); return check_exist_dir_permission(toppath.c_str()); } bool FdManager::MakeRandomTempPath(const char* path, string& tmppath) { char szBuff[64]; sprintf(szBuff, NOCACHE_PATH_PREFIX_FORM, random()); // warry for performance, but maybe don't warry. tmppath = szBuff; tmppath += path ? path : ""; return true; } //------------------------------------------------ // FdManager methods //------------------------------------------------ FdManager::FdManager() { if(this == FdManager::get()){ try{ pthread_mutex_init(&FdManager::fd_manager_lock, NULL); FdManager::is_lock_init = true; }catch(exception& e){ FdManager::is_lock_init = false; S3FS_PRN_CRIT("failed to init mutex"); } }else{ assert(false); } } FdManager::~FdManager() { if(this == FdManager::get()){ for(fdent_map_t::iterator iter = fent.begin(); fent.end() != iter; ++iter){ FdEntity* ent = (*iter).second; delete ent; } fent.clear(); if(FdManager::is_lock_init){ try{ pthread_mutex_destroy(&FdManager::fd_manager_lock); }catch(exception& e){ S3FS_PRN_CRIT("failed to init mutex"); } FdManager::is_lock_init = false; } }else{ assert(false); } } FdEntity* FdManager::GetFdEntity(const char* path, int existfd) { S3FS_PRN_INFO3("[path=%s][fd=%d]", SAFESTRPTR(path), existfd); if(!path || '\0' == path[0]){ return NULL; } AutoLock auto_lock(&FdManager::fd_manager_lock); fdent_map_t::iterator iter = fent.find(string(path)); if(fent.end() != iter && (-1 == existfd || (*iter).second->GetFd() == existfd)){ return (*iter).second; } if(-1 != existfd){ for(iter = fent.begin(); iter != fent.end(); ++iter){ if((*iter).second && (*iter).second->GetFd() == existfd){ // found opend fd in map if(0 == strcmp((*iter).second->GetPath(), path)){ return (*iter).second; } // found fd, but it is used another file(file descriptor is recycled) // so returns NULL. break; } } } return NULL; } FdEntity* FdManager::Open(const char* path, off_t size, time_t time, bool force_tmpfile, bool is_create) { FdEntity* ent; S3FS_PRN_INFO3("[path=%s][size=%jd][time=%jd]", SAFESTRPTR(path), (intmax_t)size, (intmax_t)time); if(!path || '\0' == path[0]){ return NULL; } AutoLock auto_lock(&FdManager::fd_manager_lock); fdent_map_t::iterator iter = fent.find(string(path)); if(fent.end() != iter){ // found ent = (*iter).second; }else if(is_create){ // not found string cache_path = ""; if(!force_tmpfile && !FdManager::MakeCachePath(path, cache_path, true)){ S3FS_PRN_ERR("failed to make cache path for object(%s).", path); return NULL; } // make new obj ent = new FdEntity(path, cache_path.c_str()); if(0 < cache_path.size()){ // using cache fent[string(path)] = ent; }else{ // not using cache, so the key of fdentity is set not really existsing path. // (but not strictly unexisting path.) // // [NOTE] // The reason why this process here, please look at the definition of the // comments of NOCACHE_PATH_PREFIX_FORM symbol. // string tmppath(""); FdManager::MakeRandomTempPath(path, tmppath); fent[tmppath] = ent; } }else{ return NULL; } // open if(-1 == ent->Open(size, time)){ return NULL; } return ent; } FdEntity* FdManager::ExistOpen(const char* path, int existfd) { S3FS_PRN_INFO3("[path=%s][fd=%d]", SAFESTRPTR(path), existfd); // search by real path FdEntity* ent = Open(path, -1, -1, false, false); if(!ent && -1 != existfd){ // search from all fdentity because of not using cache. AutoLock auto_lock(&FdManager::fd_manager_lock); for(fdent_map_t::iterator iter = fent.begin(); iter != fent.end(); ++iter){ if((*iter).second && (*iter).second->GetFd() == existfd && (*iter).second->IsOpen()){ // found opend fd in map if(0 == strcmp((*iter).second->GetPath(), path)){ ent = (*iter).second; // open if(-1 == ent->Open(-1, -1)){ return NULL; } }else{ // found fd, but it is used another file(file descriptor is recycled) // so returns NULL. } break; } } } return ent; } void FdManager::Rename(const std::string &from, const std::string &to) { fdent_map_t::iterator iter = fent.find(from); if(fent.end() != iter){ // found S3FS_PRN_DBG("[from=%s][to=%s]", from.c_str(), to.c_str()); FdEntity* ent = (*iter).second; fent.erase(iter); ent->SetPath(to); fent[to] = ent; } } bool FdManager::Close(FdEntity* ent) { S3FS_PRN_INFO3("[ent->file=%s][ent->fd=%d]", ent ? ent->GetPath() : "", ent ? ent->GetFd() : -1); AutoLock auto_lock(&FdManager::fd_manager_lock); for(fdent_map_t::iterator iter = fent.begin(); iter != fent.end(); ++iter){ if((*iter).second == ent){ ent->Close(); if(!ent->IsOpen()){ delete (*iter).second; fent.erase(iter); return true; } } } return false; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/fdcache.h000066400000000000000000000142271260476112200176240ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef FD_CACHE_H_ #define FD_CACHE_H_ //------------------------------------------------ // CacheFileStat //------------------------------------------------ class CacheFileStat { private: std::string path; int fd; private: static bool MakeCacheFileStatPath(const char* path, std::string& sfile_path, bool is_create_dir = true); public: static bool DeleteCacheFileStat(const char* path); static bool CheckCacheFileStatTopDir(void); explicit CacheFileStat(const char* tpath = NULL); ~CacheFileStat(); bool Open(void); bool Release(void); bool SetPath(const char* tpath, bool is_open = true); int GetFd(void) const { return fd; } }; //------------------------------------------------ // fdpage & PageList //------------------------------------------------ // page block information struct fdpage { off_t offset; size_t bytes; bool init; fdpage(off_t start = 0, size_t size = 0, bool is_init = false) : offset(start), bytes(size), init(is_init) {} off_t next(void) const { return (offset + bytes); } off_t end(void) const { return (0 < bytes ? offset + bytes - 1 : 0); } }; typedef std::list fdpage_list_t; // // Management of loading area/modifying // class PageList { private: fdpage_list_t pages; private: void Clear(void); public: static void FreeList(fdpage_list_t& list); explicit PageList(off_t size = 0, bool is_init = false); ~PageList(); off_t Size(void) const; int Resize(off_t size, bool is_init); int Init(off_t size, bool is_init); bool IsInit(off_t start, off_t size); bool SetInit(off_t start, off_t size, bool is_init = true); bool FindUninitPage(off_t start, off_t& resstart, size_t& ressize); int GetUninitPages(fdpage_list_t& uninit_list, off_t start = 0, off_t size = -1); bool Serialize(CacheFileStat& file, bool is_output); void Dump(void); }; //------------------------------------------------ // class FdEntity //------------------------------------------------ class FdEntity { private: pthread_mutex_t fdent_lock; bool is_lock_init; PageList pagelist; int refcnt; // reference count std::string path; // object path std::string cachepath; // local cache file path int fd; // file descriptor(tmp file or cache file) FILE* file; // file pointer(tmp file or cache file) bool is_modify; // if file is changed, this flag is true private: void Clear(void); int Dup(void); bool SetAllStatus(bool is_enable); public: explicit FdEntity(const char* tpath = NULL, const char* cpath = NULL); ~FdEntity(); void Close(void); bool IsOpen(void) const { return (-1 != fd); } int Open(off_t size = -1, time_t time = -1); const char* GetPath(void) const { return path.c_str(); } void SetPath(const std::string &newpath) { path = newpath; } int GetFd(void) const { return fd; } int SetMtime(time_t time); bool GetSize(off_t& size); bool GetMtime(time_t& time); bool GetStats(struct stat& st); bool SetAllEnable(void) { return SetAllStatus(true); } bool SetAllDisable(void) { return SetAllStatus(false); } bool LoadFull(off_t* size = NULL, bool force_load = false); int Load(off_t start, off_t size); int RowFlush(const char* tpath, headers_t& meta, bool force_sync = false); int Flush(headers_t& meta, bool force_sync = false) { return RowFlush(NULL, meta, force_sync); } ssize_t Read(char* bytes, off_t start, size_t size, bool force_load = false); ssize_t Write(const char* bytes, off_t start, size_t size); }; typedef std::map fdent_map_t; // key=path, value=FdEntity* //------------------------------------------------ // class FdManager //------------------------------------------------ class FdManager { private: static FdManager singleton; static pthread_mutex_t fd_manager_lock; static bool is_lock_init; static std::string cache_dir; static size_t page_size; fdent_map_t fent; public: FdManager(); ~FdManager(); // Reference singleton static FdManager* get(void) { return &singleton; } static bool DeleteCacheDirectory(void); static int DeleteCacheFile(const char* path); static bool SetCacheDir(const char* dir); static bool IsCacheDir(void) { return (0 < FdManager::cache_dir.size()); } static const char* GetCacheDir(void) { return FdManager::cache_dir.c_str(); } static size_t SetPageSize(size_t size); static size_t GetPageSize(void) { return FdManager::page_size; } static bool MakeCachePath(const char* path, std::string& cache_path, bool is_create_dir = true); static bool CheckCacheTopDir(void); static bool MakeRandomTempPath(const char* path, std::string& tmppath); FdEntity* GetFdEntity(const char* path, int existfd = -1); FdEntity* Open(const char* path, off_t size = -1, time_t time = -1, bool force_tmpfile = false, bool is_create = true); FdEntity* ExistOpen(const char* path, int existfd = -1); void Rename(const std::string &from, const std::string &to); bool Close(FdEntity* ent); }; #endif // FD_CACHE_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/gnutls_auth.cpp000066400000000000000000000270351260476112200211400ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #ifdef USE_GNUTLS_NETTLE #include #include #include #endif #include #include #include "common.h" #include "s3fs_auth.h" using namespace std; //------------------------------------------------------------------- // Utility Function for version //------------------------------------------------------------------- #ifdef USE_GNUTLS_NETTLE const char* s3fs_crypt_lib_name(void) { static const char version[] = "GnuTLS(nettle)"; return version; } #else // USE_GNUTLS_NETTLE const char* s3fs_crypt_lib_name(void) { static const char version[] = "GnuTLS(gcrypt)"; return version; } #endif // USE_GNUTLS_NETTLE //------------------------------------------------------------------- // Utility Function for global init //------------------------------------------------------------------- bool s3fs_init_global_ssl(void) { if(GNUTLS_E_SUCCESS != gnutls_global_init()){ return false; } return true; } bool s3fs_destroy_global_ssl(void) { gnutls_global_deinit(); return true; } //------------------------------------------------------------------- // Utility Function for crypt lock //------------------------------------------------------------------- bool s3fs_init_crypt_mutex(void) { return true; } bool s3fs_destroy_crypt_mutex(void) { return true; } //------------------------------------------------------------------- // Utility Function for HMAC //------------------------------------------------------------------- #ifdef USE_GNUTLS_NETTLE bool s3fs_HMAC(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen) { if(!key || 0 >= keylen || !data || 0 >= datalen || !digest || !digestlen){ return false; } if(NULL == (*digest = (unsigned char*)malloc(SHA1_DIGEST_SIZE))){ return false; } struct hmac_sha1_ctx ctx_hmac; hmac_sha1_set_key(&ctx_hmac, keylen, reinterpret_cast(key)); hmac_sha1_update(&ctx_hmac, datalen, reinterpret_cast(data)); hmac_sha1_digest(&ctx_hmac, SHA1_DIGEST_SIZE, reinterpret_cast(*digest)); *digestlen = SHA1_DIGEST_SIZE; return true; } bool s3fs_HMAC256(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen) { if(!key || 0 >= keylen || !data || 0 >= datalen || !digest || !digestlen){ return false; } if(NULL == (*digest = (unsigned char*)malloc(SHA256_DIGEST_SIZE))){ return false; } struct hmac_sha256_ctx ctx_hmac; hmac_sha256_set_key(&ctx_hmac, keylen, reinterpret_cast(key)); hmac_sha256_update(&ctx_hmac, datalen, reinterpret_cast(data)); hmac_sha256_digest(&ctx_hmac, SHA256_DIGEST_SIZE, reinterpret_cast(*digest)); *digestlen = SHA256_DIGEST_SIZE; return true; } #else // USE_GNUTLS_NETTLE bool s3fs_HMAC(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen) { if(!key || 0 >= keylen || !data || 0 >= datalen || !digest || !digestlen){ return false; } if(0 >= (*digestlen = gnutls_hmac_get_len(GNUTLS_MAC_SHA1))){ return false; } if(NULL == (*digest = (unsigned char*)malloc(*digestlen + 1))){ return false; } if(0 > gnutls_hmac_fast(GNUTLS_MAC_SHA1, key, keylen, data, datalen, *digest)){ free(*digest); *digest = NULL; return false; } return true; } bool s3fs_HMAC256(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen) { if(!key || 0 >= keylen || !data || 0 >= datalen || !digest || !digestlen){ return false; } if(0 >= (*digestlen = gnutls_hmac_get_len(GNUTLS_MAC_SHA256))){ return false; } if(NULL == (*digest = (unsigned char*)malloc(*digestlen + 1))){ return false; } if(0 > gnutls_hmac_fast(GNUTLS_MAC_SHA256, key, keylen, data, datalen, *digest)){ free(*digest); *digest = NULL; return false; } return true; } #endif // USE_GNUTLS_NETTLE //------------------------------------------------------------------- // Utility Function for MD5 //------------------------------------------------------------------- #define MD5_DIGEST_LENGTH 16 size_t get_md5_digest_length(void) { return MD5_DIGEST_LENGTH; } #ifdef USE_GNUTLS_NETTLE unsigned char* s3fs_md5hexsum(int fd, off_t start, ssize_t size) { struct md5_ctx ctx_md5; unsigned char buf[512]; ssize_t bytes; unsigned char* result; // seek to top of file. if(-1 == lseek(fd, start, SEEK_SET)){ return NULL; } memset(buf, 0, 512); md5_init(&ctx_md5); for(ssize_t total = 0; total < size; total += bytes){ bytes = 512 < (size - total) ? 512 : (size - total); bytes = read(fd, buf, bytes); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); return NULL; } md5_update(&ctx_md5, bytes, buf); memset(buf, 0, 512); } if(NULL == (result = (unsigned char*)malloc(get_md5_digest_length()))){ return NULL; } md5_digest(&ctx_md5, get_md5_digest_length(), result); if(-1 == lseek(fd, start, SEEK_SET)){ free(result); return NULL; } return result; } #else // USE_GNUTLS_NETTLE unsigned char* s3fs_md5hexsum(int fd, off_t start, ssize_t size) { gcry_md_hd_t ctx_md5; gcry_error_t err; char buf[512]; ssize_t bytes; unsigned char* result; if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ return NULL; } size = static_cast(st.st_size); } // seek to top of file. if(-1 == lseek(fd, start, SEEK_SET)){ return NULL; } memset(buf, 0, 512); if(GPG_ERR_NO_ERROR != (err = gcry_md_open(&ctx_md5, GCRY_MD_MD5, 0))){ S3FS_PRN_ERR("MD5 context creation failure: %s/%s", gcry_strsource(err), gcry_strerror(err)); return NULL; } for(ssize_t total = 0; total < size; total += bytes){ bytes = 512 < (size - total) ? 512 : (size - total); bytes = read(fd, buf, bytes); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); return NULL; } gcry_md_write(ctx_md5, buf, bytes); memset(buf, 0, 512); } if(NULL == (result = (unsigned char*)malloc(get_md5_digest_length()))){ return NULL; } memcpy(result, gcry_md_read(ctx_md5, 0), get_md5_digest_length()); gcry_md_close(ctx_md5); if(-1 == lseek(fd, start, SEEK_SET)){ free(result); return NULL; } return result; } #endif // USE_GNUTLS_NETTLE //------------------------------------------------------------------- // Utility Function for SHA256 //------------------------------------------------------------------- #define SHA256_DIGEST_LENGTH 32 size_t get_sha256_digest_length(void) { return SHA256_DIGEST_LENGTH; } #ifdef USE_GNUTLS_NETTLE bool s3fs_sha256(const unsigned char* data, unsigned int datalen, unsigned char** digest, unsigned int* digestlen) { (*digestlen) = static_cast(get_sha256_digest_length()); if(NULL == ((*digest) = reinterpret_cast(malloc(*digestlen)))){ return false; } struct sha256_ctx ctx_sha256; sha256_init(&ctx_sha256); sha256_update(&ctx_sha256, datalen, data); sha256_digest(&ctx_sha256, *digestlen, *digest); return true; } unsigned char* s3fs_sha256hexsum(int fd, off_t start, ssize_t size) { struct sha256_ctx ctx_sha256; unsigned char buf[512]; ssize_t bytes; unsigned char* result; // seek to top of file. if(-1 == lseek(fd, start, SEEK_SET)){ return NULL; } memset(buf, 0, 512); sha256_init(&ctx_sha256); for(ssize_t total = 0; total < size; total += bytes){ bytes = 512 < (size - total) ? 512 : (size - total); bytes = read(fd, buf, bytes); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); return NULL; } sha256_update(&ctx_sha256, bytes, buf); memset(buf, 0, 512); } if(NULL == (result = (unsigned char*)malloc(get_sha256_digest_length()))){ return NULL; } sha256_digest(&ctx_sha256, get_sha256_digest_length(), result); if(-1 == lseek(fd, start, SEEK_SET)){ free(result); return NULL; } return result; } #else // USE_GNUTLS_NETTLE bool s3fs_sha256(const unsigned char* data, unsigned int datalen, unsigned char** digest, unsigned int* digestlen) { (*digestlen) = static_cast(get_sha256_digest_length()); if(NULL == ((*digest) = reinterpret_cast(malloc(*digestlen)))){ return false; } gcry_md_hd_t ctx_sha256; gcry_error_t err; if(GPG_ERR_NO_ERROR != (err = gcry_md_open(&ctx_sha256, GCRY_MD_SHA256, 0))){ S3FS_PRN_ERR("SHA256 context creation failure: %s/%s", gcry_strsource(err), gcry_strerror(err)); free(*digest); return false; } gcry_md_write(ctx_sha256, data, datalen); memcpy(*digest, gcry_md_read(ctx_sha256, 0), *digestlen); gcry_md_close(ctx_sha256); return true; } unsigned char* s3fs_sha256hexsum(int fd, off_t start, ssize_t size) { gcry_md_hd_t ctx_sha256; gcry_error_t err; char buf[512]; ssize_t bytes; unsigned char* result; if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ return NULL; } size = static_cast(st.st_size); } // seek to top of file. if(-1 == lseek(fd, start, SEEK_SET)){ return NULL; } memset(buf, 0, 512); if(GPG_ERR_NO_ERROR != (err = gcry_md_open(&ctx_sha256, GCRY_MD_SHA256, 0))){ S3FS_PRN_ERR("SHA256 context creation failure: %s/%s", gcry_strsource(err), gcry_strerror(err)); return NULL; } for(ssize_t total = 0; total < size; total += bytes){ bytes = 512 < (size - total) ? 512 : (size - total); bytes = read(fd, buf, bytes); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); return NULL; } gcry_md_write(ctx_sha256, buf, bytes); memset(buf, 0, 512); } if(NULL == (result = (unsigned char*)malloc(get_sha256_digest_length()))){ return NULL; } memcpy(result, gcry_md_read(ctx_sha256, 0), get_sha256_digest_length()); gcry_md_close(ctx_sha256); if(-1 == lseek(fd, start, SEEK_SET)){ free(result); return NULL; } return result; } #endif // USE_GNUTLS_NETTLE /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/nss_auth.cpp000066400000000000000000000177661260476112200204410ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "common.h" #include "s3fs_auth.h" using namespace std; //------------------------------------------------------------------- // Utility Function for version //------------------------------------------------------------------- const char* s3fs_crypt_lib_name(void) { static const char version[] = "NSS"; return version; } //------------------------------------------------------------------- // Utility Function for global init //------------------------------------------------------------------- bool s3fs_init_global_ssl(void) { NSS_Init(NULL); NSS_NoDB_Init(NULL); return true; } bool s3fs_destroy_global_ssl(void) { NSS_Shutdown(); PL_ArenaFinish(); PR_Cleanup(); return true; } //------------------------------------------------------------------- // Utility Function for crypt lock //------------------------------------------------------------------- bool s3fs_init_crypt_mutex(void) { return true; } bool s3fs_destroy_crypt_mutex(void) { return true; } //------------------------------------------------------------------- // Utility Function for HMAC //------------------------------------------------------------------- static bool s3fs_HMAC_RAW(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen, bool is_sha256) { if(!key || 0 >= keylen || !data || 0 >= datalen || !digest || !digestlen){ return false; } PK11SlotInfo* Slot; PK11SymKey* pKey; PK11Context* Context; SECStatus SecStatus; unsigned char tmpdigest[64]; SECItem KeySecItem = {siBuffer, reinterpret_cast(const_cast(key)), static_cast(keylen)}; SECItem NullSecItem = {siBuffer, NULL, 0}; if(NULL == (Slot = PK11_GetInternalKeySlot())){ return false; } if(NULL == (pKey = PK11_ImportSymKey(Slot, (is_sha256 ? CKM_SHA256_HMAC : CKM_SHA_1_HMAC), PK11_OriginUnwrap, CKA_SIGN, &KeySecItem, NULL))){ PK11_FreeSlot(Slot); return false; } if(NULL == (Context = PK11_CreateContextBySymKey((is_sha256 ? CKM_SHA256_HMAC : CKM_SHA_1_HMAC), CKA_SIGN, pKey, &NullSecItem))){ PK11_FreeSymKey(pKey); PK11_FreeSlot(Slot); return false; } *digestlen = 0; if(SECSuccess != (SecStatus = PK11_DigestBegin(Context)) || SECSuccess != (SecStatus = PK11_DigestOp(Context, data, datalen)) || SECSuccess != (SecStatus = PK11_DigestFinal(Context, tmpdigest, digestlen, sizeof(tmpdigest))) ) { PK11_DestroyContext(Context, PR_TRUE); PK11_FreeSymKey(pKey); PK11_FreeSlot(Slot); return false; } PK11_DestroyContext(Context, PR_TRUE); PK11_FreeSymKey(pKey); PK11_FreeSlot(Slot); if(NULL == (*digest = (unsigned char*)malloc(*digestlen))){ return false; } memcpy(*digest, tmpdigest, *digestlen); return true; } bool s3fs_HMAC(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen) { return s3fs_HMAC_RAW(key, keylen, data, datalen, digest, digestlen, false); } bool s3fs_HMAC256(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen) { return s3fs_HMAC_RAW(key, keylen, data, datalen, digest, digestlen, true); } //------------------------------------------------------------------- // Utility Function for MD5 //------------------------------------------------------------------- size_t get_md5_digest_length(void) { return MD5_LENGTH; } unsigned char* s3fs_md5hexsum(int fd, off_t start, ssize_t size) { PK11Context* md5ctx; unsigned char buf[512]; ssize_t bytes; unsigned char* result; unsigned int md5outlen; if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ return NULL; } size = static_cast(st.st_size); } // seek to top of file. if(-1 == lseek(fd, start, SEEK_SET)){ return NULL; } memset(buf, 0, 512); md5ctx = PK11_CreateDigestContext(SEC_OID_MD5); for(ssize_t total = 0; total < size; total += bytes){ bytes = 512 < (size - total) ? 512 : (size - total); bytes = read(fd, buf, bytes); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); return NULL; } PK11_DigestOp(md5ctx, buf, bytes); memset(buf, 0, 512); } if(NULL == (result = (unsigned char*)malloc(get_md5_digest_length()))){ PK11_DestroyContext(md5ctx, PR_TRUE); return NULL; } PK11_DigestFinal(md5ctx, result, &md5outlen, get_md5_digest_length()); PK11_DestroyContext(md5ctx, PR_TRUE); if(-1 == lseek(fd, start, SEEK_SET)){ free(result); return NULL; } return result; } //------------------------------------------------------------------- // Utility Function for SHA256 //------------------------------------------------------------------- size_t get_sha256_digest_length(void) { return SHA256_LENGTH; } bool s3fs_sha256(const unsigned char* data, unsigned int datalen, unsigned char** digest, unsigned int* digestlen) { (*digestlen) = static_cast(get_sha256_digest_length()); if(NULL == ((*digest) = reinterpret_cast(malloc(*digestlen)))){ return false; } PK11Context* sha256ctx; unsigned int sha256outlen; sha256ctx = PK11_CreateDigestContext(SEC_OID_SHA256); PK11_DigestOp(sha256ctx, data, datalen); PK11_DigestFinal(sha256ctx, *digest, &sha256outlen, *digestlen); PK11_DestroyContext(sha256ctx, PR_TRUE); *digestlen = sha256outlen; return true; } unsigned char* s3fs_sha256hexsum(int fd, off_t start, ssize_t size) { PK11Context* sha256ctx; unsigned char buf[512]; ssize_t bytes; unsigned char* result; unsigned int sha256outlen; if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ return NULL; } size = static_cast(st.st_size); } // seek to top of file. if(-1 == lseek(fd, start, SEEK_SET)){ return NULL; } memset(buf, 0, 512); sha256ctx = PK11_CreateDigestContext(SEC_OID_SHA256); for(ssize_t total = 0; total < size; total += bytes){ bytes = 512 < (size - total) ? 512 : (size - total); bytes = read(fd, buf, bytes); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); PK11_DestroyContext(sha256ctx, PR_TRUE); return NULL; } PK11_DigestOp(sha256ctx, buf, bytes); memset(buf, 0, 512); } if(NULL == (result = (unsigned char*)malloc(get_sha256_digest_length()))){ PK11_DestroyContext(sha256ctx, PR_TRUE); return NULL; } PK11_DigestFinal(sha256ctx, result, &sha256outlen, get_sha256_digest_length()); PK11_DestroyContext(sha256ctx, PR_TRUE); if(-1 == lseek(fd, start, SEEK_SET)){ free(result); return NULL; } return result; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/openssl_auth.cpp000066400000000000000000000231751260476112200213100ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "common.h" #include "s3fs_auth.h" using namespace std; //------------------------------------------------------------------- // Utility Function for version //------------------------------------------------------------------- const char* s3fs_crypt_lib_name(void) { static const char version[] = "OpenSSL"; return version; } //------------------------------------------------------------------- // Utility Function for global init //------------------------------------------------------------------- bool s3fs_init_global_ssl(void) { ERR_load_crypto_strings(); ERR_load_BIO_strings(); OpenSSL_add_all_algorithms(); return true; } bool s3fs_destroy_global_ssl(void) { EVP_cleanup(); ERR_free_strings(); return true; } //------------------------------------------------------------------- // Utility Function for crypt lock //------------------------------------------------------------------- // internal use struct for openssl struct CRYPTO_dynlock_value { pthread_mutex_t dyn_mutex; }; static pthread_mutex_t* s3fs_crypt_mutex = NULL; static void s3fs_crypt_mutex_lock(int mode, int pos, const char* file, int line) { if(s3fs_crypt_mutex){ if(mode & CRYPTO_LOCK){ pthread_mutex_lock(&s3fs_crypt_mutex[pos]); }else{ pthread_mutex_unlock(&s3fs_crypt_mutex[pos]); } } } static unsigned long s3fs_crypt_get_threadid(void) { // For FreeBSD etc, some system's pthread_t is structure pointer. // Then we use cast like C style(not C++) instead of ifdef. return (unsigned long)(pthread_self()); } static struct CRYPTO_dynlock_value* s3fs_dyn_crypt_mutex(const char* file, int line) { struct CRYPTO_dynlock_value* dyndata; if(NULL == (dyndata = static_cast(malloc(sizeof(struct CRYPTO_dynlock_value))))){ S3FS_PRN_CRIT("Could not allocate memory for CRYPTO_dynlock_value"); return NULL; } pthread_mutex_init(&(dyndata->dyn_mutex), NULL); return dyndata; } static void s3fs_dyn_crypt_mutex_lock(int mode, struct CRYPTO_dynlock_value* dyndata, const char* file, int line) { if(dyndata){ if(mode & CRYPTO_LOCK){ pthread_mutex_lock(&(dyndata->dyn_mutex)); }else{ pthread_mutex_unlock(&(dyndata->dyn_mutex)); } } } static void s3fs_destroy_dyn_crypt_mutex(struct CRYPTO_dynlock_value* dyndata, const char* file, int line) { if(dyndata){ pthread_mutex_destroy(&(dyndata->dyn_mutex)); free(dyndata); } } bool s3fs_init_crypt_mutex(void) { if(s3fs_crypt_mutex){ S3FS_PRN_DBG("s3fs_crypt_mutex is not NULL, destroy it."); if(!s3fs_destroy_crypt_mutex()){ S3FS_PRN_ERR("Failed to s3fs_crypt_mutex"); return false; } } if(NULL == (s3fs_crypt_mutex = static_cast(malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t))))){ S3FS_PRN_CRIT("Could not allocate memory for s3fs_crypt_mutex"); return false; } for(int cnt = 0; cnt < CRYPTO_num_locks(); cnt++){ pthread_mutex_init(&s3fs_crypt_mutex[cnt], NULL); } // static lock CRYPTO_set_locking_callback(s3fs_crypt_mutex_lock); CRYPTO_set_id_callback(s3fs_crypt_get_threadid); // dynamic lock CRYPTO_set_dynlock_create_callback(s3fs_dyn_crypt_mutex); CRYPTO_set_dynlock_lock_callback(s3fs_dyn_crypt_mutex_lock); CRYPTO_set_dynlock_destroy_callback(s3fs_destroy_dyn_crypt_mutex); return true; } bool s3fs_destroy_crypt_mutex(void) { if(!s3fs_crypt_mutex){ return true; } CRYPTO_set_dynlock_destroy_callback(NULL); CRYPTO_set_dynlock_lock_callback(NULL); CRYPTO_set_dynlock_create_callback(NULL); CRYPTO_set_id_callback(NULL); CRYPTO_set_locking_callback(NULL); for(int cnt = 0; cnt < CRYPTO_num_locks(); cnt++){ pthread_mutex_destroy(&s3fs_crypt_mutex[cnt]); } CRYPTO_cleanup_all_ex_data(); free(s3fs_crypt_mutex); s3fs_crypt_mutex = NULL; return true; } //------------------------------------------------------------------- // Utility Function for HMAC //------------------------------------------------------------------- static bool s3fs_HMAC_RAW(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen, bool is_sha256) { if(!key || 0 >= keylen || !data || 0 >= datalen || !digest || !digestlen){ return false; } (*digestlen) = EVP_MAX_MD_SIZE * sizeof(unsigned char); if(NULL == ((*digest) = (unsigned char*)malloc(*digestlen))){ return false; } if(is_sha256){ HMAC(EVP_sha256(), key, keylen, data, datalen, *digest, digestlen); }else{ HMAC(EVP_sha1(), key, keylen, data, datalen, *digest, digestlen); } return true; } bool s3fs_HMAC(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen) { return s3fs_HMAC_RAW(key, keylen, data, datalen, digest, digestlen, false); } bool s3fs_HMAC256(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen) { return s3fs_HMAC_RAW(key, keylen, data, datalen, digest, digestlen, true); } //------------------------------------------------------------------- // Utility Function for MD5 //------------------------------------------------------------------- size_t get_md5_digest_length(void) { return MD5_DIGEST_LENGTH; } unsigned char* s3fs_md5hexsum(int fd, off_t start, ssize_t size) { MD5_CTX md5ctx; char buf[512]; ssize_t bytes; unsigned char* result; if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ return NULL; } size = static_cast(st.st_size); } // seek to top of file. if(-1 == lseek(fd, start, SEEK_SET)){ return NULL; } memset(buf, 0, 512); MD5_Init(&md5ctx); for(ssize_t total = 0; total < size; total += bytes){ bytes = 512 < (size - total) ? 512 : (size - total); bytes = read(fd, buf, bytes); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); return NULL; } MD5_Update(&md5ctx, buf, bytes); memset(buf, 0, 512); } if(NULL == (result = (unsigned char*)malloc(get_md5_digest_length()))){ return NULL; } MD5_Final(result, &md5ctx); if(-1 == lseek(fd, start, SEEK_SET)){ free(result); return NULL; } return result; } //------------------------------------------------------------------- // Utility Function for SHA256 //------------------------------------------------------------------- size_t get_sha256_digest_length(void) { return SHA256_DIGEST_LENGTH; } bool s3fs_sha256(const unsigned char* data, unsigned int datalen, unsigned char** digest, unsigned int* digestlen) { (*digestlen) = EVP_MAX_MD_SIZE * sizeof(unsigned char); if(NULL == ((*digest) = reinterpret_cast(malloc(*digestlen)))){ return false; } const EVP_MD* md = EVP_get_digestbyname("sha256"); EVP_MD_CTX* mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, data, datalen); EVP_DigestFinal_ex(mdctx, *digest, digestlen); EVP_MD_CTX_destroy(mdctx); return true; } unsigned char* s3fs_sha256hexsum(int fd, off_t start, ssize_t size) { const EVP_MD* md = EVP_get_digestbyname("sha256"); EVP_MD_CTX* sha256ctx; char buf[512]; ssize_t bytes; unsigned char* result; if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ return NULL; } size = static_cast(st.st_size); } // seek to top of file. if(-1 == lseek(fd, start, SEEK_SET)){ return NULL; } sha256ctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(sha256ctx, md, NULL); memset(buf, 0, 512); for(ssize_t total = 0; total < size; total += bytes){ bytes = 512 < (size - total) ? 512 : (size - total); bytes = read(fd, buf, bytes); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); EVP_MD_CTX_destroy(sha256ctx); return NULL; } EVP_DigestUpdate(sha256ctx, buf, bytes); memset(buf, 0, 512); } if(NULL == (result = (unsigned char*)malloc(get_sha256_digest_length()))){ EVP_MD_CTX_destroy(sha256ctx); return NULL; } EVP_DigestFinal_ex(sha256ctx, result, NULL); EVP_MD_CTX_destroy(sha256ctx); if(-1 == lseek(fd, start, SEEK_SET)){ free(result); return NULL; } return result; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/s3fs.cpp000066400000000000000000004336121260476112200174630ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "common.h" #include "s3fs.h" #include "curl.h" #include "cache.h" #include "string_util.h" #include "s3fs_util.h" #include "fdcache.h" #include "s3fs_auth.h" using namespace std; //------------------------------------------------------------------- // Define //------------------------------------------------------------------- #define DIRTYPE_UNKNOWN -1 #define DIRTYPE_NEW 0 #define DIRTYPE_OLD 1 #define DIRTYPE_FOLDER 2 #define DIRTYPE_NOOBJ 3 #define IS_REPLACEDIR(type) (DIRTYPE_OLD == type || DIRTYPE_FOLDER == type || DIRTYPE_NOOBJ == type) #define IS_RMTYPEDIR(type) (DIRTYPE_OLD == type || DIRTYPE_FOLDER == type) #if !defined(ENOATTR) #define ENOATTR ENODATA #endif //------------------------------------------------------------------- // Structs //------------------------------------------------------------------- typedef struct uncomplete_multipart_info{ string key; string id; string date; }UNCOMP_MP_INFO; typedef std::list uncomp_mp_list_t; //------------------------------------------------------------------- // Global valiables //------------------------------------------------------------------- bool foreground = false; bool nomultipart = false; bool pathrequeststyle = false; bool is_specified_endpoint = false; std::string program_name; std::string service_path = "/"; std::string host = "http://s3.amazonaws.com"; std::string bucket = ""; std::string endpoint = "us-east-1"; s3fs_log_level debug_level = S3FS_LOG_CRIT; const char* s3fs_log_nest[S3FS_LOG_NEST_MAX] = {"", " ", " ", " "}; //------------------------------------------------------------------- // Static valiables //------------------------------------------------------------------- static uid_t mp_uid = 0; // owner of mount point(only not specified uid opt) static gid_t mp_gid = 0; // group of mount point(only not specified gid opt) static mode_t mp_mode = 0; // mode of mount point static mode_t mp_umask = 0; // umask for mount point static bool is_mp_umask = false;// default does not set. static std::string mountpoint; static std::string passwd_file = ""; static bool utility_mode = false; static bool noxmlns = false; static bool nocopyapi = false; static bool norenameapi = false; static bool nonempty = false; static bool allow_other = false; static uid_t s3fs_uid = 0; static gid_t s3fs_gid = 0; static mode_t s3fs_umask = 0; static bool is_s3fs_uid = false;// default does not set. static bool is_s3fs_gid = false;// default does not set. static bool is_s3fs_umask = false;// default does not set. static bool is_remove_cache = false; static bool create_bucket = false; static int64_t singlepart_copy_limit = FIVE_GB; //------------------------------------------------------------------- // Static functions : prototype //------------------------------------------------------------------- static void s3fs_usr2_handler(int sig); static bool set_s3fs_usr2_handler(void); static s3fs_log_level set_s3fs_log_level(s3fs_log_level level); static s3fs_log_level bumpup_s3fs_log_level(void); static bool is_special_name_folder_object(const char* path); static int chk_dir_object_type(const char* path, string& newpath, string& nowpath, string& nowcache, headers_t* pmeta = NULL, int* pDirType = NULL); static int get_object_attribute(const char* path, struct stat* pstbuf, headers_t* pmeta = NULL, bool overcheck = true, bool* pisforce = NULL); static int check_object_access(const char* path, int mask, struct stat* pstbuf); static int check_object_owner(const char* path, struct stat* pstbuf); static int check_parent_object_access(const char* path, int mask); static FdEntity* get_local_fent(const char* path, bool is_load = false); static bool multi_head_callback(S3fsCurl* s3fscurl); static S3fsCurl* multi_head_retry_callback(S3fsCurl* s3fscurl); static int readdir_multi_head(const char* path, S3ObjList& head, void* buf, fuse_fill_dir_t filler); static int list_bucket(const char* path, S3ObjList& head, const char* delimiter, bool check_content_only = false); static int directory_empty(const char* path); static bool is_truncated(xmlDocPtr doc);; static int append_objects_from_xml_ex(const char* path, xmlDocPtr doc, xmlXPathContextPtr ctx, const char* ex_contents, const char* ex_key, const char* ex_etag, int isCPrefix, S3ObjList& head); static int append_objects_from_xml(const char* path, xmlDocPtr doc, S3ObjList& head); static bool GetXmlNsUrl(xmlDocPtr doc, string& nsurl); static xmlChar* get_base_exp(xmlDocPtr doc, const char* exp); static xmlChar* get_prefix(xmlDocPtr doc); static xmlChar* get_next_marker(xmlDocPtr doc); static char* get_object_name(xmlDocPtr doc, xmlNodePtr node, const char* path); static int put_headers(const char* path, headers_t& meta, bool is_copy); static int rename_large_object(const char* from, const char* to); static int create_file_object(const char* path, mode_t mode, uid_t uid, gid_t gid); static int create_directory_object(const char* path, mode_t mode, time_t time, uid_t uid, gid_t gid); static int rename_object(const char* from, const char* to); static int rename_object_nocopy(const char* from, const char* to); static int clone_directory_object(const char* from, const char* to); static int rename_directory(const char* from, const char* to); static int remote_mountpath_exists(const char* path); static xmlChar* get_exp_value_xml(xmlDocPtr doc, xmlXPathContextPtr ctx, const char* exp_key); static void print_uncomp_mp_list(uncomp_mp_list_t& list); static bool abort_uncomp_mp_list(uncomp_mp_list_t& list); static bool get_uncomp_mp_list(xmlDocPtr doc, uncomp_mp_list_t& list); static void free_xattrs(xattrs_t& xattrs); static bool parse_xattr_keyval(const std::string& xattrpair, string& key, PXATTRVAL& pval); static size_t parse_xattrs(const std::string& strxattrs, xattrs_t& xattrs); static std::string build_xattrs(const xattrs_t& xattrs); static int s3fs_utility_mode(void); static int s3fs_check_service(void); static int check_for_aws_format(void); static int check_passwd_file_perms(void); static int read_passwd_file(void); static int get_access_keys(void); static int set_moutpoint_attribute(struct stat& mpst); static int my_fuse_opt_proc(void* data, const char* arg, int key, struct fuse_args* outargs); // fuse interface functions static int s3fs_getattr(const char* path, struct stat* stbuf); static int s3fs_readlink(const char* path, char* buf, size_t size); static int s3fs_mknod(const char* path, mode_t mode, dev_t rdev); static int s3fs_mkdir(const char* path, mode_t mode); static int s3fs_unlink(const char* path); static int s3fs_rmdir(const char* path); static int s3fs_symlink(const char* from, const char* to); static int s3fs_rename(const char* from, const char* to); static int s3fs_link(const char* from, const char* to); static int s3fs_chmod(const char* path, mode_t mode); static int s3fs_chmod_nocopy(const char* path, mode_t mode); static int s3fs_chown(const char* path, uid_t uid, gid_t gid); static int s3fs_chown_nocopy(const char* path, uid_t uid, gid_t gid); static int s3fs_utimens(const char* path, const struct timespec ts[2]); static int s3fs_utimens_nocopy(const char* path, const struct timespec ts[2]); static int s3fs_truncate(const char* path, off_t size); static int s3fs_create(const char* path, mode_t mode, struct fuse_file_info* fi); static int s3fs_open(const char* path, struct fuse_file_info* fi); static int s3fs_read(const char* path, char* buf, size_t size, off_t offset, struct fuse_file_info* fi); static int s3fs_write(const char* path, const char* buf, size_t size, off_t offset, struct fuse_file_info* fi); static int s3fs_statfs(const char* path, struct statvfs* stbuf); static int s3fs_flush(const char* path, struct fuse_file_info* fi); static int s3fs_fsync(const char* path, int datasync, struct fuse_file_info* fi); static int s3fs_release(const char* path, struct fuse_file_info* fi); static int s3fs_opendir(const char* path, struct fuse_file_info* fi); static int s3fs_readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fi); static int s3fs_access(const char* path, int mask); static void* s3fs_init(struct fuse_conn_info* conn); static void s3fs_destroy(void*); #if defined(__APPLE__) static int s3fs_setxattr(const char* path, const char* name, const char* value, size_t size, int flags, uint32_t position); static int s3fs_getxattr(const char* path, const char* name, char* value, size_t size, uint32_t position); #else static int s3fs_setxattr(const char* path, const char* name, const char* value, size_t size, int flags); static int s3fs_getxattr(const char* path, const char* name, char* value, size_t size); #endif static int s3fs_listxattr(const char* path, char* list, size_t size); static int s3fs_removexattr(const char* path, const char* name); //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- static void s3fs_usr2_handler(int sig) { if(SIGUSR2 == sig){ bumpup_s3fs_log_level(); } } static bool set_s3fs_usr2_handler(void) { struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = s3fs_usr2_handler; sa.sa_flags = SA_RESTART; if(0 != sigaction(SIGUSR2, &sa, NULL)){ return false; } return true; } static s3fs_log_level set_s3fs_log_level(s3fs_log_level level) { if(level == debug_level){ return debug_level; } s3fs_log_level old = debug_level; debug_level = level; setlogmask(LOG_UPTO(S3FS_LOG_LEVEL_TO_SYSLOG(debug_level))); S3FS_PRN_CRIT("change debug level from %sto %s", S3FS_LOG_LEVEL_STRING(old), S3FS_LOG_LEVEL_STRING(debug_level)); return old; } static s3fs_log_level bumpup_s3fs_log_level(void) { s3fs_log_level old = debug_level; debug_level = ( S3FS_LOG_CRIT == debug_level ? S3FS_LOG_ERR : S3FS_LOG_ERR == debug_level ? S3FS_LOG_WARN : S3FS_LOG_WARN == debug_level ? S3FS_LOG_INFO : S3FS_LOG_INFO == debug_level ? S3FS_LOG_DBG : S3FS_LOG_CRIT ); setlogmask(LOG_UPTO(S3FS_LOG_LEVEL_TO_SYSLOG(debug_level))); S3FS_PRN_CRIT("change debug level from %sto %s", S3FS_LOG_LEVEL_STRING(old), S3FS_LOG_LEVEL_STRING(debug_level)); return old; } static bool is_special_name_folder_object(const char* path) { if(!path || '\0' == path[0]){ return false; } string strpath = path; headers_t header; if(string::npos == strpath.find("_$folder$", 0)){ if('/' == strpath[strpath.length() - 1]){ strpath = strpath.substr(0, strpath.length() - 1); } strpath += "_$folder$"; } S3fsCurl s3fscurl; if(0 != s3fscurl.HeadRequest(strpath.c_str(), header)){ return false; } header.clear(); S3FS_MALLOCTRIM(0); return true; } // [Detail] // This function is complicated for checking directory object type. // Arguments is used for deleting cache/path, and remake directory object. // Please see the codes which calls this function. // // path: target path // newpath: should be object path for making/putting/getting after checking // nowpath: now object name for deleting after checking // nowcache: now cache path for deleting after checking // pmeta: headers map // pDirType: directory object type // static int chk_dir_object_type(const char* path, string& newpath, string& nowpath, string& nowcache, headers_t* pmeta, int* pDirType) { int TypeTmp; int result = -1; bool isforce = false; int* pType = pDirType ? pDirType : &TypeTmp; // Normalize new path. newpath = path; if('/' != newpath[newpath.length() - 1]){ string::size_type Pos; if(string::npos != (Pos = newpath.find("_$folder$", 0))){ newpath = newpath.substr(0, Pos); } newpath += "/"; } // Alwayes check "dir/" at first. if(0 == (result = get_object_attribute(newpath.c_str(), NULL, pmeta, false, &isforce))){ // Found "dir/" cache --> Check for "_$folder$", "no dir object" nowcache = newpath; if(is_special_name_folder_object(newpath.c_str())){ // "_$folder$" type. (*pType) = DIRTYPE_FOLDER; nowpath = newpath.substr(0, newpath.length() - 1) + "_$folder$"; // cut and add }else if(isforce){ // "no dir object" type. (*pType) = DIRTYPE_NOOBJ; nowpath = ""; }else{ nowpath = path; if(0 < nowpath.length() && '/' == nowpath[nowpath.length() - 1]){ // "dir/" type (*pType) = DIRTYPE_NEW; }else{ // "dir" type (*pType) = DIRTYPE_OLD; } } }else{ // Check "dir" nowpath = newpath.substr(0, newpath.length() - 1); if(0 == (result = get_object_attribute(nowpath.c_str(), NULL, pmeta, false, &isforce))){ // Found "dir" cache --> this case is only "dir" type. // Because, if object is "_$folder$" or "no dir object", the cache is "dir/" type. // (But "no dir objet" is checked here.) nowcache = nowpath; if(isforce){ (*pType) = DIRTYPE_NOOBJ; nowpath = ""; }else{ (*pType) = DIRTYPE_OLD; } }else{ // Not found cache --> check for "_$folder$" and "no dir object". nowcache = ""; // This case is no cahce. nowpath += "_$folder$"; if(is_special_name_folder_object(nowpath.c_str())){ // "_$folder$" type. (*pType) = DIRTYPE_FOLDER; result = 0; // result is OK. }else if(-ENOTEMPTY == directory_empty(newpath.c_str())){ // "no dir object" type. (*pType) = DIRTYPE_NOOBJ; nowpath = ""; // now path. result = 0; // result is OK. }else{ // Error: Unknown type. (*pType) = DIRTYPE_UNKNOWN; newpath = ""; nowpath = ""; } } } return result; } // // Get object attributes with stat cache. // This function is base for s3fs_getattr(). // // [NOTICE] // Checking order is changed following list because of reducing the number of the requests. // 1) "dir" // 2) "dir/" // 3) "dir_$folder$" // static int get_object_attribute(const char* path, struct stat* pstbuf, headers_t* pmeta, bool overcheck, bool* pisforce) { int result = -1; struct stat tmpstbuf; struct stat* pstat = pstbuf ? pstbuf : &tmpstbuf; headers_t tmpHead; headers_t* pheader = pmeta ? pmeta : &tmpHead; string strpath; S3fsCurl s3fscurl; bool forcedir = false; string::size_type Pos; S3FS_PRN_DBG("[path=%s]", path); if(!path || '\0' == path[0]){ return -ENOENT; } memset(pstat, 0, sizeof(struct stat)); if(0 == strcmp(path, "/") || 0 == strcmp(path, ".")){ pstat->st_nlink = 1; // see fuse faq pstat->st_mode = mp_mode; pstat->st_uid = is_s3fs_uid ? s3fs_uid : mp_uid; pstat->st_gid = is_s3fs_gid ? s3fs_gid : mp_gid; return 0; } // Check cache. strpath = path; if(overcheck && string::npos != (Pos = strpath.find("_$folder$", 0))){ strpath = strpath.substr(0, Pos); strpath += "/"; } if(pisforce){ (*pisforce) = false; } if(StatCache::getStatCacheData()->GetStat(strpath, pstat, pheader, overcheck, pisforce)){ return 0; } if(StatCache::getStatCacheData()->IsNoObjectCache(strpath)){ // there is the path in the cache for no object, it is no object. return -ENOENT; } // At first, check path strpath = path; result = s3fscurl.HeadRequest(strpath.c_str(), (*pheader)); s3fscurl.DestroyCurlHandle(); // overcheck if(overcheck && 0 != result){ if('/' != strpath[strpath.length() - 1] && string::npos == strpath.find("_$folder$", 0)){ // path is "object", check "object/" for overcheck strpath += "/"; result = s3fscurl.HeadRequest(strpath.c_str(), (*pheader)); s3fscurl.DestroyCurlHandle(); } if(0 != result){ // not found "object/", check "_$folder$" strpath = path; if(string::npos == strpath.find("_$folder$", 0)){ if('/' == strpath[strpath.length() - 1]){ strpath = strpath.substr(0, strpath.length() - 1); } strpath += "_$folder$"; result = s3fscurl.HeadRequest(strpath.c_str(), (*pheader)); s3fscurl.DestroyCurlHandle(); } } if(0 != result){ // not found "object/" and "object_$folder$", check no dir object. strpath = path; if(string::npos == strpath.find("_$folder$", 0)){ if('/' == strpath[strpath.length() - 1]){ strpath = strpath.substr(0, strpath.length() - 1); } if(-ENOTEMPTY == directory_empty(strpath.c_str())){ // found "no dir obejct". strpath += "/"; forcedir = true; if(pisforce){ (*pisforce) = true; } result = 0; } } } }else{ // found "path" object. if('/' != strpath[strpath.length() - 1]){ // check a case of that "object" does not have attribute and "object" is possible to be directory. if(is_need_check_obj_detail(*pheader)){ if(-ENOTEMPTY == directory_empty(strpath.c_str())){ strpath += "/"; forcedir = true; if(pisforce){ (*pisforce) = true; } result = 0; } } } } if(0 != result){ // finally, "path" object did not find. Add no object cache. strpath = path; // reset original StatCache::getStatCacheData()->AddNoObjectCache(strpath); return result; } // if path has "_$folder$", need to cut it. if(string::npos != (Pos = strpath.find("_$folder$", 0))){ strpath = strpath.substr(0, Pos); strpath += "/"; } // Set into cache if(0 != StatCache::getStatCacheData()->GetCacheSize()){ // add into stat cache if(!StatCache::getStatCacheData()->AddStat(strpath, (*pheader), forcedir)){ S3FS_PRN_ERR("failed adding stat cache [path=%s]", strpath.c_str()); return -ENOENT; } if(!StatCache::getStatCacheData()->GetStat(strpath, pstat, pheader, overcheck, pisforce)){ // There is not in cache.(why?) -> retry to convert. if(!convert_header_to_stat(strpath.c_str(), (*pheader), pstat, forcedir)){ S3FS_PRN_ERR("failed convert headers to stat[path=%s]", strpath.c_str()); return -ENOENT; } } }else{ // cache size is Zero -> only convert. if(!convert_header_to_stat(strpath.c_str(), (*pheader), pstat, forcedir)){ S3FS_PRN_ERR("failed convert headers to stat[path=%s]", strpath.c_str()); return -ENOENT; } } return 0; } // // Check the object uid and gid for write/read/execute. // The param "mask" is as same as access() function. // If there is not a target file, this function returns -ENOENT. // If the target file can be accessed, the result always is 0. // // path: the target object path // mask: bit field(F_OK, R_OK, W_OK, X_OK) like access(). // stat: NULL or the pointer of struct stat. // static int check_object_access(const char* path, int mask, struct stat* pstbuf) { int result; struct stat st; struct stat* pst = (pstbuf ? pstbuf : &st); struct fuse_context* pcxt; S3FS_PRN_DBG("[path=%s]", path); if(NULL == (pcxt = fuse_get_context())){ return -EIO; } if(0 != (result = get_object_attribute(path, pst))){ // If there is not tha target file(object), reusult is -ENOENT. return result; } if(0 == pcxt->uid){ // root is allowed all accessing. return 0; } if(is_s3fs_uid && s3fs_uid == pcxt->uid){ // "uid" user is allowed all accessing. return 0; } if(F_OK == mask){ // if there is a file, always return allowed. return 0; } // for "uid", "gid" option uid_t obj_uid = (is_s3fs_uid ? s3fs_uid : pst->st_uid); gid_t obj_gid = (is_s3fs_gid ? s3fs_gid : pst->st_gid); // compare file mode and uid/gid + mask. mode_t mode; mode_t base_mask = S_IRWXO; if(is_s3fs_umask){ // If umask is set, all object attributes set ~umask. mode = ((S_IRWXU | S_IRWXG | S_IRWXO) & ~s3fs_umask); }else{ mode = pst->st_mode; } if(pcxt->uid == obj_uid){ base_mask |= S_IRWXU; } if(pcxt->gid == obj_gid){ base_mask |= S_IRWXG; } if(1 == is_uid_inculde_group(pcxt->uid, obj_gid)){ base_mask |= S_IRWXG; } mode &= base_mask; if(X_OK == (mask & X_OK)){ if(0 == (mode & (S_IXUSR | S_IXGRP | S_IXOTH))){ return -EPERM; } } if(W_OK == (mask & W_OK)){ if(0 == (mode & (S_IWUSR | S_IWGRP | S_IWOTH))){ return -EACCES; } } if(R_OK == (mask & R_OK)){ if(0 == (mode & (S_IRUSR | S_IRGRP | S_IROTH))){ return -EACCES; } } if(0 == mode){ return -EACCES; } return 0; } static int check_object_owner(const char* path, struct stat* pstbuf) { int result; struct stat st; struct stat* pst = (pstbuf ? pstbuf : &st); struct fuse_context* pcxt; S3FS_PRN_DBG("[path=%s]", path); if(NULL == (pcxt = fuse_get_context())){ return -EIO; } if(0 != (result = get_object_attribute(path, pst))){ // If there is not tha target file(object), reusult is -ENOENT. return result; } // check owner if(0 == pcxt->uid){ // root is allowed all accessing. return 0; } if(is_s3fs_uid && s3fs_uid == pcxt->uid){ // "uid" user is allowed all accessing. return 0; } if(pcxt->uid == pst->st_uid){ return 0; } return -EPERM; } // // Check accessing the parent directories of the object by uid and gid. // static int check_parent_object_access(const char* path, int mask) { string parent; int result; S3FS_PRN_DBG("[path=%s]", path); if(0 == strcmp(path, "/") || 0 == strcmp(path, ".")){ // path is mount point. return 0; } if(X_OK == (mask & X_OK)){ for(parent = mydirname(path); 0 < parent.size(); parent = mydirname(parent)){ if(parent == "."){ parent = "/"; } if(0 != (result = check_object_access(parent.c_str(), X_OK, NULL))){ return result; } if(parent == "/" || parent == "."){ break; } } } mask = (mask & ~X_OK); if(0 != mask){ parent = mydirname(path); if(parent == "."){ parent = "/"; } if(0 != (result = check_object_access(parent.c_str(), mask, NULL))){ return result; } } return 0; } // // ssevalue is MD5 for SSE-C type, or KMS id for SSE-KMS // bool get_object_sse_type(const char* path, sse_type_t& ssetype, string& ssevalue) { if(!path){ return false; } headers_t meta; if(0 != get_object_attribute(path, NULL, &meta)){ S3FS_PRN_ERR("Failed to get object(%s) headers", path); return false; } ssetype = SSE_DISABLE; ssevalue.erase(); for(headers_t::iterator iter = meta.begin(); iter != meta.end(); ++iter){ string key = (*iter).first; if(0 == strcasecmp(key.c_str(), "x-amz-server-side-encryption") && 0 == strcasecmp((*iter).second.c_str(), "AES256")){ ssetype = SSE_S3; }else if(0 == strcasecmp(key.c_str(), "x-amz-server-side-encryption-aws-kms-key-id")){ ssetype = SSE_KMS; ssevalue = (*iter).second; }else if(0 == strcasecmp(key.c_str(), "x-amz-server-side-encryption-customer-key-md5")){ ssetype = SSE_C; ssevalue = (*iter).second; } } return true; } static FdEntity* get_local_fent(const char* path, bool is_load) { struct stat stobj; FdEntity* ent; S3FS_PRN_INFO2("[path=%s]", path); if(0 != get_object_attribute(path, &stobj)){ return NULL; } // open time_t mtime = (!S_ISREG(stobj.st_mode) || S_ISLNK(stobj.st_mode)) ? -1 : stobj.st_mtime; bool force_tmpfile = S_ISREG(stobj.st_mode) ? false : true; if(NULL == (ent = FdManager::get()->Open(path, stobj.st_size, mtime, force_tmpfile, true))){ S3FS_PRN_ERR("Coult not open file. errno(%d)", errno); return NULL; } // load if(is_load && !ent->LoadFull()){ S3FS_PRN_ERR("Coult not load file. errno(%d)", errno); FdManager::get()->Close(ent); return NULL; } return ent; } /** * create or update s3 meta * ow_sse_flg is for over writing sse header by use_sse option. * @return fuse return code */ static int put_headers(const char* path, headers_t& meta, bool is_copy) { int result; S3fsCurl s3fscurl(true); struct stat buf; S3FS_PRN_INFO2("[path=%s]", path); // files larger than 5GB must be modified via the multipart interface // *** If there is not target object(a case of move command), // get_object_attribute() returns error with initilizing buf. (void)get_object_attribute(path, &buf); if(buf.st_size >= FIVE_GB){ // multipart if(0 != (result = s3fscurl.MultipartHeadRequest(path, buf.st_size, meta, is_copy))){ return result; } }else{ if(0 != (result = s3fscurl.PutHeadRequest(path, meta, is_copy))){ return result; } } FdEntity* ent = NULL; if(NULL == (ent = FdManager::get()->ExistOpen(path))){ // no opened fd if(FdManager::get()->IsCacheDir()){ // create cache file if be needed ent = FdManager::get()->Open(path, buf.st_size, -1, false, true); } } if(ent){ time_t mtime = get_mtime(meta); ent->SetMtime(mtime); FdManager::get()->Close(ent); } return 0; } static int s3fs_getattr(const char* path, struct stat* stbuf) { int result; S3FS_PRN_INFO("[path=%s]", path); // check parent directory attribute. if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } if(0 != (result = check_object_access(path, F_OK, stbuf))){ return result; } // If has already opened fd, the st_size shuld be instead. // (See: Issue 241) if(stbuf){ FdEntity* ent; if(NULL != (ent = FdManager::get()->ExistOpen(path))){ struct stat tmpstbuf; if(ent->GetStats(tmpstbuf)){ stbuf->st_size = tmpstbuf.st_size; } FdManager::get()->Close(ent); } stbuf->st_blksize = 4096; stbuf->st_blocks = get_blocks(stbuf->st_size); } S3FS_PRN_DBG("[path=%s] uid=%u, gid=%u, mode=%04o", path, (unsigned int)(stbuf->st_uid), (unsigned int)(stbuf->st_gid), stbuf->st_mode); S3FS_MALLOCTRIM(0); return result; } static int s3fs_readlink(const char* path, char* buf, size_t size) { if(!path || !buf || 0 >= size){ return 0; } // Open FdEntity* ent; if(NULL == (ent = get_local_fent(path))){ S3FS_PRN_ERR("could not get fent(file=%s)", path); return -EIO; } // Get size off_t readsize; if(!ent->GetSize(readsize)){ S3FS_PRN_ERR("could not get file size(file=%s)", path); FdManager::get()->Close(ent); return -EIO; } if(static_cast(size) <= readsize){ readsize = size - 1; } // Read ssize_t ressize; if(0 > (ressize = ent->Read(buf, 0, static_cast(readsize)))){ S3FS_PRN_ERR("could not read file(file=%s, errno=%zd)", path, ressize); FdManager::get()->Close(ent); return static_cast(ressize); } buf[ressize] = '\0'; FdManager::get()->Close(ent); S3FS_MALLOCTRIM(0); return 0; } static int do_create_bucket(void) { S3FS_PRN_INFO2("/"); headers_t meta; S3fsCurl s3fscurl(true); long res = s3fscurl.PutRequest("/", meta, -1); if(res < 0){ // fd=-1 means for creating zero byte object. long responseCode = s3fscurl.GetLastResponseCode(); if((responseCode == 400 || responseCode == 403) && S3fsCurl::IsSignatureV4()){ S3FS_PRN_ERR("Could not connect, so retry to connect by signature version 2."); S3fsCurl::SetSignatureV4(false); // retry to check s3fscurl.DestroyCurlHandle(); res = s3fscurl.PutRequest("/", meta, -1); } } return res; } // common function for creation of a plain object static int create_file_object(const char* path, mode_t mode, uid_t uid, gid_t gid) { S3FS_PRN_INFO2("[path=%s][mode=%04o]", path, mode); headers_t meta; meta["Content-Type"] = S3fsCurl::LookupMimeType(string(path)); meta["x-amz-meta-uid"] = str(uid); meta["x-amz-meta-gid"] = str(gid); meta["x-amz-meta-mode"] = str(mode); meta["x-amz-meta-mtime"] = str(time(NULL)); S3fsCurl s3fscurl(true); return s3fscurl.PutRequest(path, meta, -1); // fd=-1 means for creating zero byte object. } static int s3fs_mknod(const char *path, mode_t mode, dev_t rdev) { int result; struct fuse_context* pcxt; S3FS_PRN_INFO("[path=%s][mode=%04o][dev=%ju]", path, mode, (uintmax_t)rdev); if(NULL == (pcxt = fuse_get_context())){ return -EIO; } if(0 != (result = create_file_object(path, mode, pcxt->uid, pcxt->gid))){ S3FS_PRN_ERR("could not create object for special file(result=%d)", result); return result; } StatCache::getStatCacheData()->DelStat(path); S3FS_MALLOCTRIM(0); return result; } static int s3fs_create(const char* path, mode_t mode, struct fuse_file_info* fi) { int result; struct fuse_context* pcxt; S3FS_PRN_INFO("[path=%s][mode=%04o][flags=%d]", path, mode, fi->flags); if(NULL == (pcxt = fuse_get_context())){ return -EIO; } // check parent directory attribute. if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } result = check_object_access(path, W_OK, NULL); if(-ENOENT == result){ if(0 != (result = check_parent_object_access(path, W_OK))){ return result; } }else if(0 != result){ return result; } result = create_file_object(path, mode, pcxt->uid, pcxt->gid); StatCache::getStatCacheData()->DelStat(path); if(result != 0){ return result; } FdEntity* ent; if(NULL == (ent = FdManager::get()->Open(path, 0, -1, false, true))){ return -EIO; } fi->fh = ent->GetFd(); S3FS_MALLOCTRIM(0); return 0; } static int create_directory_object(const char* path, mode_t mode, time_t time, uid_t uid, gid_t gid) { S3FS_PRN_INFO1("[path=%s][mode=%04o][time=%jd][uid=%u][gid=%u]", path, mode, (intmax_t)time, (unsigned int)uid, (unsigned int)gid); if(!path || '\0' == path[0]){ return -1; } string tpath = path; if('/' != tpath[tpath.length() - 1]){ tpath += "/"; } headers_t meta; meta["Content-Type"] = string("application/x-directory"); meta["x-amz-meta-uid"] = str(uid); meta["x-amz-meta-gid"] = str(gid); meta["x-amz-meta-mode"] = str(mode); meta["x-amz-meta-mtime"] = str(time); S3fsCurl s3fscurl; return s3fscurl.PutRequest(tpath.c_str(), meta, -1); // fd=-1 means for creating zero byte object. } static int s3fs_mkdir(const char* path, mode_t mode) { int result; struct fuse_context* pcxt; S3FS_PRN_INFO("[path=%s][mode=%04o]", path, mode); if(NULL == (pcxt = fuse_get_context())){ return -EIO; } // check parent directory attribute. if(0 != (result = check_parent_object_access(path, W_OK | X_OK))){ return result; } if(-ENOENT != (result = check_object_access(path, F_OK, NULL))){ if(0 == result){ result = -EEXIST; } return result; } result = create_directory_object(path, mode, time(NULL), pcxt->uid, pcxt->gid); StatCache::getStatCacheData()->DelStat(path); S3FS_MALLOCTRIM(0); return result; } static int s3fs_unlink(const char* path) { int result; S3FS_PRN_INFO("[path=%s]", path); if(0 != (result = check_parent_object_access(path, W_OK | X_OK))){ return result; } S3fsCurl s3fscurl; result = s3fscurl.DeleteRequest(path); FdManager::DeleteCacheFile(path); StatCache::getStatCacheData()->DelStat(path); S3FS_MALLOCTRIM(0); return result; } static int directory_empty(const char* path) { int result; S3ObjList head; if((result = list_bucket(path, head, "/", true)) != 0){ S3FS_PRN_ERR("list_bucket returns error."); return result; } if(!head.IsEmpty()){ return -ENOTEMPTY; } return 0; } static int s3fs_rmdir(const char* path) { int result; string strpath; struct stat stbuf; S3FS_PRN_INFO("[path=%s]", path); if(0 != (result = check_parent_object_access(path, W_OK | X_OK))){ return result; } // directory must be empty if(directory_empty(path) != 0){ return -ENOTEMPTY; } strpath = path; if('/' != strpath[strpath.length() - 1]){ strpath += "/"; } S3fsCurl s3fscurl; result = s3fscurl.DeleteRequest(strpath.c_str()); s3fscurl.DestroyCurlHandle(); StatCache::getStatCacheData()->DelStat(strpath.c_str()); // double check for old version(before 1.63) // The old version makes "dir" object, newer version makes "dir/". // A case, there is only "dir", the first removing object is "dir/". // Then "dir/" is not exists, but curl_delete returns 0. // So need to check "dir" and should be removed it. if('/' == strpath[strpath.length() - 1]){ strpath = strpath.substr(0, strpath.length() - 1); } if(0 == get_object_attribute(strpath.c_str(), &stbuf, NULL, false)){ if(S_ISDIR(stbuf.st_mode)){ // Found "dir" object. result = s3fscurl.DeleteRequest(strpath.c_str()); s3fscurl.DestroyCurlHandle(); StatCache::getStatCacheData()->DelStat(strpath.c_str()); } } // If there is no "dir" and "dir/" object(this case is made by s3cmd/s3sync), // the cache key is "dir/". So we get error only onece(delete "dir/"). // check for "_$folder$" object. // This processing is necessary for other S3 clients compatibility. if(is_special_name_folder_object(strpath.c_str())){ strpath += "_$folder$"; result = s3fscurl.DeleteRequest(strpath.c_str()); } S3FS_MALLOCTRIM(0); return result; } static int s3fs_symlink(const char* from, const char* to) { int result; struct fuse_context* pcxt; S3FS_PRN_INFO("[from=%s][to=%s]", from, to); if(NULL == (pcxt = fuse_get_context())){ return -EIO; } if(0 != (result = check_parent_object_access(to, W_OK | X_OK))){ return result; } if(-ENOENT != (result = check_object_access(to, F_OK, NULL))){ if(0 == result){ result = -EEXIST; } return result; } headers_t headers; headers["Content-Type"] = string("application/octet-stream"); // Static headers["x-amz-meta-mode"] = str(S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO); headers["x-amz-meta-mtime"] = str(time(NULL)); headers["x-amz-meta-uid"] = str(pcxt->uid); headers["x-amz-meta-gid"] = str(pcxt->gid); // open tmpfile FdEntity* ent; if(NULL == (ent = FdManager::get()->Open(to, 0, -1, true, true))){ S3FS_PRN_ERR("could not open tmpfile(errno=%d)", errno); return -errno; } // write ssize_t from_size = strlen(from); if(from_size != ent->Write(from, 0, from_size)){ S3FS_PRN_ERR("could not write tmpfile(errno=%d)", errno); FdManager::get()->Close(ent); return -errno; } // upload if(0 != (result = ent->Flush(headers, true))){ S3FS_PRN_WARN("could not upload tmpfile(result=%d)", result); } FdManager::get()->Close(ent); StatCache::getStatCacheData()->DelStat(to); S3FS_MALLOCTRIM(0); return result; } static int rename_object(const char* from, const char* to) { int result; string s3_realpath; headers_t meta; S3FS_PRN_INFO1("[from=%s][to=%s]", from , to); if(0 != (result = check_parent_object_access(to, W_OK | X_OK))){ // not permmit writing "to" object parent dir. return result; } if(0 != (result = check_parent_object_access(from, W_OK | X_OK))){ // not permmit removing "from" object parent dir. return result; } if(0 != (result = get_object_attribute(from, NULL, &meta))){ return result; } s3_realpath = get_realpath(from); meta["x-amz-copy-source"] = urlEncode(service_path + bucket + s3_realpath); meta["Content-Type"] = S3fsCurl::LookupMimeType(string(to)); meta["x-amz-metadata-directive"] = "REPLACE"; if(0 != (result = put_headers(to, meta, true))){ return result; } FdManager::get()->Rename(from, to); result = s3fs_unlink(from); StatCache::getStatCacheData()->DelStat(to); return result; } static int rename_object_nocopy(const char* from, const char* to) { int result; headers_t meta; S3FS_PRN_INFO1("[from=%s][to=%s]", from , to); if(0 != (result = check_parent_object_access(to, W_OK | X_OK))){ // not permmit writing "to" object parent dir. return result; } if(0 != (result = check_parent_object_access(from, W_OK | X_OK))){ // not permmit removing "from" object parent dir. return result; } // Get attributes if(0 != (result = get_object_attribute(from, NULL, &meta))){ return result; } // Set header meta["Content-Type"] = S3fsCurl::LookupMimeType(string(to)); // open & load FdEntity* ent; if(NULL == (ent = get_local_fent(from, true))){ S3FS_PRN_ERR("could not open and read file(%s)", from); return -EIO; } // upload if(0 != (result = ent->RowFlush(to, meta, true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", to, result); FdManager::get()->Close(ent); return result; } FdManager::get()->Close(ent); // Remove file result = s3fs_unlink(from); // Stats StatCache::getStatCacheData()->DelStat(to); StatCache::getStatCacheData()->DelStat(from); return result; } static int rename_large_object(const char* from, const char* to) { int result; struct stat buf; headers_t meta; S3FS_PRN_INFO1("[from=%s][to=%s]", from , to); if(0 != (result = check_parent_object_access(to, W_OK | X_OK))){ // not permmit writing "to" object parent dir. return result; } if(0 != (result = check_parent_object_access(from, W_OK | X_OK))){ // not permmit removing "from" object parent dir. return result; } if(0 != (result = get_object_attribute(from, &buf, &meta, false))){ return result; } S3fsCurl s3fscurl(true); if(0 != (result = s3fscurl.MultipartRenameRequest(from, to, meta, buf.st_size))){ return result; } s3fscurl.DestroyCurlHandle(); StatCache::getStatCacheData()->DelStat(to); return s3fs_unlink(from); } static int clone_directory_object(const char* from, const char* to) { int result = -1; struct stat stbuf; S3FS_PRN_INFO1("[from=%s][to=%s]", from, to); // get target's attributes if(0 != (result = get_object_attribute(from, &stbuf))){ return result; } result = create_directory_object(to, stbuf.st_mode, stbuf.st_mtime, stbuf.st_uid, stbuf.st_gid); StatCache::getStatCacheData()->DelStat(to); return result; } static int rename_directory(const char* from, const char* to) { S3ObjList head; s3obj_list_t headlist; string strfrom = from ? from : ""; // from is without "/". string strto = to ? to : ""; // to is without "/" too. string basepath = strfrom + "/"; string newpath; // should be from name(not used) string nowcache; // now cache path(not used) int DirType; bool normdir; MVNODE* mn_head = NULL; MVNODE* mn_tail = NULL; MVNODE* mn_cur; struct stat stbuf; int result; bool is_dir; S3FS_PRN_INFO1("[from=%s][to=%s]", from, to); // // Initiate and Add base directory into MVNODE struct. // strto += "/"; if(0 == chk_dir_object_type(from, newpath, strfrom, nowcache, NULL, &DirType) && DIRTYPE_UNKNOWN != DirType){ if(DIRTYPE_NOOBJ != DirType){ normdir = false; }else{ normdir = true; strfrom = from; // from directory is not removed, but from directory attr is needed. } if(NULL == (add_mvnode(&mn_head, &mn_tail, strfrom.c_str(), strto.c_str(), true, normdir))){ return -ENOMEM; } }else{ // Something wrong about "from" directory. } // // get a list of all the objects // // No delimiter is specified, the result(head) is all object keys. // (CommonPrefixes is empty, but all object is listed in Key.) if(0 != (result = list_bucket(basepath.c_str(), head, NULL))){ S3FS_PRN_ERR("list_bucket returns error."); return result; } head.GetNameList(headlist); // get name without "/". S3ObjList::MakeHierarchizedList(headlist, false); // add hierarchized dir. s3obj_list_t::const_iterator liter; for(liter = headlist.begin(); headlist.end() != liter; ++liter){ // make "from" and "to" object name. string from_name = basepath + (*liter); string to_name = strto + (*liter); string etag = head.GetETag((*liter).c_str()); // Check subdirectory. StatCache::getStatCacheData()->HasStat(from_name, etag.c_str()); // Check ETag if(0 != get_object_attribute(from_name.c_str(), &stbuf, NULL)){ S3FS_PRN_WARN("failed to get %s object attribute.", from_name.c_str()); continue; } if(S_ISDIR(stbuf.st_mode)){ is_dir = true; if(0 != chk_dir_object_type(from_name.c_str(), newpath, from_name, nowcache, NULL, &DirType) || DIRTYPE_UNKNOWN == DirType){ S3FS_PRN_WARN("failed to get %s%s object directory type.", basepath.c_str(), (*liter).c_str()); continue; } if(DIRTYPE_NOOBJ != DirType){ normdir = false; }else{ normdir = true; from_name = basepath + (*liter); // from directory is not removed, but from directory attr is needed. } }else{ is_dir = false; normdir = false; } // push this one onto the stack if(NULL == add_mvnode(&mn_head, &mn_tail, from_name.c_str(), to_name.c_str(), is_dir, normdir)){ return -ENOMEM; } } // // rename // // rename directory objects. for(mn_cur = mn_head; mn_cur; mn_cur = mn_cur->next){ if(mn_cur->is_dir && mn_cur->old_path && '\0' != mn_cur->old_path[0]){ if(0 != (result = clone_directory_object(mn_cur->old_path, mn_cur->new_path))){ S3FS_PRN_ERR("clone_directory_object returned an error(%d)", result); free_mvnodes(mn_head); return -EIO; } } } // iterate over the list - copy the files with rename_object // does a safe copy - copies first and then deletes old for(mn_cur = mn_head; mn_cur; mn_cur = mn_cur->next){ if(!mn_cur->is_dir){ if(!nocopyapi && !norenameapi){ result = rename_object(mn_cur->old_path, mn_cur->new_path); }else{ result = rename_object_nocopy(mn_cur->old_path, mn_cur->new_path); } if(0 != result){ S3FS_PRN_ERR("rename_object returned an error(%d)", result); free_mvnodes(mn_head); return -EIO; } } } // Iterate over old the directories, bottoms up and remove for(mn_cur = mn_tail; mn_cur; mn_cur = mn_cur->prev){ if(mn_cur->is_dir && mn_cur->old_path && '\0' != mn_cur->old_path[0]){ if(!(mn_cur->is_normdir)){ if(0 != (result = s3fs_rmdir(mn_cur->old_path))){ S3FS_PRN_ERR("s3fs_rmdir returned an error(%d)", result); free_mvnodes(mn_head); return -EIO; } }else{ // cache clear. StatCache::getStatCacheData()->DelStat(mn_cur->old_path); } } } free_mvnodes(mn_head); return 0; } static int s3fs_rename(const char* from, const char* to) { struct stat buf; int result; S3FS_PRN_INFO("[from=%s][to=%s]", from, to); if(0 != (result = check_parent_object_access(to, W_OK | X_OK))){ // not permmit writing "to" object parent dir. return result; } if(0 != (result = check_parent_object_access(from, W_OK | X_OK))){ // not permmit removing "from" object parent dir. return result; } if(0 != (result = get_object_attribute(from, &buf, NULL))){ return result; } // files larger than 5GB must be modified via the multipart interface if(S_ISDIR(buf.st_mode)){ result = rename_directory(from, to); }else if(!nomultipart && buf.st_size >= singlepart_copy_limit){ result = rename_large_object(from, to); }else{ if(!nocopyapi && !norenameapi){ result = rename_object(from, to); }else{ result = rename_object_nocopy(from, to); } } S3FS_MALLOCTRIM(0); return result; } static int s3fs_link(const char* from, const char* to) { S3FS_PRN_INFO("[from=%s][to=%s]", from, to); return -EPERM; } static int s3fs_chmod(const char* path, mode_t mode) { int result; string strpath; string newpath; string nowcache; headers_t meta; struct stat stbuf; int nDirType = DIRTYPE_UNKNOWN; S3FS_PRN_INFO("[path=%s][mode=%04o]", path, mode); if(0 == strcmp(path, "/")){ S3FS_PRN_ERR("Could not change mode for mount point."); return -EIO; } if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } if(0 != (result = check_object_owner(path, &stbuf))){ return result; } if(S_ISDIR(stbuf.st_mode)){ result = chk_dir_object_type(path, newpath, strpath, nowcache, &meta, &nDirType); }else{ strpath = path; nowcache = strpath; result = get_object_attribute(strpath.c_str(), NULL, &meta); } if(0 != result){ return result; } if(S_ISDIR(stbuf.st_mode) && IS_REPLACEDIR(nDirType)){ // Should rebuild directory object(except new type) // Need to remove old dir("dir" etc) and make new dir("dir/") // At first, remove directory old object if(IS_RMTYPEDIR(nDirType)){ S3fsCurl s3fscurl; if(0 != (result = s3fscurl.DeleteRequest(strpath.c_str()))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") if(0 != (result = create_directory_object(newpath.c_str(), mode, stbuf.st_mtime, stbuf.st_uid, stbuf.st_gid))){ return result; } }else{ // normal object or directory object of newer version meta["x-amz-meta-mode"] = str(mode); meta["x-amz-copy-source"] = urlEncode(service_path + bucket + get_realpath(strpath.c_str())); meta["x-amz-metadata-directive"] = "REPLACE"; if(put_headers(strpath.c_str(), meta, true) != 0){ return -EIO; } StatCache::getStatCacheData()->DelStat(nowcache); } S3FS_MALLOCTRIM(0); return 0; } static int s3fs_chmod_nocopy(const char* path, mode_t mode) { int result; string strpath; string newpath; string nowcache; headers_t meta; struct stat stbuf; int nDirType = DIRTYPE_UNKNOWN; S3FS_PRN_INFO1("[path=%s][mode=%04o]", path, mode); if(0 == strcmp(path, "/")){ S3FS_PRN_ERR("Could not change mode for maount point."); return -EIO; } if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } if(0 != (result = check_object_owner(path, &stbuf))){ return result; } // Get attributes if(S_ISDIR(stbuf.st_mode)){ result = chk_dir_object_type(path, newpath, strpath, nowcache, &meta, &nDirType); }else{ strpath = path; nowcache = strpath; result = get_object_attribute(strpath.c_str(), NULL, &meta); } if(0 != result){ return result; } if(S_ISDIR(stbuf.st_mode)){ // Should rebuild all directory object // Need to remove old dir("dir" etc) and make new dir("dir/") // At first, remove directory old object if(IS_RMTYPEDIR(nDirType)){ S3fsCurl s3fscurl; if(0 != (result = s3fscurl.DeleteRequest(strpath.c_str()))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") if(0 != (result = create_directory_object(newpath.c_str(), mode, stbuf.st_mtime, stbuf.st_uid, stbuf.st_gid))){ return result; } }else{ // normal object or directory object of newer version // Change file mode meta["x-amz-meta-mode"] = str(mode); // open & load FdEntity* ent; if(NULL == (ent = get_local_fent(strpath.c_str(), true))){ S3FS_PRN_ERR("could not open and read file(%s)", strpath.c_str()); return -EIO; } // upload if(0 != (result = ent->Flush(meta, true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", strpath.c_str(), result); FdManager::get()->Close(ent); return result; } FdManager::get()->Close(ent); StatCache::getStatCacheData()->DelStat(nowcache); } S3FS_MALLOCTRIM(0); return result; } static int s3fs_chown(const char* path, uid_t uid, gid_t gid) { int result; string strpath; string newpath; string nowcache; headers_t meta; struct stat stbuf; int nDirType = DIRTYPE_UNKNOWN; S3FS_PRN_INFO("[path=%s][uid=%u][gid=%u]", path, (unsigned int)uid, (unsigned int)gid); if(0 == strcmp(path, "/")){ S3FS_PRN_ERR("Could not change owner for maount point."); return -EIO; } if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } if(0 != (result = check_object_owner(path, &stbuf))){ return result; } if((uid_t)(-1) == uid){ uid = stbuf.st_uid; } if((gid_t)(-1) == gid){ gid = stbuf.st_gid; } if(S_ISDIR(stbuf.st_mode)){ result = chk_dir_object_type(path, newpath, strpath, nowcache, &meta, &nDirType); }else{ strpath = path; nowcache = strpath; result = get_object_attribute(strpath.c_str(), NULL, &meta); } if(0 != result){ return result; } struct passwd* pwdata= getpwuid(uid); struct group* grdata = getgrgid(gid); if(pwdata){ uid = pwdata->pw_uid; } if(grdata){ gid = grdata->gr_gid; } if(S_ISDIR(stbuf.st_mode) && IS_REPLACEDIR(nDirType)){ // Should rebuild directory object(except new type) // Need to remove old dir("dir" etc) and make new dir("dir/") // At first, remove directory old object if(IS_RMTYPEDIR(nDirType)){ S3fsCurl s3fscurl; if(0 != (result = s3fscurl.DeleteRequest(strpath.c_str()))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") if(0 != (result = create_directory_object(newpath.c_str(), stbuf.st_mode, stbuf.st_mtime, uid, gid))){ return result; } }else{ meta["x-amz-meta-uid"] = str(uid); meta["x-amz-meta-gid"] = str(gid); meta["x-amz-copy-source"] = urlEncode(service_path + bucket + get_realpath(strpath.c_str())); meta["x-amz-metadata-directive"] = "REPLACE"; if(put_headers(strpath.c_str(), meta, true) != 0){ return -EIO; } StatCache::getStatCacheData()->DelStat(nowcache); } S3FS_MALLOCTRIM(0); return 0; } static int s3fs_chown_nocopy(const char* path, uid_t uid, gid_t gid) { int result; string strpath; string newpath; string nowcache; headers_t meta; struct stat stbuf; int nDirType = DIRTYPE_UNKNOWN; S3FS_PRN_INFO1("[path=%s][uid=%u][gid=%u]", path, (unsigned int)uid, (unsigned int)gid); if(0 == strcmp(path, "/")){ S3FS_PRN_ERR("Could not change owner for maount point."); return -EIO; } if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } if(0 != (result = check_object_owner(path, &stbuf))){ return result; } // Get attributes if(S_ISDIR(stbuf.st_mode)){ result = chk_dir_object_type(path, newpath, strpath, nowcache, &meta, &nDirType); }else{ strpath = path; nowcache = strpath; result = get_object_attribute(strpath.c_str(), NULL, &meta); } if(0 != result){ return result; } struct passwd* pwdata= getpwuid(uid); struct group* grdata = getgrgid(gid); if(pwdata){ uid = pwdata->pw_uid; } if(grdata){ gid = grdata->gr_gid; } if(S_ISDIR(stbuf.st_mode)){ // Should rebuild all directory object // Need to remove old dir("dir" etc) and make new dir("dir/") // At first, remove directory old object if(IS_RMTYPEDIR(nDirType)){ S3fsCurl s3fscurl; if(0 != (result = s3fscurl.DeleteRequest(strpath.c_str()))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") if(0 != (result = create_directory_object(newpath.c_str(), stbuf.st_mode, stbuf.st_mtime, uid, gid))){ return result; } }else{ // normal object or directory object of newer version // Change owner meta["x-amz-meta-uid"] = str(uid); meta["x-amz-meta-gid"] = str(gid); // open & load FdEntity* ent; if(NULL == (ent = get_local_fent(strpath.c_str(), true))){ S3FS_PRN_ERR("could not open and read file(%s)", strpath.c_str()); return -EIO; } // upload if(0 != (result = ent->Flush(meta, true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", strpath.c_str(), result); FdManager::get()->Close(ent); return result; } FdManager::get()->Close(ent); StatCache::getStatCacheData()->DelStat(nowcache); } S3FS_MALLOCTRIM(0); return result; } static int s3fs_utimens(const char* path, const struct timespec ts[2]) { int result; string strpath; string newpath; string nowcache; headers_t meta; struct stat stbuf; int nDirType = DIRTYPE_UNKNOWN; S3FS_PRN_INFO("[path=%s][mtime=%jd]", path, (intmax_t)(ts[1].tv_sec)); if(0 == strcmp(path, "/")){ S3FS_PRN_ERR("Could not change mtime for maount point."); return -EIO; } if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } if(0 != (result = check_object_access(path, W_OK, &stbuf))){ if(0 != check_object_owner(path, &stbuf)){ return result; } } if(S_ISDIR(stbuf.st_mode)){ result = chk_dir_object_type(path, newpath, strpath, nowcache, &meta, &nDirType); }else{ strpath = path; nowcache = strpath; result = get_object_attribute(strpath.c_str(), NULL, &meta); } if(0 != result){ return result; } if(S_ISDIR(stbuf.st_mode) && IS_REPLACEDIR(nDirType)){ // Should rebuild directory object(except new type) // Need to remove old dir("dir" etc) and make new dir("dir/") // At first, remove directory old object if(IS_RMTYPEDIR(nDirType)){ S3fsCurl s3fscurl; if(0 != (result = s3fscurl.DeleteRequest(strpath.c_str()))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") if(0 != (result = create_directory_object(newpath.c_str(), stbuf.st_mode, ts[1].tv_sec, stbuf.st_uid, stbuf.st_gid))){ return result; } }else{ meta["x-amz-meta-mtime"] = str(ts[1].tv_sec); meta["x-amz-copy-source"] = urlEncode(service_path + bucket + get_realpath(strpath.c_str())); meta["x-amz-metadata-directive"] = "REPLACE"; if(put_headers(strpath.c_str(), meta, true) != 0){ return -EIO; } StatCache::getStatCacheData()->DelStat(nowcache); } S3FS_MALLOCTRIM(0); return 0; } static int s3fs_utimens_nocopy(const char* path, const struct timespec ts[2]) { int result; string strpath; string newpath; string nowcache; headers_t meta; struct stat stbuf; int nDirType = DIRTYPE_UNKNOWN; S3FS_PRN_INFO1("[path=%s][mtime=%s]", path, str(ts[1].tv_sec).c_str()); if(0 == strcmp(path, "/")){ S3FS_PRN_ERR("Could not change mtime for mount point."); return -EIO; } if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } if(0 != (result = check_object_access(path, W_OK, &stbuf))){ if(0 != check_object_owner(path, &stbuf)){ return result; } } // Get attributes if(S_ISDIR(stbuf.st_mode)){ result = chk_dir_object_type(path, newpath, strpath, nowcache, &meta, &nDirType); }else{ strpath = path; nowcache = strpath; result = get_object_attribute(strpath.c_str(), NULL, &meta); } if(0 != result){ return result; } if(S_ISDIR(stbuf.st_mode)){ // Should rebuild all directory object // Need to remove old dir("dir" etc) and make new dir("dir/") // At first, remove directory old object if(IS_RMTYPEDIR(nDirType)){ S3fsCurl s3fscurl; if(0 != (result = s3fscurl.DeleteRequest(strpath.c_str()))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") if(0 != (result = create_directory_object(newpath.c_str(), stbuf.st_mode, ts[1].tv_sec, stbuf.st_uid, stbuf.st_gid))){ return result; } }else{ // normal object or directory object of newer version // Change date meta["x-amz-meta-mtime"] = str(ts[1].tv_sec); // open & load FdEntity* ent; if(NULL == (ent = get_local_fent(strpath.c_str(), true))){ S3FS_PRN_ERR("could not open and read file(%s)", strpath.c_str()); return -EIO; } // set mtime if(0 != (result = ent->SetMtime(ts[1].tv_sec))){ S3FS_PRN_ERR("could not set mtime to file(%s): result=%d", strpath.c_str(), result); FdManager::get()->Close(ent); return result; } // upload if(0 != (result = ent->Flush(meta, true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", strpath.c_str(), result); FdManager::get()->Close(ent); return result; } FdManager::get()->Close(ent); StatCache::getStatCacheData()->DelStat(nowcache); } S3FS_MALLOCTRIM(0); return result; } static int s3fs_truncate(const char* path, off_t size) { int result; headers_t meta; FdEntity* ent = NULL; S3FS_PRN_INFO("[path=%s][size=%jd]", path, (intmax_t)size); if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } if(0 != (result = check_object_access(path, W_OK, NULL))){ return result; } // Get file information if(0 == (result = get_object_attribute(path, NULL, &meta))){ // Exists -> Get file(with size) if(NULL == (ent = FdManager::get()->Open(path, size, -1, false, true))){ S3FS_PRN_ERR("could not open file(%s): errno=%d", path, errno); return -EIO; } if(0 != (result = ent->Load(0, size))){ S3FS_PRN_ERR("could not download file(%s): result=%d", path, result); FdManager::get()->Close(ent); return result; } }else{ // Not found -> Make tmpfile(with size) if(NULL == (ent = FdManager::get()->Open(path, size, -1, true, true))){ S3FS_PRN_ERR("could not open file(%s): errno=%d", path, errno); return -EIO; } } // upload if(0 != (result = ent->Flush(meta, true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", path, result); FdManager::get()->Close(ent); return result; } FdManager::get()->Close(ent); StatCache::getStatCacheData()->DelStat(path); S3FS_MALLOCTRIM(0); return result; } static int s3fs_open(const char* path, struct fuse_file_info* fi) { int result; struct stat st; S3FS_PRN_INFO("[path=%s][flags=%d]", path, fi->flags); // clear stat for reading fresh stat. // (if object stat is changed, we refresh it. then s3fs gets always // stat when s3fs open the object). StatCache::getStatCacheData()->DelStat(path); int mask = (O_RDONLY != (fi->flags & O_ACCMODE) ? W_OK : R_OK); if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } result = check_object_access(path, mask, &st); if(-ENOENT == result){ if(0 != (result = check_parent_object_access(path, W_OK))){ return result; } }else if(0 != result){ return result; } if((unsigned int)fi->flags & O_TRUNC){ st.st_size = 0; } if(!S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)){ st.st_mtime = -1; } FdEntity* ent; if(NULL == (ent = FdManager::get()->Open(path, st.st_size, st.st_mtime, false, true))){ return -EIO; } fi->fh = ent->GetFd(); S3FS_MALLOCTRIM(0); return 0; } static int s3fs_read(const char* path, char* buf, size_t size, off_t offset, struct fuse_file_info* fi) { ssize_t res; S3FS_PRN_DBG("[path=%s][size=%zu][offset=%jd][fd=%llu]", path, size, (intmax_t)offset, (unsigned long long)(fi->fh)); FdEntity* ent; if(NULL == (ent = FdManager::get()->ExistOpen(path, static_cast(fi->fh)))){ S3FS_PRN_ERR("could not find opened fd(%s)", path); return -EIO; } if(ent->GetFd() != static_cast(fi->fh)){ S3FS_PRN_WARN("different fd(%d - %llu)", ent->GetFd(), (unsigned long long)(fi->fh)); } // check real file size off_t realsize = 0; if(!ent->GetSize(realsize) || 0 >= realsize){ S3FS_PRN_ERR("file size is 0, so break to read."); FdManager::get()->Close(ent); return 0; } if(0 > (res = ent->Read(buf, offset, size, false))){ S3FS_PRN_WARN("failed to read file(%s). result=%zd", path, res); } FdManager::get()->Close(ent); return static_cast(res); } static int s3fs_write(const char* path, const char* buf, size_t size, off_t offset, struct fuse_file_info* fi) { ssize_t res; S3FS_PRN_DBG("[path=%s][size=%zu][offset=%jd][fd=%llu]", path, size, (intmax_t)offset, (unsigned long long)(fi->fh)); FdEntity* ent; if(NULL == (ent = FdManager::get()->ExistOpen(path, static_cast(fi->fh)))){ S3FS_PRN_ERR("could not find opened fd(%s)", path); return -EIO; } if(ent->GetFd() != static_cast(fi->fh)){ S3FS_PRN_WARN("different fd(%d - %llu)", ent->GetFd(), (unsigned long long)(fi->fh)); } if(0 > (res = ent->Write(buf, offset, size))){ S3FS_PRN_WARN("failed to write file(%s). result=%zd", path, res); } FdManager::get()->Close(ent); return static_cast(res); } static int s3fs_statfs(const char* path, struct statvfs* stbuf) { // 256T stbuf->f_bsize = 0X1000000; stbuf->f_blocks = 0X1000000; stbuf->f_bfree = 0x1000000; stbuf->f_bavail = 0x1000000; stbuf->f_namemax = NAME_MAX; return 0; } static int s3fs_flush(const char* path, struct fuse_file_info* fi) { int result; S3FS_PRN_INFO("[path=%s][fd=%llu]", path, (unsigned long long)(fi->fh)); int mask = (O_RDONLY != (fi->flags & O_ACCMODE) ? W_OK : R_OK); if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } result = check_object_access(path, mask, NULL); if(-ENOENT == result){ if(0 != (result = check_parent_object_access(path, W_OK))){ return result; } }else if(0 != result){ return result; } FdEntity* ent; if(NULL != (ent = FdManager::get()->ExistOpen(path, static_cast(fi->fh)))){ headers_t meta; if(0 != (result = get_object_attribute(path, NULL, &meta))){ FdManager::get()->Close(ent); return result; } // If both mtime are not same, force to change mtime based on fd. time_t ent_mtime; if(ent->GetMtime(ent_mtime)){ if(str(ent_mtime) != meta["x-amz-meta-mtime"]){ meta["x-amz-meta-mtime"] = str(ent_mtime); } } result = ent->Flush(meta, false); FdManager::get()->Close(ent); } S3FS_MALLOCTRIM(0); return result; } // [NOTICE] // Assumption is a valid fd. // static int s3fs_fsync(const char* path, int datasync, struct fuse_file_info* fi) { int result = 0; S3FS_PRN_INFO("[path=%s][fd=%llu]", path, (unsigned long long)(fi->fh)); FdEntity* ent; if(NULL != (ent = FdManager::get()->ExistOpen(path, static_cast(fi->fh)))){ headers_t meta; if(0 != (result = get_object_attribute(path, NULL, &meta))){ FdManager::get()->Close(ent); return result; } // If datasync is not zero, only flush data without meta updating. time_t ent_mtime; if(ent->GetMtime(ent_mtime)){ if(0 == datasync && str(ent_mtime) != meta["x-amz-meta-mtime"]){ meta["x-amz-meta-mtime"] = str(ent_mtime); } } result = ent->Flush(meta, false); FdManager::get()->Close(ent); } S3FS_MALLOCTRIM(0); return result; } static int s3fs_release(const char* path, struct fuse_file_info* fi) { S3FS_PRN_INFO("[path=%s][fd=%llu]", path, (unsigned long long)(fi->fh)); // [NOTICE] // At first, we remove stats cache. // Because fuse does not wait for response from "release" function. :-( // And fuse runs next command before this function returns. // Thus we call deleting stats function ASSAP. // if((fi->flags & O_RDWR) || (fi->flags & O_WRONLY)){ StatCache::getStatCacheData()->DelStat(path); } FdEntity* ent; if(NULL == (ent = FdManager::get()->GetFdEntity(path, static_cast(fi->fh)))){ S3FS_PRN_ERR("could not find fd(file=%s)", path); return -EIO; } if(ent->GetFd() != static_cast(fi->fh)){ S3FS_PRN_WARN("different fd(%d - %llu)", ent->GetFd(), (unsigned long long)(fi->fh)); } FdManager::get()->Close(ent); // check - for debug if(IS_S3FS_LOG_DBG()){ if(NULL != (ent = FdManager::get()->GetFdEntity(path, static_cast(fi->fh)))){ S3FS_PRN_WARN("file(%s),fd(%d) is still opened.", path, ent->GetFd()); } } S3FS_MALLOCTRIM(0); return 0; } static int s3fs_opendir(const char* path, struct fuse_file_info* fi) { int result; int mask = (O_RDONLY != (fi->flags & O_ACCMODE) ? W_OK : R_OK) | X_OK; S3FS_PRN_INFO("[path=%s][flags=%d]", path, fi->flags); if(0 == (result = check_object_access(path, mask, NULL))){ result = check_parent_object_access(path, mask); } S3FS_MALLOCTRIM(0); return result; } static bool multi_head_callback(S3fsCurl* s3fscurl) { if(!s3fscurl){ return false; } string saved_path = s3fscurl->GetSpacialSavedPath(); if(!StatCache::getStatCacheData()->AddStat(saved_path, *(s3fscurl->GetResponseHeaders()))){ S3FS_PRN_ERR("failed adding stat cache [path=%s]", saved_path.c_str()); return false; } return true; } static S3fsCurl* multi_head_retry_callback(S3fsCurl* s3fscurl) { if(!s3fscurl){ return NULL; } int ssec_key_pos= s3fscurl->GetLastPreHeadSeecKeyPos(); int retry_count = s3fscurl->GetMultipartRetryCount(); // retry next sse key. // if end of sse key, set retry master count is up. ssec_key_pos = (ssec_key_pos < 0 ? 0 : ssec_key_pos + 1); if(0 == S3fsCurl::GetSseKeyCount() || S3fsCurl::GetSseKeyCount() <= ssec_key_pos){ if(s3fscurl->IsOverMultipartRetryCount()){ S3FS_PRN_ERR("Over retry count(%d) limit(%s).", s3fscurl->GetMultipartRetryCount(), s3fscurl->GetSpacialSavedPath().c_str()); return NULL; } ssec_key_pos= -1; retry_count++; } S3fsCurl* newcurl = new S3fsCurl(s3fscurl->IsUseAhbe()); string path = s3fscurl->GetPath(); string base_path = s3fscurl->GetBasePath(); string saved_path = s3fscurl->GetSpacialSavedPath(); if(!newcurl->PreHeadRequest(path, base_path, saved_path, ssec_key_pos)){ S3FS_PRN_ERR("Could not duplicate curl object(%s).", saved_path.c_str()); delete newcurl; return NULL; } newcurl->SetMultipartRetryCount(retry_count); return newcurl; } static int readdir_multi_head(const char* path, S3ObjList& head, void* buf, fuse_fill_dir_t filler) { S3fsMultiCurl curlmulti; s3obj_list_t headlist; s3obj_list_t fillerlist; int result = 0; S3FS_PRN_INFO1("[path=%s][list=%zu]", path, headlist.size()); // Make base path list. head.GetNameList(headlist, true, false); // get name with "/". // Initialize S3fsMultiCurl curlmulti.SetSuccessCallback(multi_head_callback); curlmulti.SetRetryCallback(multi_head_retry_callback); // Loop while(!headlist.empty()){ s3obj_list_t::iterator iter; long cnt; fillerlist.clear(); // Make single head request(with max). for(iter = headlist.begin(), cnt = 0; headlist.end() != iter && cnt < S3fsMultiCurl::GetMaxMultiRequest(); iter = headlist.erase(iter)){ string disppath = path + (*iter); string etag = head.GetETag((*iter).c_str()); string fillpath = disppath; if('/' == disppath[disppath.length() - 1]){ fillpath = fillpath.substr(0, fillpath.length() -1); } fillerlist.push_back(fillpath); if(StatCache::getStatCacheData()->HasStat(disppath, etag.c_str())){ continue; } // First check for directory, start checking "not SSE-C". // If checking failed, retry to check with "SSE-C" by retry callback func when SSE-C mode. S3fsCurl* s3fscurl = new S3fsCurl(); if(!s3fscurl->PreHeadRequest(disppath, (*iter), disppath)){ // target path = cache key path.(ex "dir/") S3FS_PRN_WARN("Could not make curl object for head request(%s).", disppath.c_str()); delete s3fscurl; continue; } if(!curlmulti.SetS3fsCurlObject(s3fscurl)){ S3FS_PRN_WARN("Could not make curl object into multi curl(%s).", disppath.c_str()); delete s3fscurl; continue; } cnt++; // max request count within S3fsMultiCurl::GetMaxMultiRequest() } // Multi request if(0 != (result = curlmulti.Request())){ // If result is -EIO, it is somthing error occurred. // This case includes that the object is encrypting(SSE) and s3fs does not have keys. // So s3fs set result to 0 in order to continue the process. if(-EIO == result){ S3FS_PRN_WARN("error occuered in multi request(errno=%d), but continue...", result); result = 0; }else{ S3FS_PRN_ERR("error occuered in multi request(errno=%d).", result); break; } } // populate fuse buffer // here is best posision, because a case is cache size < files in directory // for(iter = fillerlist.begin(); fillerlist.end() != iter; ++iter){ struct stat st; string bpath = mybasename((*iter)); if(StatCache::getStatCacheData()->GetStat((*iter), &st)){ filler(buf, bpath.c_str(), &st, 0); }else{ S3FS_PRN_INFO2("Could not find %s file in stat cache.", (*iter).c_str()); filler(buf, bpath.c_str(), 0, 0); } } // reinit for loop. curlmulti.Clear(); } return result; } static int s3fs_readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fi) { S3ObjList head; int result; S3FS_PRN_INFO("[path=%s]", path); if(0 != (result = check_object_access(path, X_OK, NULL))){ return result; } // get a list of all the objects if((result = list_bucket(path, head, "/")) != 0){ S3FS_PRN_ERR("list_bucket returns error(%d).", result); return result; } // force to add "." and ".." name. filler(buf, ".", 0, 0); filler(buf, "..", 0, 0); if(head.IsEmpty()){ return 0; } // Send multi head request for stats caching. string strpath = path; if(strcmp(path, "/") != 0){ strpath += "/"; } if(0 != (result = readdir_multi_head(strpath.c_str(), head, buf, filler))){ S3FS_PRN_ERR("readdir_multi_head returns error(%d).", result); } S3FS_MALLOCTRIM(0); return result; } static int list_bucket(const char* path, S3ObjList& head, const char* delimiter, bool check_content_only) { int result; string s3_realpath; string query_delimiter;; string query_prefix;; string query_maxkey;; string next_marker = ""; bool truncated = true; S3fsCurl s3fscurl; xmlDocPtr doc; BodyData* body; S3FS_PRN_INFO1("[path=%s]", path); if(delimiter && 0 < strlen(delimiter)){ query_delimiter += "delimiter="; query_delimiter += delimiter; query_delimiter += "&"; } query_prefix += "&prefix="; s3_realpath = get_realpath(path); if(0 == s3_realpath.length() || '/' != s3_realpath[s3_realpath.length() - 1]){ // last word must be "/" query_prefix += urlEncode(s3_realpath.substr(1) + "/"); }else{ query_prefix += urlEncode(s3_realpath.substr(1)); } if (check_content_only){ query_maxkey += "max-keys=1"; }else{ query_maxkey += "max-keys=1000"; } while(truncated){ string each_query = query_delimiter; if(next_marker != ""){ each_query += "marker=" + urlEncode(next_marker) + "&"; next_marker = ""; } each_query += query_maxkey; each_query += query_prefix; // request if(0 != (result = s3fscurl.ListBucketRequest(path, each_query.c_str()))){ S3FS_PRN_ERR("ListBucketRequest returns with error."); return result; } body = s3fscurl.GetBodyData(); // xmlDocPtr if(NULL == (doc = xmlReadMemory(body->str(), static_cast(body->size()), "", NULL, 0))){ S3FS_PRN_ERR("xmlReadMemory returns with error."); return -1; } if(0 != append_objects_from_xml(path, doc, head)){ S3FS_PRN_ERR("append_objects_from_xml returns with error."); xmlFreeDoc(doc); return -1; } if(true == (truncated = is_truncated(doc))){ xmlChar* tmpch = get_next_marker(doc); if(tmpch){ next_marker = (char*)tmpch; xmlFree(tmpch); }else{ // If did not specify "delimiter", s3 did not return "NextMarker". // On this case, can use lastest name for next marker. // string lastname; if(!head.GetLastName(lastname)){ S3FS_PRN_WARN("Could not find next marker, thus break loop."); truncated = false; }else{ next_marker = s3_realpath.substr(1); if(0 == s3_realpath.length() || '/' != s3_realpath[s3_realpath.length() - 1]){ next_marker += "/"; } next_marker += lastname; } } } S3FS_XMLFREEDOC(doc); // reset(initialize) curl object s3fscurl.DestroyCurlHandle(); if (check_content_only) break; } S3FS_MALLOCTRIM(0); return 0; } const char* c_strErrorObjectName = "FILE or SUBDIR in DIR"; static int append_objects_from_xml_ex(const char* path, xmlDocPtr doc, xmlXPathContextPtr ctx, const char* ex_contents, const char* ex_key, const char* ex_etag, int isCPrefix, S3ObjList& head) { xmlXPathObjectPtr contents_xp; xmlNodeSetPtr content_nodes; if(NULL == (contents_xp = xmlXPathEvalExpression((xmlChar*)ex_contents, ctx))){ S3FS_PRN_ERR("xmlXPathEvalExpression returns null."); return -1; } if(xmlXPathNodeSetIsEmpty(contents_xp->nodesetval)){ S3FS_PRN_ERR("contents_xp->nodesetval is empty."); S3FS_XMLXPATHFREEOBJECT(contents_xp); return 0; } content_nodes = contents_xp->nodesetval; bool is_dir; string stretag; int i; for(i = 0; i < content_nodes->nodeNr; i++){ ctx->node = content_nodes->nodeTab[i]; // object name xmlXPathObjectPtr key; if(NULL == (key = xmlXPathEvalExpression((xmlChar*)ex_key, ctx))){ S3FS_PRN_WARN("key is null. but continue."); continue; } if(xmlXPathNodeSetIsEmpty(key->nodesetval)){ S3FS_PRN_WARN("node is empty. but continue."); xmlXPathFreeObject(key); continue; } xmlNodeSetPtr key_nodes = key->nodesetval; char* name = get_object_name(doc, key_nodes->nodeTab[0]->xmlChildrenNode, path); if(!name){ S3FS_PRN_WARN("name is something wrong. but continue."); }else if((const char*)name != c_strErrorObjectName){ is_dir = isCPrefix ? true : false; stretag = ""; if(!isCPrefix && ex_etag){ // Get ETag xmlXPathObjectPtr ETag; if(NULL != (ETag = xmlXPathEvalExpression((xmlChar*)ex_etag, ctx))){ if(xmlXPathNodeSetIsEmpty(ETag->nodesetval)){ S3FS_PRN_INFO("ETag->nodesetval is empty."); }else{ xmlNodeSetPtr etag_nodes = ETag->nodesetval; xmlChar* petag = xmlNodeListGetString(doc, etag_nodes->nodeTab[0]->xmlChildrenNode, 1); if(petag){ stretag = (char*)petag; xmlFree(petag); } } xmlXPathFreeObject(ETag); } } if(!head.insert(name, (0 < stretag.length() ? stretag.c_str() : NULL), is_dir)){ S3FS_PRN_ERR("insert_object returns with error."); xmlXPathFreeObject(key); xmlXPathFreeObject(contents_xp); free(name); S3FS_MALLOCTRIM(0); return -1; } free(name); }else{ S3FS_PRN_WARN("name is file or subdir in dir. but continue."); } xmlXPathFreeObject(key); } S3FS_XMLXPATHFREEOBJECT(contents_xp); return 0; } static bool GetXmlNsUrl(xmlDocPtr doc, string& nsurl) { static time_t tmLast = 0; // cache for 60 sec. static string strNs(""); bool result = false; if(!doc){ return result; } if((tmLast + 60) < time(NULL)){ // refresh tmLast = time(NULL); strNs = ""; xmlNodePtr pRootNode = xmlDocGetRootElement(doc); if(pRootNode){ xmlNsPtr* nslist = xmlGetNsList(doc, pRootNode); if(nslist){ if(nslist[0] && nslist[0]->href){ strNs = (const char*)(nslist[0]->href); } S3FS_XMLFREE(nslist); } } } if(0 < strNs.size()){ nsurl = strNs; result = true; } return result; } static int append_objects_from_xml(const char* path, xmlDocPtr doc, S3ObjList& head) { string xmlnsurl; string ex_contents = "//"; string ex_key = ""; string ex_cprefix = "//"; string ex_prefix = ""; string ex_etag = ""; if(!doc){ return -1; } // If there is not , use path instead of it. xmlChar* pprefix = get_prefix(doc); string prefix = (pprefix ? (char*)pprefix : path ? path : ""); if(pprefix){ xmlFree(pprefix); } xmlXPathContextPtr ctx = xmlXPathNewContext(doc); if(!noxmlns && GetXmlNsUrl(doc, xmlnsurl)){ xmlXPathRegisterNs(ctx, (xmlChar*)"s3", (xmlChar*)xmlnsurl.c_str()); ex_contents+= "s3:"; ex_key += "s3:"; ex_cprefix += "s3:"; ex_prefix += "s3:"; ex_etag += "s3:"; } ex_contents+= "Contents"; ex_key += "Key"; ex_cprefix += "CommonPrefixes"; ex_prefix += "Prefix"; ex_etag += "ETag"; if(-1 == append_objects_from_xml_ex(prefix.c_str(), doc, ctx, ex_contents.c_str(), ex_key.c_str(), ex_etag.c_str(), 0, head) || -1 == append_objects_from_xml_ex(prefix.c_str(), doc, ctx, ex_cprefix.c_str(), ex_prefix.c_str(), NULL, 1, head) ) { S3FS_PRN_ERR("append_objects_from_xml_ex returns with error."); S3FS_XMLXPATHFREECONTEXT(ctx); return -1; } S3FS_XMLXPATHFREECONTEXT(ctx); return 0; } static xmlChar* get_base_exp(xmlDocPtr doc, const char* exp) { xmlXPathObjectPtr marker_xp; string xmlnsurl; string exp_string = "//"; if(!doc){ return NULL; } xmlXPathContextPtr ctx = xmlXPathNewContext(doc); if(!noxmlns && GetXmlNsUrl(doc, xmlnsurl)){ xmlXPathRegisterNs(ctx, (xmlChar*)"s3", (xmlChar*)xmlnsurl.c_str()); exp_string += "s3:"; } exp_string += exp; if(NULL == (marker_xp = xmlXPathEvalExpression((xmlChar *)exp_string.c_str(), ctx))){ xmlXPathFreeContext(ctx); return NULL; } if(xmlXPathNodeSetIsEmpty(marker_xp->nodesetval)){ S3FS_PRN_ERR("marker_xp->nodesetval is empty."); xmlXPathFreeObject(marker_xp); xmlXPathFreeContext(ctx); return NULL; } xmlNodeSetPtr nodes = marker_xp->nodesetval; xmlChar* result = xmlNodeListGetString(doc, nodes->nodeTab[0]->xmlChildrenNode, 1); xmlXPathFreeObject(marker_xp); xmlXPathFreeContext(ctx); return result; } static xmlChar* get_prefix(xmlDocPtr doc) { return get_base_exp(doc, "Prefix"); } static xmlChar* get_next_marker(xmlDocPtr doc) { return get_base_exp(doc, "NextMarker"); } static bool is_truncated(xmlDocPtr doc) { bool result = false; xmlChar* strTruncate = get_base_exp(doc, "IsTruncated"); if(!strTruncate){ return result; } if(0 == strcasecmp((const char*)strTruncate, "true")){ result = true; } xmlFree(strTruncate); return result; } // return: the pointer to object name on allocated memory. // the pointer to "c_strErrorObjectName".(not allocated) // NULL(a case of something error occurred) static char* get_object_name(xmlDocPtr doc, xmlNodePtr node, const char* path) { // Get full path xmlChar* fullpath = xmlNodeListGetString(doc, node, 1); if(!fullpath){ S3FS_PRN_ERR("could not get object full path name.."); return NULL; } // basepath(path) is as same as fullpath. if(0 == strcmp((char*)fullpath, path)){ xmlFree(fullpath); return (char*)c_strErrorObjectName; } // Make dir path and filename string strdirpath = mydirname(string((char*)fullpath)); string strmybpath = mybasename(string((char*)fullpath)); const char* dirpath = strdirpath.c_str(); const char* mybname = strmybpath.c_str(); const char* basepath= (!path || '\0' == path[0] || '/' != path[0] ? path : &path[1]); xmlFree(fullpath); if(!mybname || '\0' == mybname[0]){ return NULL; } // check subdir & file in subdir if(dirpath && 0 < strlen(dirpath)){ // case of "/" if(0 == strcmp(mybname, "/") && 0 == strcmp(dirpath, "/")){ return (char*)c_strErrorObjectName; } // case of "." if(0 == strcmp(mybname, ".") && 0 == strcmp(dirpath, ".")){ return (char*)c_strErrorObjectName; } // case of ".." if(0 == strcmp(mybname, "..") && 0 == strcmp(dirpath, ".")){ return (char*)c_strErrorObjectName; } // case of "name" if(0 == strcmp(dirpath, ".")){ // OK return strdup(mybname); }else{ if(basepath && 0 == strcmp(dirpath, basepath)){ // OK return strdup(mybname); }else if(basepath && 0 < strlen(basepath) && '/' == basepath[strlen(basepath) - 1] && 0 == strncmp(dirpath, basepath, strlen(basepath) - 1)){ string withdirname = ""; if(strlen(dirpath) > strlen(basepath)){ withdirname = &dirpath[strlen(basepath)]; } if(0 < withdirname.length() && '/' != withdirname[withdirname.length() - 1]){ withdirname += "/"; } withdirname += mybname; return strdup(withdirname.c_str()); } } } // case of something wrong return (char*)c_strErrorObjectName; } static int remote_mountpath_exists(const char* path) { struct stat stbuf; S3FS_PRN_INFO1("[path=%s]", path); // getattr will prefix the path with the remote mountpoint if(0 != get_object_attribute("/", &stbuf, NULL)){ return -1; } if(!S_ISDIR(stbuf.st_mode)){ return -1; } return 0; } static void free_xattrs(xattrs_t& xattrs) { for(xattrs_t::iterator iter = xattrs.begin(); iter != xattrs.end(); xattrs.erase(iter++)){ if(iter->second){ delete iter->second; } } } static bool parse_xattr_keyval(const std::string& xattrpair, string& key, PXATTRVAL& pval) { // parse key and value size_t pos; string tmpval; if(string::npos == (pos = xattrpair.find_first_of(":"))){ S3FS_PRN_ERR("one of xattr pair(%s) is wrong format.", xattrpair.c_str()); return false; } key = xattrpair.substr(0, pos); tmpval = xattrpair.substr(pos + 1); if(!takeout_str_dquart(key) || !takeout_str_dquart(tmpval)){ S3FS_PRN_ERR("one of xattr pair(%s) is wrong format.", xattrpair.c_str()); return false; } pval = new XATTRVAL; pval->length = 0; pval->pvalue = s3fs_decode64(tmpval.c_str(), &pval->length); return true; } static size_t parse_xattrs(const std::string& strxattrs, xattrs_t& xattrs) { xattrs.clear(); // decode string jsonxattrs = urlDecode(strxattrs); // get from "{" to "}" string restxattrs; { size_t startpos = string::npos; size_t endpos = string::npos; if(string::npos != (startpos = jsonxattrs.find_first_of("{"))){ endpos = jsonxattrs.find_last_of("}"); } if(startpos == string::npos || endpos == string::npos || endpos <= startpos){ S3FS_PRN_WARN("xattr header(%s) is not json format.", jsonxattrs.c_str()); return 0; } restxattrs = jsonxattrs.substr(startpos + 1, endpos - (startpos + 1)); } // parse each key:val for(size_t pair_nextpos = restxattrs.find_first_of(","); 0 < restxattrs.length(); restxattrs = (pair_nextpos != string::npos ? restxattrs.substr(pair_nextpos + 1) : string("")), pair_nextpos = restxattrs.find_first_of(",")){ string pair = pair_nextpos != string::npos ? restxattrs.substr(0, pair_nextpos) : restxattrs; string key = ""; PXATTRVAL pval = NULL; if(!parse_xattr_keyval(pair, key, pval)){ // something format error, so skip this. continue; } xattrs[key] = pval; } return xattrs.size(); } static std::string build_xattrs(const xattrs_t& xattrs) { string strxattrs("{"); bool is_set = false; for(xattrs_t::const_iterator iter = xattrs.begin(); iter != xattrs.end(); ++iter){ if(is_set){ strxattrs += ','; }else{ is_set = true; } strxattrs += '\"'; strxattrs += iter->first; strxattrs += "\":\""; if(iter->second){ char* base64val = s3fs_base64((iter->second)->pvalue, (iter->second)->length); if(base64val){ strxattrs += base64val; free(base64val); } } strxattrs += '\"'; } strxattrs += '}'; strxattrs = urlEncode(strxattrs); return strxattrs; } static int set_xattrs_to_header(headers_t& meta, const char* name, const char* value, size_t size, int flags) { string strxattrs; xattrs_t xattrs; headers_t::iterator iter; if(meta.end() == (iter = meta.find("x-amz-meta-xattr"))){ if(XATTR_REPLACE == (flags & XATTR_REPLACE)){ // there is no xattr header but flags is replace, so failure. return -ENOATTR; } }else{ if(XATTR_CREATE == (flags & XATTR_CREATE)){ // found xattr header but flags is only creating, so failure. return -EEXIST; } strxattrs = iter->second; } // get map as xattrs_t parse_xattrs(strxattrs, xattrs); // add name(do not care overwrite and empty name/value) xattrs_t::iterator xiter; if(xattrs.end() != (xiter = xattrs.find(string(name)))){ // found same head. free value. delete xiter->second; } PXATTRVAL pval = new XATTRVAL; pval->length = size; if(0 < size){ if(NULL == (pval->pvalue = (unsigned char*)malloc(size))){ delete pval; free_xattrs(xattrs); return -ENOMEM; } memcpy(pval->pvalue, value, size); }else{ pval->pvalue = NULL; } xattrs[string(name)] = pval; // build new strxattrs(not encoded) and set it to headers_t meta["x-amz-meta-xattr"] = build_xattrs(xattrs); free_xattrs(xattrs); return 0; } #if defined(__APPLE__) static int s3fs_setxattr(const char* path, const char* name, const char* value, size_t size, int flags, uint32_t position) #else static int s3fs_setxattr(const char* path, const char* name, const char* value, size_t size, int flags) #endif { S3FS_PRN_INFO("[path=%s][name=%s][value=%p][size=%zu][flags=%d]", path, name, value, size, flags); if((value && 0 == size) || (!value && 0 < size)){ S3FS_PRN_ERR("Wrong parameter: value(%p), size(%zu)", value, size); return 0; } #if defined(__APPLE__) if (position != 0) { // No resource fork support return -EINVAL; } #endif int result; string strpath; string newpath; string nowcache; headers_t meta; struct stat stbuf; int nDirType = DIRTYPE_UNKNOWN; if(0 == strcmp(path, "/")){ S3FS_PRN_ERR("Could not change mode for mount point."); return -EIO; } if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } if(0 != (result = check_object_owner(path, &stbuf))){ return result; } if(S_ISDIR(stbuf.st_mode)){ result = chk_dir_object_type(path, newpath, strpath, nowcache, &meta, &nDirType); }else{ strpath = path; nowcache = strpath; result = get_object_attribute(strpath.c_str(), NULL, &meta); } if(0 != result){ return result; } // make new header_t if(0 != (result = set_xattrs_to_header(meta, name, value, size, flags))){ return result; } if(S_ISDIR(stbuf.st_mode) && IS_REPLACEDIR(nDirType)){ // Should rebuild directory object(except new type) // Need to remove old dir("dir" etc) and make new dir("dir/") // At first, remove directory old object if(IS_RMTYPEDIR(nDirType)){ S3fsCurl s3fscurl; if(0 != (result = s3fscurl.DeleteRequest(strpath.c_str()))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") if(0 != (result = create_directory_object(newpath.c_str(), stbuf.st_mode, stbuf.st_mtime, stbuf.st_uid, stbuf.st_gid))){ return result; } // need to set xattr header for directory. strpath = newpath; nowcache = strpath; } // set xattr all object meta["x-amz-copy-source"] = urlEncode(service_path + bucket + get_realpath(strpath.c_str())); meta["x-amz-metadata-directive"] = "REPLACE"; if(0 != put_headers(strpath.c_str(), meta, true)){ return -EIO; } StatCache::getStatCacheData()->DelStat(nowcache); return 0; } #if defined(__APPLE__) static int s3fs_getxattr(const char* path, const char* name, char* value, size_t size, uint32_t position) #else static int s3fs_getxattr(const char* path, const char* name, char* value, size_t size) #endif { S3FS_PRN_INFO("[path=%s][name=%s][value=%p][size=%zu]", path, name, value, size); if(!path || !name){ return -EIO; } #if (__APPLE__) if (position != 0) { // No resource fork support return -EINVAL; } #endif int result; headers_t meta; xattrs_t xattrs; // check parent directory attribute. if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } // get headders if(0 != (result = get_object_attribute(path, NULL, &meta))){ return result; } // get xattrs headers_t::iterator hiter = meta.find("x-amz-meta-xattr"); if(meta.end() == hiter){ // object does not have xattrs return -ENOATTR; } string strxattrs = hiter->second; parse_xattrs(strxattrs, xattrs); // search name string strname = name; xattrs_t::iterator xiter = xattrs.find(strname); if(xattrs.end() == xiter){ // not found name in xattrs free_xattrs(xattrs); return -ENOATTR; } // decode size_t length = 0; unsigned char* pvalue = NULL; if(NULL != xiter->second){ length = xiter->second->length; pvalue = xiter->second->pvalue; } if(0 < size){ if(static_cast(size) < length){ // over buffer size free_xattrs(xattrs); return -ERANGE; } if(pvalue){ memcpy(value, pvalue, length); } } free_xattrs(xattrs); return static_cast(length); } static int s3fs_listxattr(const char* path, char* list, size_t size) { S3FS_PRN_INFO("[path=%s][list=%p][size=%zu]", path, list, size); if(!path){ return -EIO; } int result; headers_t meta; xattrs_t xattrs; // check parent directory attribute. if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } // get headders if(0 != (result = get_object_attribute(path, NULL, &meta))){ return result; } // get xattrs headers_t::iterator iter; if(meta.end() == (iter = meta.find("x-amz-meta-xattr"))){ // object does not have xattrs return 0; } string strxattrs = iter->second; parse_xattrs(strxattrs, xattrs); // calculate total name length size_t total = 0; for(xattrs_t::const_iterator iter = xattrs.begin(); iter != xattrs.end(); ++iter){ if(0 < iter->first.length()){ total += iter->first.length() + 1; } } if(0 == total){ free_xattrs(xattrs); return 0; } // check parameters if(size <= 0){ free_xattrs(xattrs); return total; } if(!list || size < total){ free_xattrs(xattrs); return -ERANGE; } // copy to list char* setpos = list; for(xattrs_t::const_iterator iter = xattrs.begin(); iter != xattrs.end(); ++iter){ if(0 < iter->first.length()){ strcpy(setpos, iter->first.c_str()); setpos = &setpos[strlen(setpos) + 1]; } } free_xattrs(xattrs); return total; } static int s3fs_removexattr(const char* path, const char* name) { S3FS_PRN_INFO("[path=%s][name=%s]", path, name); if(!path || !name){ return -EIO; } int result; string strpath; string newpath; string nowcache; headers_t meta; xattrs_t xattrs; struct stat stbuf; int nDirType = DIRTYPE_UNKNOWN; if(0 == strcmp(path, "/")){ S3FS_PRN_ERR("Could not change mode for mount point."); return -EIO; } if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } if(0 != (result = check_object_owner(path, &stbuf))){ return result; } if(S_ISDIR(stbuf.st_mode)){ result = chk_dir_object_type(path, newpath, strpath, nowcache, &meta, &nDirType); }else{ strpath = path; nowcache = strpath; result = get_object_attribute(strpath.c_str(), NULL, &meta); } if(0 != result){ return result; } // get xattrs headers_t::iterator hiter = meta.find("x-amz-meta-xattr"); if(meta.end() == hiter){ // object does not have xattrs return -ENOATTR; } string strxattrs = hiter->second; parse_xattrs(strxattrs, xattrs); // check name xattrs string strname = name; xattrs_t::iterator xiter = xattrs.find(strname); if(xattrs.end() == xiter){ free_xattrs(xattrs); return -ENOATTR; } // make new header_t after deleting name xattr if(xiter->second){ delete xiter->second; } xattrs.erase(xiter); // build new xattr if(!xattrs.empty()){ meta["x-amz-meta-xattr"] = build_xattrs(xattrs); }else{ meta.erase("x-amz-meta-xattr"); } if(S_ISDIR(stbuf.st_mode) && IS_REPLACEDIR(nDirType)){ // Should rebuild directory object(except new type) // Need to remove old dir("dir" etc) and make new dir("dir/") // At first, remove directory old object if(IS_RMTYPEDIR(nDirType)){ S3fsCurl s3fscurl; if(0 != (result = s3fscurl.DeleteRequest(strpath.c_str()))){ free_xattrs(xattrs); return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") if(0 != (result = create_directory_object(newpath.c_str(), stbuf.st_mode, stbuf.st_mtime, stbuf.st_uid, stbuf.st_gid))){ free_xattrs(xattrs); return result; } // need to set xattr header for directory. strpath = newpath; nowcache = strpath; } // set xattr all object meta["x-amz-copy-source"] = urlEncode(service_path + bucket + get_realpath(strpath.c_str())); meta["x-amz-metadata-directive"] = "REPLACE"; if(0 != put_headers(strpath.c_str(), meta, true)){ free_xattrs(xattrs); return -EIO; } StatCache::getStatCacheData()->DelStat(nowcache); free_xattrs(xattrs); return 0; } static void* s3fs_init(struct fuse_conn_info* conn) { S3FS_PRN_CRIT("init v%s(commit:%s) with %s", VERSION, COMMIT_HASH_VAL, s3fs_crypt_lib_name()); // ssl init if(!s3fs_init_global_ssl()){ S3FS_PRN_CRIT("could not initialize for ssl libraries."); exit(EXIT_FAILURE); } // init curl if(!S3fsCurl::InitS3fsCurl("/etc/mime.types")){ S3FS_PRN_CRIT("Could not initiate curl library."); exit(EXIT_FAILURE); } if (create_bucket){ do_create_bucket(); } // Check Bucket // If the network is up, check for valid credentials and if the bucket // exists. skip check if mounting a public bucket if(!S3fsCurl::IsPublicBucket()){ int result; if(EXIT_SUCCESS != (result = s3fs_check_service())){ exit(result); } } // Investigate system capabilities #ifndef __APPLE__ if((unsigned int)conn->capable & FUSE_CAP_ATOMIC_O_TRUNC){ conn->want |= FUSE_CAP_ATOMIC_O_TRUNC; } #endif // cache if(is_remove_cache && !FdManager::DeleteCacheDirectory()){ S3FS_PRN_DBG("Could not inilialize cache directory."); } return NULL; } static void s3fs_destroy(void*) { S3FS_PRN_INFO("destroy"); // Destroy curl if(!S3fsCurl::DestroyS3fsCurl()){ S3FS_PRN_WARN("Could not release curl library."); } // cache if(is_remove_cache && !FdManager::DeleteCacheDirectory()){ S3FS_PRN_WARN("Could not remove cache directory."); } // ssl s3fs_destroy_global_ssl(); } static int s3fs_access(const char* path, int mask) { S3FS_PRN_INFO("[path=%s][mask=%s%s%s%s]", path, ((mask & R_OK) == R_OK) ? "R_OK " : "", ((mask & W_OK) == W_OK) ? "W_OK " : "", ((mask & X_OK) == X_OK) ? "X_OK " : "", (mask == F_OK) ? "F_OK" : ""); int result = check_object_access(path, mask, NULL); S3FS_MALLOCTRIM(0); return result; } static xmlChar* get_exp_value_xml(xmlDocPtr doc, xmlXPathContextPtr ctx, const char* exp_key) { if(!doc || !ctx || !exp_key){ return NULL; } xmlXPathObjectPtr exp; xmlNodeSetPtr exp_nodes; xmlChar* exp_value; // search exp_key tag if(NULL == (exp = xmlXPathEvalExpression((xmlChar*)exp_key, ctx))){ S3FS_PRN_ERR("Could not find key(%s).", exp_key); return NULL; } if(xmlXPathNodeSetIsEmpty(exp->nodesetval)){ S3FS_PRN_ERR("Key(%s) node is empty.", exp_key); S3FS_XMLXPATHFREEOBJECT(exp); return NULL; } // get exp_key value & set in struct exp_nodes = exp->nodesetval; if(NULL == (exp_value = xmlNodeListGetString(doc, exp_nodes->nodeTab[0]->xmlChildrenNode, 1))){ S3FS_PRN_ERR("Key(%s) value is empty.", exp_key); S3FS_XMLXPATHFREEOBJECT(exp); return NULL; } S3FS_XMLXPATHFREEOBJECT(exp); return exp_value; } static void print_uncomp_mp_list(uncomp_mp_list_t& list) { printf("\n"); printf("Lists the parts that have been uploaded for a specific multipart upload.\n"); printf("\n"); if(!list.empty()){ printf("---------------------------------------------------------------\n"); int cnt = 0; for(uncomp_mp_list_t::iterator iter = list.begin(); iter != list.end(); ++iter, ++cnt){ printf(" Path : %s\n", (*iter).key.c_str()); printf(" UploadId : %s\n", (*iter).id.c_str()); printf(" Date : %s\n", (*iter).date.c_str()); printf("\n"); } printf("---------------------------------------------------------------\n"); }else{ printf("There is no list.\n"); } } static bool abort_uncomp_mp_list(uncomp_mp_list_t& list) { char buff[1024]; if(list.empty()){ return true; } memset(buff, 0, sizeof(buff)); // confirm while(true){ printf("Would you remove all objects? [Y/N]\n"); if(NULL != fgets(buff, sizeof(buff), stdin)){ if(0 == strcasecmp(buff, "Y\n") || 0 == strcasecmp(buff, "YES\n")){ break; }else if(0 == strcasecmp(buff, "N\n") || 0 == strcasecmp(buff, "NO\n")){ return true; } printf("*** please put Y(yes) or N(no).\n"); } } // do removing their. S3fsCurl s3fscurl; bool result = true; for(uncomp_mp_list_t::iterator iter = list.begin(); iter != list.end(); ++iter){ const char* tpath = (*iter).key.c_str(); string upload_id = (*iter).id; if(0 != s3fscurl.AbortMultipartUpload(tpath, upload_id)){ S3FS_PRN_EXIT("Failed to remove %s multipart uploading object.", tpath); result = false; }else{ printf("Succeed to remove %s multipart uploading object.\n", tpath); } // reset(initialize) curl object s3fscurl.DestroyCurlHandle(); } return result; } static bool get_uncomp_mp_list(xmlDocPtr doc, uncomp_mp_list_t& list) { if(!doc){ return false; } xmlXPathContextPtr ctx = xmlXPathNewContext(doc);; string xmlnsurl; string ex_upload = "//"; string ex_key = ""; string ex_id = ""; string ex_date = ""; if(!noxmlns && GetXmlNsUrl(doc, xmlnsurl)){ xmlXPathRegisterNs(ctx, (xmlChar*)"s3", (xmlChar*)xmlnsurl.c_str()); ex_upload += "s3:"; ex_key += "s3:"; ex_id += "s3:"; ex_date += "s3:"; } ex_upload += "Upload"; ex_key += "Key"; ex_id += "UploadId"; ex_date += "Initiated"; // get "Upload" Tags xmlXPathObjectPtr upload_xp; if(NULL == (upload_xp = xmlXPathEvalExpression((xmlChar*)ex_upload.c_str(), ctx))){ S3FS_PRN_ERR("xmlXPathEvalExpression returns null."); return false; } if(xmlXPathNodeSetIsEmpty(upload_xp->nodesetval)){ S3FS_PRN_INFO("upload_xp->nodesetval is empty."); S3FS_XMLXPATHFREEOBJECT(upload_xp); S3FS_XMLXPATHFREECONTEXT(ctx); return true; } // Make list int cnt; xmlNodeSetPtr upload_nodes; list.clear(); for(cnt = 0, upload_nodes = upload_xp->nodesetval; cnt < upload_nodes->nodeNr; cnt++){ ctx->node = upload_nodes->nodeTab[cnt]; UNCOMP_MP_INFO part; xmlChar* ex_value; // search "Key" tag if(NULL == (ex_value = get_exp_value_xml(doc, ctx, ex_key.c_str()))){ continue; } if('/' != *((char*)ex_value)){ part.key = "/"; }else{ part.key = ""; } part.key += (char*)ex_value; S3FS_XMLFREE(ex_value); // search "UploadId" tag if(NULL == (ex_value = get_exp_value_xml(doc, ctx, ex_id.c_str()))){ continue; } part.id = (char*)ex_value; S3FS_XMLFREE(ex_value); // search "Initiated" tag if(NULL == (ex_value = get_exp_value_xml(doc, ctx, ex_date.c_str()))){ continue; } part.date = (char*)ex_value; S3FS_XMLFREE(ex_value); list.push_back(part); } S3FS_XMLXPATHFREEOBJECT(upload_xp); S3FS_XMLXPATHFREECONTEXT(ctx); return true; } static int s3fs_utility_mode(void) { if(!utility_mode){ return EXIT_FAILURE; } // ssl init if(!s3fs_init_global_ssl()){ S3FS_PRN_EXIT("could not initialize for ssl libraries."); return EXIT_FAILURE; } // init curl if(!S3fsCurl::InitS3fsCurl("/etc/mime.types")){ S3FS_PRN_EXIT("Could not initiate curl library."); s3fs_destroy_global_ssl(); return EXIT_FAILURE; } printf("Utility Mode\n"); S3fsCurl s3fscurl; string body; int result = EXIT_SUCCESS; if(0 != s3fscurl.MultipartListRequest(body)){ S3FS_PRN_EXIT("Could not get list multipart upload."); result = EXIT_FAILURE; }else{ // perse result(uncomplete multipart upload information) S3FS_PRN_DBG("response body = {\n%s\n}", body.c_str()); xmlDocPtr doc; if(NULL == (doc = xmlReadMemory(body.c_str(), static_cast(body.size()), "", NULL, 0))){ S3FS_PRN_DBG("xmlReadMemory exited with error."); result = EXIT_FAILURE; }else{ // make working uploads list uncomp_mp_list_t list; if(!get_uncomp_mp_list(doc, list)){ S3FS_PRN_DBG("get_uncomp_mp_list exited with error."); result = EXIT_FAILURE; }else{ // print list print_uncomp_mp_list(list); // remove if(!abort_uncomp_mp_list(list)){ S3FS_PRN_DBG("an error occurred during removal process."); result = EXIT_FAILURE; } } S3FS_XMLFREEDOC(doc); } } // Destroy curl if(!S3fsCurl::DestroyS3fsCurl()){ S3FS_PRN_WARN("Could not release curl library."); } // ssl s3fs_destroy_global_ssl(); return result; } // // If calling with wrong region, s3fs gets following error body as 400 erro code. // "AuthorizationHeaderMalformedThe authorization header is // malformed; the region 'us-east-1' is wrong; expecting 'ap-northeast-1' // ap-northeast-1...... // " // // So this is cheep codes but s3fs should get correct reagion automatically. // static bool check_region_error(const char* pbody, string& expectregion) { if(!pbody){ return false; } const char* region; const char* regionend; if(NULL == (region = strcasestr(pbody, "The authorization header is malformed; the region "))){ return false; } if(NULL == (region = strcasestr(region, "expecting \'"))){ return false; } region += strlen("expecting \'"); if(NULL == (regionend = strchr(region, '\''))){ return false; } string strtmp(region, (regionend - region)); if(0 == strtmp.length()){ return false; } expectregion = strtmp; return true; } static int s3fs_check_service(void) { S3FS_PRN_INFO("check services."); // At first time for access S3, we check IAM role if it sets. if(!S3fsCurl::CheckIAMCredentialUpdate()){ S3FS_PRN_CRIT("Failed to check IAM role name(%s).", S3fsCurl::GetIAMRole()); return EXIT_FAILURE; } S3fsCurl s3fscurl; int res; if(0 > (res = s3fscurl.CheckBucket())){ // get response code long responseCode = s3fscurl.GetLastResponseCode(); // check wrong endpoint, and automatically switch endpoint if(responseCode == 400 && !is_specified_endpoint){ // check region error BodyData* body = s3fscurl.GetBodyData(); string expectregion; if(check_region_error(body->str(), expectregion)){ // not specified endpoint, so try to connect to expected region. S3FS_PRN_CRIT("Could not connect wrong region %s, so retry to connect region %s.", endpoint.c_str(), expectregion.c_str()); endpoint = expectregion; if(S3fsCurl::IsSignatureV4()){ if(host == "http://s3.amazonaws.com"){ host = "http://s3-" + endpoint + ".amazonaws.com"; }else if(host == "https://s3.amazonaws.com"){ host = "https://s3-" + endpoint + ".amazonaws.com"; } } // retry to check with new endpoint s3fscurl.DestroyCurlHandle(); res = s3fscurl.CheckBucket(); responseCode = s3fscurl.GetLastResponseCode(); } } // try signature v2 if(0 > res && (responseCode == 400 || responseCode == 403) && S3fsCurl::IsSignatureV4()){ // switch sigv2 S3FS_PRN_WARN("Could not connect, so retry to connect by signature version 2."); S3fsCurl::SetSignatureV4(false); // retry to check with sigv2 s3fscurl.DestroyCurlHandle(); res = s3fscurl.CheckBucket(); responseCode = s3fscurl.GetLastResponseCode(); } // check errors(after retrying) if(0 > res && responseCode != 200 && responseCode != 301){ if(responseCode == 400){ S3FS_PRN_CRIT("Bad Request - result of checking service."); return EXIT_FAILURE; } if(responseCode == 403){ S3FS_PRN_CRIT("invalid credentials - result of checking service."); return EXIT_FAILURE; } if(responseCode == 404){ S3FS_PRN_CRIT("bucket not found - result of checking service."); return EXIT_FAILURE; } // unable to connect if(responseCode == CURLE_OPERATION_TIMEDOUT){ S3FS_PRN_CRIT("unable to connect bucket and timeout - result of checking service."); return EXIT_FAILURE; } // another error S3FS_PRN_CRIT("unable to connect - result of checking service."); return EXIT_FAILURE; } } // make sure remote mountpath exists and is a directory if(mount_prefix.size() > 0){ if(remote_mountpath_exists(mount_prefix.c_str()) != 0){ S3FS_PRN_CRIT("remote mountpath %s not found.", mount_prefix.c_str()); return EXIT_FAILURE; } } S3FS_MALLOCTRIM(0); return EXIT_SUCCESS; } // Return: 1 - OK(could read and set accesskey etc.) // 0 - NG(could not read) // -1 - Should shoutdown immidiatly static int check_for_aws_format(void) { size_t first_pos = string::npos; string line; bool got_access_key_id_line = 0; bool got_secret_key_line = 0; string str1 ("AWSAccessKeyId="); string str2 ("AWSSecretKey="); size_t found; string AccessKeyId; string SecretAccesskey; ifstream PF(passwd_file.c_str()); if(PF.good()){ while (getline(PF, line)){ if(line[0]=='#'){ continue; } if(line.size() == 0){ continue; } if('\r' == line[line.size() - 1]){ line = line.substr(0, line.size() - 1); if(line.size() == 0){ continue; } } first_pos = line.find_first_of(" \t"); if(first_pos != string::npos){ S3FS_PRN_EXIT("invalid line in passwd file, found whitespace character."); return -1; } first_pos = line.find_first_of("["); if(first_pos != string::npos && first_pos == 0){ S3FS_PRN_EXIT("invalid line in passwd file, found a bracket \"[\" character."); return -1; } found = line.find(str1); if(found != string::npos){ first_pos = line.find_first_of("="); AccessKeyId = line.substr(first_pos + 1, string::npos); got_access_key_id_line = 1; continue; } found = line.find(str2); if(found != string::npos){ first_pos = line.find_first_of("="); SecretAccesskey = line.substr(first_pos + 1, string::npos); got_secret_key_line = 1; continue; } } } if(got_access_key_id_line && got_secret_key_line){ if(!S3fsCurl::SetAccessKey(AccessKeyId.c_str(), SecretAccesskey.c_str())){ S3FS_PRN_EXIT("if one access key is specified, both keys need to be specified."); return 0; } return 1; }else{ return 0; } } // // check_passwd_file_perms // // expect that global passwd_file variable contains // a non-empty value and is readable by the current user // // Check for too permissive access to the file // help save users from themselves via a security hole // // only two options: return or error out // static int check_passwd_file_perms(void) { struct stat info; // let's get the file info if(stat(passwd_file.c_str(), &info) != 0){ S3FS_PRN_EXIT("unexpected error from stat(%s).", passwd_file.c_str()); return EXIT_FAILURE; } // return error if any file has others permissions if( (info.st_mode & S_IROTH) || (info.st_mode & S_IWOTH) || (info.st_mode & S_IXOTH)) { S3FS_PRN_EXIT("credentials file %s should not have others permissions.", passwd_file.c_str()); return EXIT_FAILURE; } // Any local file should not have any group permissions // /etc/passwd-s3fs can have group permissions if(passwd_file != "/etc/passwd-s3fs"){ if( (info.st_mode & S_IRGRP) || (info.st_mode & S_IWGRP) || (info.st_mode & S_IXGRP)) { S3FS_PRN_EXIT("credentials file %s should not have group permissions.", passwd_file.c_str()); return EXIT_FAILURE; } }else{ // "/etc/passwd-s3fs" does not allow group write. if((info.st_mode & S_IWGRP)){ S3FS_PRN_EXIT("credentials file %s should not have group writable permissions.", passwd_file.c_str()); return EXIT_FAILURE; } } if((info.st_mode & S_IXUSR) || (info.st_mode & S_IXGRP)){ S3FS_PRN_EXIT("credentials file %s should not have executable permissions.", passwd_file.c_str()); return EXIT_FAILURE; } return EXIT_SUCCESS; } // // read_passwd_file // // Support for per bucket credentials // // Format for the credentials file: // [bucket:]AccessKeyId:SecretAccessKey // // Lines beginning with # are considered comments // and ignored, as are empty lines // // Uncommented lines without the ":" character are flagged as // an error, so are lines with spaces or tabs // // only one default key pair is allowed, but not required // static int read_passwd_file(void) { string line; string field1, field2, field3; size_t first_pos = string::npos; size_t last_pos = string::npos; bool default_found = 0; int aws_format; // if you got here, the password file // exists and is readable by the // current user, check for permissions if(EXIT_SUCCESS != check_passwd_file_perms()){ return EXIT_FAILURE; } aws_format = check_for_aws_format(); if(1 == aws_format){ return EXIT_SUCCESS; }else if(-1 == aws_format){ return EXIT_FAILURE; } ifstream PF(passwd_file.c_str()); if(PF.good()){ while (getline(PF, line)){ if(line[0]=='#'){ continue; } if(line.size() == 0){ continue; } if('\r' == line[line.size() - 1]){ line = line.substr(0, line.size() - 1); if(line.size() == 0){ continue; } } first_pos = line.find_first_of(" \t"); if(first_pos != string::npos){ S3FS_PRN_EXIT("invalid line in passwd file, found whitespace character."); return EXIT_FAILURE; } first_pos = line.find_first_of("["); if(first_pos != string::npos && first_pos == 0){ S3FS_PRN_EXIT("invalid line in passwd file, found a bracket \"[\" character."); return EXIT_FAILURE; } first_pos = line.find_first_of(":"); if(first_pos == string::npos){ S3FS_PRN_EXIT("invalid line in passwd file, no \":\" separator found."); return EXIT_FAILURE; } last_pos = line.find_last_of(":"); if(first_pos != last_pos){ // bucket specified field1 = line.substr(0,first_pos); field2 = line.substr(first_pos + 1, last_pos - first_pos - 1); field3 = line.substr(last_pos + 1, string::npos); }else{ // no bucket specified - original style - found default key if(default_found == 1){ S3FS_PRN_EXIT("more than one default key pair found in passwd file."); return EXIT_FAILURE; } default_found = 1; field1.assign(""); field2 = line.substr(0,first_pos); field3 = line.substr(first_pos + 1, string::npos); if(!S3fsCurl::SetAccessKey(field2.c_str(), field3.c_str())){ S3FS_PRN_EXIT("if one access key is specified, both keys need to be specified."); return EXIT_FAILURE; } } // does the bucket we are mounting match this passwd file entry? // if so, use that key pair, otherwise use the default key, if found, // will be used if(field1.size() != 0 && field1 == bucket){ if(!S3fsCurl::SetAccessKey(field2.c_str(), field3.c_str())){ S3FS_PRN_EXIT("if one access key is specified, both keys need to be specified."); return EXIT_FAILURE; } break; } } } return EXIT_SUCCESS; } // // get_access_keys // // called only when were are not mounting a // public bucket // // Here is the order precedence for getting the // keys: // // 1 - from the command line (security risk) // 2 - from a password file specified on the command line // 3 - from environment variables // 4 - from the users ~/.passwd-s3fs // 5 - from /etc/passwd-s3fs // static int get_access_keys(void) { // should be redundant if(S3fsCurl::IsPublicBucket()){ return EXIT_SUCCESS; } // 1 - keys specified on the command line if(S3fsCurl::IsSetAccessKeyId()){ return EXIT_SUCCESS; } // 2 - was specified on the command line if(passwd_file.size() > 0){ ifstream PF(passwd_file.c_str()); if(PF.good()){ PF.close(); return read_passwd_file(); }else{ S3FS_PRN_EXIT("specified passwd_file is not readable."); return EXIT_FAILURE; } } // 3 - environment variables char* AWSACCESSKEYID = getenv("AWSACCESSKEYID"); char* AWSSECRETACCESSKEY = getenv("AWSSECRETACCESSKEY"); if(AWSACCESSKEYID != NULL || AWSSECRETACCESSKEY != NULL){ if( (AWSACCESSKEYID == NULL && AWSSECRETACCESSKEY != NULL) || (AWSACCESSKEYID != NULL && AWSSECRETACCESSKEY == NULL) ){ S3FS_PRN_EXIT("if environment variable AWSACCESSKEYID is set then AWSSECRETACCESSKEY must be set too."); return EXIT_FAILURE; } if(!S3fsCurl::SetAccessKey(AWSACCESSKEYID, AWSSECRETACCESSKEY)){ S3FS_PRN_EXIT("if one access key is specified, both keys need to be specified."); return EXIT_FAILURE; } return EXIT_SUCCESS; } // 3a - from the AWS_CREDENTIAL_FILE environment variable char * AWS_CREDENTIAL_FILE; AWS_CREDENTIAL_FILE = getenv("AWS_CREDENTIAL_FILE"); if(AWS_CREDENTIAL_FILE != NULL){ passwd_file.assign(AWS_CREDENTIAL_FILE); if(passwd_file.size() > 0){ ifstream PF(passwd_file.c_str()); if(PF.good()){ PF.close(); return read_passwd_file(); }else{ S3FS_PRN_EXIT("AWS_CREDENTIAL_FILE: \"%s\" is not readable.", passwd_file.c_str()); return EXIT_FAILURE; } } } // 4 - from the default location in the users home directory char * HOME; HOME = getenv ("HOME"); if(HOME != NULL){ passwd_file.assign(HOME); passwd_file.append("/.passwd-s3fs"); ifstream PF(passwd_file.c_str()); if(PF.good()){ PF.close(); if(EXIT_SUCCESS != read_passwd_file()){ return EXIT_FAILURE; } // It is possible that the user's file was there but // contained no key pairs i.e. commented out // in that case, go look in the final location if(S3fsCurl::IsSetAccessKeyId()){ return EXIT_SUCCESS; } } } // 5 - from the system default location passwd_file.assign("/etc/passwd-s3fs"); ifstream PF(passwd_file.c_str()); if(PF.good()){ PF.close(); return read_passwd_file(); } S3FS_PRN_EXIT("could not determine how to establish security credentials."); return EXIT_FAILURE; } // // Check & Set attributes for mount point. // static int set_moutpoint_attribute(struct stat& mpst) { mp_uid = geteuid(); mp_gid = getegid(); mp_mode = S_IFDIR | (allow_other ? (is_mp_umask ? (~mp_umask & (S_IRWXU | S_IRWXG | S_IRWXO)) : (S_IRWXU | S_IRWXG | S_IRWXO)) : S_IRWXU); S3FS_PRN_INFO2("PROC(uid=%u, gid=%u) - MountPoint(uid=%u, gid=%u, mode=%04o)", (unsigned int)mp_uid, (unsigned int)mp_gid, (unsigned int)(mpst.st_uid), (unsigned int)(mpst.st_gid), mpst.st_mode); // check owner if(0 == mp_uid || mpst.st_uid == mp_uid){ return true; } // check group permission if(mpst.st_gid == mp_gid || 1 == is_uid_inculde_group(mp_uid, mpst.st_gid)){ if(S_IRWXG == (mpst.st_mode & S_IRWXG)){ return true; } } // check other permission if(S_IRWXO == (mpst.st_mode & S_IRWXO)){ return true; } return false; } // This is repeatedly called by the fuse option parser // if the key is equal to FUSE_OPT_KEY_OPT, it's an option passed in prefixed by // '-' or '--' e.g.: -f -d -ousecache=/tmp // // if the key is equal to FUSE_OPT_KEY_NONOPT, it's either the bucket name // or the mountpoint. The bucket name will always come before the mountpoint static int my_fuse_opt_proc(void* data, const char* arg, int key, struct fuse_args* outargs) { if(key == FUSE_OPT_KEY_NONOPT){ // the first NONOPT option is the bucket name if(bucket.size() == 0){ // extract remote mount path char *bucket_name = (char*)arg; if(strstr(arg, ":")){ bucket = strtok(bucket_name, ":"); char* pmount_prefix = strtok(NULL, ":"); if(pmount_prefix){ if(0 == strlen(pmount_prefix) || '/' != pmount_prefix[0]){ S3FS_PRN_EXIT("path(%s) must be prefix \"/\".", pmount_prefix); return -1; } mount_prefix = pmount_prefix; // remove trailing slash if(mount_prefix.at(mount_prefix.size() - 1) == '/'){ mount_prefix = mount_prefix.substr(0, mount_prefix.size() - 1); } } }else{ bucket = arg; } return 0; } // the second NONPOT option is the mountpoint(not utility mode) if(0 == mountpoint.size() && 0 == utility_mode){ // save the mountpoint and do some basic error checking mountpoint = arg; struct stat stbuf; if(stat(arg, &stbuf) == -1){ S3FS_PRN_EXIT("unable to access MOUNTPOINT %s: %s", mountpoint.c_str(), strerror(errno)); return -1; } if(!(S_ISDIR(stbuf.st_mode))){ S3FS_PRN_EXIT("MOUNTPOINT: %s is not a directory.", mountpoint.c_str()); return -1; } if(!set_moutpoint_attribute(stbuf)){ S3FS_PRN_EXIT("MOUNTPOINT: %s permission denied.", mountpoint.c_str()); return -1; } if(!nonempty){ struct dirent *ent; DIR *dp = opendir(mountpoint.c_str()); if(dp == NULL){ S3FS_PRN_EXIT("failed to open MOUNTPOINT: %s: %s", mountpoint.c_str(), strerror(errno)); return -1; } while((ent = readdir(dp)) != NULL){ if(strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0){ closedir(dp); S3FS_PRN_EXIT("MOUNTPOINT directory %s is not empty. if you are sure this is safe, can use the 'nonempty' mount option.", mountpoint.c_str()); return -1; } } closedir(dp); } return 1; } // Unknow option if(0 == utility_mode){ S3FS_PRN_EXIT("specified unknown third optioni(%s).", arg); }else{ S3FS_PRN_EXIT("specified unknown second optioni(%s). you don't need to specify second option(mountpoint) for utility mode(-u).", arg); } return -1; }else if(key == FUSE_OPT_KEY_OPT){ if(0 == STR2NCMP(arg, "uid=")){ s3fs_uid = get_uid(strchr(arg, '=') + sizeof(char)); if(0 != geteuid() && 0 == s3fs_uid){ S3FS_PRN_EXIT("root user can only specify uid=0."); return -1; } is_s3fs_uid = true; return 1; // continue for fuse option } if(0 == STR2NCMP(arg, "gid=")){ s3fs_gid = get_gid(strchr(arg, '=') + sizeof(char)); if(0 != getegid() && 0 == s3fs_gid){ S3FS_PRN_EXIT("root user can only specify gid=0."); return -1; } is_s3fs_gid = true; return 1; // continue for fuse option } if(0 == STR2NCMP(arg, "umask=")){ s3fs_umask = strtol(strchr(arg, '=') + sizeof(char), NULL, 0); s3fs_umask &= (S_IRWXU | S_IRWXG | S_IRWXO); is_s3fs_umask = true; return 1; // continue for fuse option } if(0 == strcmp(arg, "allow_other")){ allow_other = true; return 1; // continue for fuse option } if(0 == STR2NCMP(arg, "mp_umask=")){ mp_umask = strtol(strchr(arg, '=') + sizeof(char), NULL, 0); mp_umask &= (S_IRWXU | S_IRWXG | S_IRWXO); is_mp_umask = true; return 0; } if(0 == STR2NCMP(arg, "default_acl=")){ const char* acl = strchr(arg, '=') + sizeof(char); S3fsCurl::SetDefaultAcl(acl); return 0; } if(0 == STR2NCMP(arg, "retries=")){ S3fsCurl::SetRetries(static_cast(s3fs_strtoofft(strchr(arg, '=') + sizeof(char)))); return 0; } if(0 == STR2NCMP(arg, "use_cache=")){ FdManager::SetCacheDir(strchr(arg, '=') + sizeof(char)); return 0; } if(0 == strcmp(arg, "del_cache")){ is_remove_cache = true; return 0; } if(0 == STR2NCMP(arg, "multireq_max=")){ long maxreq = static_cast(s3fs_strtoofft(strchr(arg, '=') + sizeof(char))); S3fsMultiCurl::SetMaxMultiRequest(maxreq); return 0; } if(0 == strcmp(arg, "nonempty")){ nonempty = true; return 1; // need to continue for fuse. } if(0 == strcmp(arg, "nomultipart")){ nomultipart = true; return 0; } // old format for storage_class if(0 == strcmp(arg, "use_rrs") || 0 == STR2NCMP(arg, "use_rrs=")){ off_t rrs = 1; // for an old format. if(0 == STR2NCMP(arg, "use_rrs=")){ rrs = s3fs_strtoofft(strchr(arg, '=') + sizeof(char)); } if(0 == rrs){ S3fsCurl::SetStorageClass(STANDARD); }else if(1 == rrs){ S3fsCurl::SetStorageClass(REDUCED_REDUNDANCY); }else{ S3FS_PRN_EXIT("poorly formed argument to option: use_rrs"); return -1; } return 0; } if(0 == STR2NCMP(arg, "storage_class=")){ const char *storage_class = strchr(arg, '=') + sizeof(char); if(0 == strcmp(storage_class, "standard")){ S3fsCurl::SetStorageClass(STANDARD); }else if(0 == strcmp(storage_class, "standard_ia")){ S3fsCurl::SetStorageClass(STANDARD_IA); }else if(0 == strcmp(storage_class, "reduced_redundancy")){ S3fsCurl::SetStorageClass(REDUCED_REDUNDANCY); }else{ S3FS_PRN_EXIT("unknown value for storage_class: %s", storage_class); return -1; } return 0; } // // [NOTE] // use_sse Set Server Side Encrypting type to SSE-S3 // use_sse=1 // use_sse=file Set Server Side Encrypting type to Custom key(SSE-C) and load custom keys // use_sse=custom(c):file // use_sse=custom(c) Set Server Side Encrypting type to Custom key(SSE-C) // use_sse=kmsid(k):kms-key-id Set Server Side Encrypting type to AWS Key Management key id(SSE-KMS) and load KMS id // use_sse=kmsid(k) Set Server Side Encrypting type to AWS Key Management key id(SSE-KMS) // // load_sse_c=file Load Server Side Encrypting custom keys // // AWSSSECKEYS Loaing Environment for Server Side Encrypting custom keys // AWSSSEKMSID Loaing Environment for Server Side Encrypting Key id // if(0 == STR2NCMP(arg, "use_sse")){ if(0 == strcmp(arg, "use_sse") || 0 == strcmp(arg, "use_sse=1")){ // use_sse=1 is old type paraemter // sse type is SSE_S3 if(!S3fsCurl::IsSseDisable() && !S3fsCurl::IsSseS3Type()){ S3FS_PRN_EXIT("already set SSE another type, so confrict use_sse option or environment."); return -1; } S3fsCurl::SetSseType(SSE_S3); }else if(0 == strcmp(arg, "use_sse=kmsid") || 0 == strcmp(arg, "use_sse=k")){ // sse type is SSE_KMS with out kmsid(expecting id is loaded by environment) if(!S3fsCurl::IsSseDisable() && !S3fsCurl::IsSseKmsType()){ S3FS_PRN_EXIT("already set SSE another type, so confrict use_sse option or environment."); return -1; } if(!S3fsCurl::IsSetSseKmsId()){ S3FS_PRN_EXIT("use_sse=kms but not loaded kms id by environemnt."); return -1; } S3fsCurl::SetSseType(SSE_KMS); }else if(0 == STR2NCMP(arg, "use_sse=kmsid:") || 0 == STR2NCMP(arg, "use_sse=k:")){ // sse type is SSE_KMS with kmsid if(!S3fsCurl::IsSseDisable() && !S3fsCurl::IsSseKmsType()){ S3FS_PRN_EXIT("already set SSE another type, so confrict use_sse option or environment."); return -1; } const char* kmsid; if(0 == STR2NCMP(arg, "use_sse=kmsid:")){ kmsid = &arg[strlen("use_sse=kmsid:")]; }else{ kmsid = &arg[strlen("use_sse=k:")]; } if(!S3fsCurl::SetSseKmsid(kmsid)){ S3FS_PRN_EXIT("failed to load use_sse kms id."); return -1; } S3fsCurl::SetSseType(SSE_KMS); }else if(0 == strcmp(arg, "use_sse=custom") || 0 == strcmp(arg, "use_sse=c")){ // sse type is SSE_C with out custom keys(expecting keays are loaded by environment or load_sse_c option) if(!S3fsCurl::IsSseDisable() && !S3fsCurl::IsSseCType()){ S3FS_PRN_EXIT("already set SSE another type, so confrict use_sse option or environment."); return -1; } // [NOTE] // do not check ckeys exists here. // S3fsCurl::SetSseType(SSE_C); }else if(0 == STR2NCMP(arg, "use_sse=custom:") || 0 == STR2NCMP(arg, "use_sse=c:")){ // sse type is SSE_C with custom keys if(!S3fsCurl::IsSseDisable() && !S3fsCurl::IsSseCType()){ S3FS_PRN_EXIT("already set SSE another type, so confrict use_sse option or environment."); return -1; } const char* ssecfile; if(0 == STR2NCMP(arg, "use_sse=custom:")){ ssecfile = &arg[strlen("use_sse=custom:")]; }else{ ssecfile = &arg[strlen("use_sse=c:")]; } if(!S3fsCurl::SetSseCKeys(ssecfile)){ S3FS_PRN_EXIT("failed to load use_sse custom key file(%s).", ssecfile); return -1; } S3fsCurl::SetSseType(SSE_C); }else if(0 == strcmp(arg, "use_sse=")){ // this type is old style(paraemter is custom key file path) // SSE_C with custom keys. const char* ssecfile = &arg[strlen("use_sse=")]; if(!S3fsCurl::SetSseCKeys(ssecfile)){ S3FS_PRN_EXIT("failed to load use_sse custom key file(%s).", ssecfile); return -1; } S3fsCurl::SetSseType(SSE_C); }else{ // never come here. S3FS_PRN_EXIT("something wrong use_sse optino."); return -1; } return 0; } // [NOTE] // Do only load SSE custom keys, care for set without set sse type. if(0 == STR2NCMP(arg, "load_sse_c=")){ const char* ssecfile = &arg[strlen("load_sse_c=")]; if(!S3fsCurl::SetSseCKeys(ssecfile)){ S3FS_PRN_EXIT("failed to load use_sse custom key file(%s).", ssecfile); return -1; } } if(0 == STR2NCMP(arg, "ssl_verify_hostname=")){ long sslvh = static_cast(s3fs_strtoofft(strchr(arg, '=') + sizeof(char))); if(-1 == S3fsCurl::SetSslVerifyHostname(sslvh)){ S3FS_PRN_EXIT("poorly formed argument to option: ssl_verify_hostname."); return -1; } return 0; } if(0 == STR2NCMP(arg, "passwd_file=")){ passwd_file = strchr(arg, '=') + sizeof(char); return 0; } if(0 == STR2NCMP(arg, "iam_role=")){ const char* role = strchr(arg, '=') + sizeof(char); S3fsCurl::SetIAMRole(role); return 0; } if(0 == STR2NCMP(arg, "public_bucket=")){ off_t pubbucket = s3fs_strtoofft(strchr(arg, '=') + sizeof(char)); if(1 == pubbucket){ S3fsCurl::SetPublicBucket(true); }else if(0 == pubbucket){ S3fsCurl::SetPublicBucket(false); }else{ S3FS_PRN_EXIT("poorly formed argument to option: public_bucket."); return -1; } return 0; } if(0 == STR2NCMP(arg, "host=")){ host = strchr(arg, '=') + sizeof(char); return 0; } if(0 == STR2NCMP(arg, "servicepath=")){ service_path = strchr(arg, '=') + sizeof(char); return 0; } if(0 == strcmp(arg, "no_check_certificate")){ S3fsCurl::SetCheckCertificate(false); return 0; } if(0 == STR2NCMP(arg, "connect_timeout=")){ long contimeout = static_cast(s3fs_strtoofft(strchr(arg, '=') + sizeof(char))); S3fsCurl::SetConnectTimeout(contimeout); return 0; } if(0 == STR2NCMP(arg, "readwrite_timeout=")){ time_t rwtimeout = static_cast(s3fs_strtoofft(strchr(arg, '=') + sizeof(char))); S3fsCurl::SetReadwriteTimeout(rwtimeout); return 0; } if(0 == STR2NCMP(arg, "max_stat_cache_size=")){ unsigned long cache_size = static_cast(s3fs_strtoofft(strchr(arg, '=') + sizeof(char))); StatCache::getStatCacheData()->SetCacheSize(cache_size); return 0; } if(0 == STR2NCMP(arg, "stat_cache_expire=")){ time_t expr_time = static_cast(s3fs_strtoofft(strchr(arg, '=') + sizeof(char))); StatCache::getStatCacheData()->SetExpireTime(expr_time); return 0; } if(0 == strcmp(arg, "enable_noobj_cache")){ StatCache::getStatCacheData()->EnableCacheNoObject(); return 0; } if(0 == strcmp(arg, "nodnscache")){ S3fsCurl::SetDnsCache(false); return 0; } if(0 == strcmp(arg, "nosscache")){ S3fsCurl::SetSslSessionCache(false); return 0; } if(0 == STR2NCMP(arg, "parallel_count=") || 0 == STR2NCMP(arg, "parallel_upload=")){ int maxpara = static_cast(s3fs_strtoofft(strchr(arg, '=') + sizeof(char))); if(0 >= maxpara){ S3FS_PRN_EXIT("argument should be over 1: parallel_count"); return -1; } S3fsCurl::SetMaxParallelCount(maxpara); if(FdManager::GetPageSize() < static_cast(S3fsCurl::GetMultipartSize() * S3fsCurl::GetMaxParallelCount())){ FdManager::SetPageSize(static_cast(S3fsCurl::GetMultipartSize() * S3fsCurl::GetMaxParallelCount())); } return 0; } if(0 == STR2NCMP(arg, "fd_page_size=")){ size_t pagesize = static_cast(s3fs_strtoofft(strchr(arg, '=') + sizeof(char))); if(pagesize < static_cast(S3fsCurl::GetMultipartSize() * S3fsCurl::GetMaxParallelCount())){ S3FS_PRN_EXIT("argument should be over 1MB: fd_page_size"); return -1; } FdManager::SetPageSize(pagesize); return 0; } if(0 == STR2NCMP(arg, "multipart_size=")){ off_t size = static_cast(s3fs_strtoofft(strchr(arg, '=') + sizeof(char))); if(!S3fsCurl::SetMultipartSize(size)){ S3FS_PRN_EXIT("multipart_size option must be at least 10 MB."); return -1; } if(FdManager::GetPageSize() < static_cast(S3fsCurl::GetMultipartSize() * S3fsCurl::GetMaxParallelCount())){ FdManager::SetPageSize(static_cast(S3fsCurl::GetMultipartSize() * S3fsCurl::GetMaxParallelCount())); } return 0; } if(0 == STR2NCMP(arg, "singlepart_copy_limit=")){ singlepart_copy_limit = static_cast(s3fs_strtoofft(strchr(arg, '=') + sizeof(char))) * 1024; return 0; } if(0 == STR2NCMP(arg, "ahbe_conf=")){ string ahbe_conf = strchr(arg, '=') + sizeof(char); if(!AdditionalHeader::get()->Load(ahbe_conf.c_str())){ S3FS_PRN_EXIT("failed to load ahbe_conf file(%s).", ahbe_conf.c_str()); return -1; } AdditionalHeader::get()->Dump(); return 0; } if(0 == strcmp(arg, "noxmlns")){ noxmlns = true; return 0; } if(0 == strcmp(arg, "nocopyapi")){ nocopyapi = true; return 0; } if(0 == strcmp(arg, "norenameapi")){ norenameapi = true; return 0; } if(0 == strcmp(arg, "enable_content_md5")){ S3fsCurl::SetContentMd5(true); return 0; } if(0 == STR2NCMP(arg, "url=")){ host = strchr(arg, '=') + sizeof(char); // strip the trailing '/', if any, off the end of the host // string size_t found, length; found = host.find_last_of('/'); length = host.length(); while(found == (length - 1) && length > 0){ host.erase(found); found = host.find_last_of('/'); length = host.length(); } return 0; } if(0 == strcmp(arg, "sigv2")){ S3fsCurl::SetSignatureV4(false); return 0; } if(0 == strcmp(arg, "createbucket")){ create_bucket = true; return 0; } if(0 == STR2NCMP(arg, "endpoint=")){ endpoint = strchr(arg, '=') + sizeof(char); is_specified_endpoint = true; return 0; } if(0 == strcmp(arg, "use_path_request_style")){ pathrequeststyle = true; return 0; } // // debug option for s3fs // if(0 == STR2NCMP(arg, "dbglevel=")){ const char* strlevel = strchr(arg, '=') + sizeof(char); if(0 == strcasecmp(strlevel, "silent") || 0 == strcasecmp(strlevel, "critical") || 0 == strcasecmp(strlevel, "crit")){ set_s3fs_log_level(S3FS_LOG_CRIT); }else if(0 == strcasecmp(strlevel, "error") || 0 == strcasecmp(strlevel, "err")){ set_s3fs_log_level(S3FS_LOG_ERR); }else if(0 == strcasecmp(strlevel, "wan") || 0 == strcasecmp(strlevel, "warn") || 0 == strcasecmp(strlevel, "warning")){ set_s3fs_log_level(S3FS_LOG_WARN); }else if(0 == strcasecmp(strlevel, "inf") || 0 == strcasecmp(strlevel, "info") || 0 == strcasecmp(strlevel, "information")){ set_s3fs_log_level(S3FS_LOG_INFO); }else if(0 == strcasecmp(strlevel, "dbg") || 0 == strcasecmp(strlevel, "debug")){ set_s3fs_log_level(S3FS_LOG_DBG); }else{ S3FS_PRN_EXIT("option dbglevel has unknown parameter(%s).", strlevel); return -1; } return 0; } // // debug option // // debug_level is S3FS_LOG_INFO, after second -d is passed to fuse. // if(0 == strcmp(arg, "-d") || 0 == strcmp(arg, "--debug")){ if(!IS_S3FS_LOG_INFO() && !IS_S3FS_LOG_DBG()){ set_s3fs_log_level(S3FS_LOG_INFO); return 0; } if(0 == strcmp(arg, "--debug")){ // fuse doesn't understand "--debug", but it understands -d. // but we can't pass -d back to fuse. return 0; } } // "f2" is not used no more. // (set S3FS_LOG_DBG) if(0 == strcmp(arg, "f2")){ set_s3fs_log_level(S3FS_LOG_DBG); return 0; } if(0 == strcmp(arg, "curldbg")){ S3fsCurl::SetVerbose(true); return 0; } if(0 == STR2NCMP(arg, "accessKeyId=")){ S3FS_PRN_EXIT("option accessKeyId is no longer supported."); return -1; } if(0 == STR2NCMP(arg, "secretAccessKey=")){ S3FS_PRN_EXIT("option secretAccessKey is no longer supported."); return -1; } } return 1; } int main(int argc, char* argv[]) { int ch; int fuse_res; int option_index = 0; struct fuse_operations s3fs_oper; static const struct option long_opts[] = { {"help", no_argument, NULL, 'h'}, {"version", no_argument, 0, 0}, {"debug", no_argument, NULL, 'd'}, {0, 0, 0, 0} }; // init syslog(default CRIT) openlog("s3fs", LOG_PID | LOG_ODELAY | LOG_NOWAIT, LOG_USER); set_s3fs_log_level(debug_level); // init xml2 xmlInitParser(); LIBXML_TEST_VERSION // get progam name - emulate basename size_t found = string::npos; program_name.assign(argv[0]); found = program_name.find_last_of("/"); if(found != string::npos){ program_name.replace(0, found+1, ""); } while((ch = getopt_long(argc, argv, "dho:fsu", long_opts, &option_index)) != -1){ switch(ch){ case 0: if(strcmp(long_opts[option_index].name, "version") == 0){ show_version(); exit(EXIT_SUCCESS); } break; case 'h': show_help(); exit(EXIT_SUCCESS); case 'o': break; case 'd': break; case 'f': foreground = true; break; case 's': break; case 'u': utility_mode = 1; break; default: exit(EXIT_FAILURE); } } // Load SSE environment if(!S3fsCurl::LoadEnvSse()){ S3FS_PRN_EXIT("something wrong about SSE environment."); exit(EXIT_FAILURE); } // clear this structure memset(&s3fs_oper, 0, sizeof(s3fs_oper)); // This is the fuse-style parser for the arguments // after which the bucket name and mountpoint names // should have been set struct fuse_args custom_args = FUSE_ARGS_INIT(argc, argv); if(0 != fuse_opt_parse(&custom_args, NULL, NULL, my_fuse_opt_proc)){ exit(EXIT_FAILURE); } // [NOTE] // exclusive option check here. // if(REDUCED_REDUNDANCY == S3fsCurl::GetStorageClass() && !S3fsCurl::IsSseDisable()){ S3FS_PRN_EXIT("use_sse option could not be specified with storage class reduced_redundancy."); exit(EXIT_FAILURE); } if(!S3fsCurl::FinalCheckSse()){ S3FS_PRN_EXIT("something wrong about SSE options."); exit(EXIT_FAILURE); } // The first plain argument is the bucket if(bucket.size() == 0){ S3FS_PRN_EXIT("missing BUCKET argument."); show_usage(); exit(EXIT_FAILURE); } // bucket names cannot contain upper case characters in virtual-hosted style if((!pathrequeststyle) && (lower(bucket) != bucket)){ S3FS_PRN_EXIT("BUCKET %s, name not compatible with virtual-hosted style.", bucket.c_str()); exit(EXIT_FAILURE); } // check bucket name for illegal characters found = bucket.find_first_of("/:\\;!@#$%^&*?|+="); if(found != string::npos){ S3FS_PRN_EXIT("BUCKET %s -- bucket name contains an illegal character.", bucket.c_str()); exit(EXIT_FAILURE); } // The second plain argument is the mountpoint // if the option was given, we all ready checked for a // readable, non-empty directory, this checks determines // if the mountpoint option was ever supplied if(utility_mode == 0){ if(mountpoint.size() == 0){ S3FS_PRN_EXIT("missing MOUNTPOINT argument."); show_usage(); exit(EXIT_FAILURE); } } // error checking of command line arguments for compatibility if(S3fsCurl::IsPublicBucket() && S3fsCurl::IsSetAccessKeyId()){ S3FS_PRN_EXIT("specifying both public_bucket and the access keys options is invalid."); exit(EXIT_FAILURE); } if(passwd_file.size() > 0 && S3fsCurl::IsSetAccessKeyId()){ S3FS_PRN_EXIT("specifying both passwd_file and the access keys options is invalid."); exit(EXIT_FAILURE); } if(!S3fsCurl::IsPublicBucket()){ if(EXIT_SUCCESS != get_access_keys()){ exit(EXIT_FAILURE); } if(!S3fsCurl::IsSetAccessKeyId()){ S3FS_PRN_EXIT("could not establish security credentials, check documentation."); exit(EXIT_FAILURE); } // More error checking on the access key pair can be done // like checking for appropriate lengths and characters } // check cache dir permission if(!FdManager::CheckCacheTopDir() || !CacheFileStat::CheckCacheFileStatTopDir()){ S3FS_PRN_EXIT("could not allow cache directory permission, check permission of cache directories."); exit(EXIT_FAILURE); } // There's room for more command line error checking // Check to see if the bucket name contains periods and https (SSL) is // being used. This is a known limitation: // http://docs.amazonwebservices.com/AmazonS3/latest/dev/ // The Developers Guide suggests that either use HTTP of for us to write // our own certificate verification logic. // For now, this will be unsupported unless we get a request for it to // be supported. In that case, we have a couple of options: // - implement a command line option that bypasses the verify host // but doesn't bypass verifying the certificate // - write our own host verification (this might be complex) // See issue #128strncasecmp /* if(1 == S3fsCurl::GetSslVerifyHostname()){ found = bucket.find_first_of("."); if(found != string::npos){ found = host.find("https:"); if(found != string::npos){ S3FS_PRN_EXIT("Using https and a bucket name with periods is unsupported."); exit(1); } } } */ if(utility_mode){ exit(s3fs_utility_mode()); } s3fs_oper.getattr = s3fs_getattr; s3fs_oper.readlink = s3fs_readlink; s3fs_oper.mknod = s3fs_mknod; s3fs_oper.mkdir = s3fs_mkdir; s3fs_oper.unlink = s3fs_unlink; s3fs_oper.rmdir = s3fs_rmdir; s3fs_oper.symlink = s3fs_symlink; s3fs_oper.rename = s3fs_rename; s3fs_oper.link = s3fs_link; if(!nocopyapi){ s3fs_oper.chmod = s3fs_chmod; s3fs_oper.chown = s3fs_chown; s3fs_oper.utimens = s3fs_utimens; }else{ s3fs_oper.chmod = s3fs_chmod_nocopy; s3fs_oper.chown = s3fs_chown_nocopy; s3fs_oper.utimens = s3fs_utimens_nocopy; } s3fs_oper.truncate = s3fs_truncate; s3fs_oper.open = s3fs_open; s3fs_oper.read = s3fs_read; s3fs_oper.write = s3fs_write; s3fs_oper.statfs = s3fs_statfs; s3fs_oper.flush = s3fs_flush; s3fs_oper.fsync = s3fs_fsync; s3fs_oper.release = s3fs_release; s3fs_oper.opendir = s3fs_opendir; s3fs_oper.readdir = s3fs_readdir; s3fs_oper.init = s3fs_init; s3fs_oper.destroy = s3fs_destroy; s3fs_oper.access = s3fs_access; s3fs_oper.create = s3fs_create; // extended attributes s3fs_oper.setxattr = s3fs_setxattr; s3fs_oper.getxattr = s3fs_getxattr; s3fs_oper.listxattr = s3fs_listxattr; s3fs_oper.removexattr = s3fs_removexattr; if(!s3fs_init_global_ssl()){ S3FS_PRN_EXIT("could not initialize for ssl libraries."); exit(EXIT_FAILURE); } // set signal handler for debugging if(!set_s3fs_usr2_handler()){ S3FS_PRN_EXIT("could not set signal handler for SIGUSR2."); exit(EXIT_FAILURE); } // now passing things off to fuse, fuse will finish evaluating the command line args fuse_res = fuse_main(custom_args.argc, custom_args.argv, &s3fs_oper, NULL); fuse_opt_free_args(&custom_args); s3fs_destroy_global_ssl(); // cleanup xml2 xmlCleanupParser(); S3FS_MALLOCTRIM(0); exit(fuse_res); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/s3fs.h000066400000000000000000000054221260476112200171220ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef S3FS_S3_H_ #define S3FS_S3_H_ #define FUSE_USE_VERSION 26 #define FIVE_GB 5368709120LL #include #define S3FS_FUSE_EXIT() { \ struct fuse_context* pcxt = fuse_get_context(); \ if(pcxt){ \ fuse_exit(pcxt->fuse); \ } \ } // // s3fs use many small allocated chunk in heap area for // stats cache and parsing xml, etc. The OS may decide // that giving this little memory back to the kernel // will cause too much overhead and delay the operation. // So s3fs calls malloc_trim function to really get the // memory back. Following macros is prepared for that // your system does not have it. // // Address of gratitude, this workaround quotes a document // of libxml2. // http://xmlsoft.org/xmlmem.html // #ifdef HAVE_MALLOC_TRIM #include #define DISPWARN_MALLOCTRIM(str) #define S3FS_MALLOCTRIM(pad) malloc_trim(pad) #define S3FS_XMLFREEDOC(doc) \ { \ xmlFreeDoc(doc); \ S3FS_MALLOCTRIM(0); \ } #define S3FS_XMLFREE(ptr) \ { \ xmlFree(ptr); \ S3FS_MALLOCTRIM(0); \ } #define S3FS_XMLXPATHFREECONTEXT(ctx) \ { \ xmlXPathFreeContext(ctx); \ S3FS_MALLOCTRIM(0); \ } #define S3FS_XMLXPATHFREEOBJECT(obj) \ { \ xmlXPathFreeObject(obj); \ S3FS_MALLOCTRIM(0); \ } #else // HAVE_MALLOC_TRIM #define DISPWARN_MALLOCTRIM(str) \ fprintf(stderr, "Warning: %s without malloc_trim is possibility of the use memory increase.\n", program_name.c_str()) #define S3FS_MALLOCTRIM(pad) #define S3FS_XMLFREEDOC(doc) xmlFreeDoc(doc) #define S3FS_XMLFREE(ptr) xmlFree(ptr) #define S3FS_XMLXPATHFREECONTEXT(ctx) xmlXPathFreeContext(ctx) #define S3FS_XMLXPATHFREEOBJECT(obj) xmlXPathFreeObject(obj) #endif // HAVE_MALLOC_TRIM #endif // S3FS_S3_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/s3fs_auth.h000066400000000000000000000043341260476112200201440ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef S3FS_AUTH_H_ #define S3FS_AUTH_H_ #include #include //------------------------------------------------------------------- // Utility functions for Authentication //------------------------------------------------------------------- // // in common_auth.cpp // std::string s3fs_get_content_md5(int fd); std::string s3fs_md5sum(int fd, off_t start, ssize_t size); std::string s3fs_sha256sum(int fd, off_t start, ssize_t size); // // in xxxxxx_auth.cpp // const char* s3fs_crypt_lib_name(void); bool s3fs_init_global_ssl(void); bool s3fs_destroy_global_ssl(void); bool s3fs_init_crypt_mutex(void); bool s3fs_destroy_crypt_mutex(void); bool s3fs_HMAC(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen); bool s3fs_HMAC256(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen); size_t get_md5_digest_length(void); unsigned char* s3fs_md5hexsum(int fd, off_t start, ssize_t size); bool s3fs_sha256(const unsigned char* data, unsigned int datalen, unsigned char** digest, unsigned int* digestlen); size_t get_sha256_digest_length(void); unsigned char* s3fs_sha256hexsum(int fd, off_t start, ssize_t size); #endif // S3FS_AUTH_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/s3fs_util.cpp000066400000000000000000001052301260476112200205100ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2013 Takeshi Nakatani * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "common.h" #include "s3fs_util.h" #include "string_util.h" #include "s3fs.h" #include "s3fs_auth.h" using namespace std; //------------------------------------------------------------------- // Global valiables //------------------------------------------------------------------- std::string mount_prefix = ""; //------------------------------------------------------------------- // Utility //------------------------------------------------------------------- string get_realpath(const char *path) { string realpath = mount_prefix; realpath += path; return realpath; } //------------------------------------------------------------------- // Class S3ObjList //------------------------------------------------------------------- // New class S3ObjList is base on old s3_object struct. // This class is for S3 compatible clients. // // If name is terminated by "/", it is forced dir type. // If name is terminated by "_$folder$", it is forced dir type. // If is_dir is true and name is not terminated by "/", the name is added "/". // bool S3ObjList::insert(const char* name, const char* etag, bool is_dir) { if(!name || '\0' == name[0]){ return false; } s3obj_t::iterator iter; string newname; string orgname = name; // Normalization string::size_type pos = orgname.find("_$folder$"); if(string::npos != pos){ newname = orgname.substr(0, pos); is_dir = true; }else{ newname = orgname; } if(is_dir){ if('/' != newname[newname.length() - 1]){ newname += "/"; } }else{ if('/' == newname[newname.length() - 1]){ is_dir = true; } } // Check derived name object. if(is_dir){ string chkname = newname.substr(0, newname.length() - 1); if(objects.end() != (iter = objects.find(chkname))){ // found "dir" object --> remove it. objects.erase(iter); } }else{ string chkname = newname + "/"; if(objects.end() != (iter = objects.find(chkname))){ // found "dir/" object --> not add new object. // and add normalization return insert_nomalized(orgname.c_str(), chkname.c_str(), true); } } // Add object if(objects.end() != (iter = objects.find(newname))){ // Found same object --> update information. (*iter).second.normalname.erase(); (*iter).second.orgname = orgname; (*iter).second.is_dir = is_dir; if(etag){ (*iter).second.etag = string(etag); // over write } }else{ // add new object s3obj_entry newobject; newobject.orgname = orgname; newobject.is_dir = is_dir; if(etag){ newobject.etag = etag; } objects[newname] = newobject; } // add normalization return insert_nomalized(orgname.c_str(), newname.c_str(), is_dir); } bool S3ObjList::insert_nomalized(const char* name, const char* normalized, bool is_dir) { if(!name || '\0' == name[0] || !normalized || '\0' == normalized[0]){ return false; } if(0 == strcmp(name, normalized)){ return true; } s3obj_t::iterator iter; if(objects.end() != (iter = objects.find(name))){ // found name --> over write (*iter).second.orgname.erase(); (*iter).second.etag.erase(); (*iter).second.normalname = normalized; (*iter).second.is_dir = is_dir; }else{ // not found --> add new object s3obj_entry newobject; newobject.normalname = normalized; newobject.is_dir = is_dir; objects[name] = newobject; } return true; } const s3obj_entry* S3ObjList::GetS3Obj(const char* name) const { s3obj_t::const_iterator iter; if(!name || '\0' == name[0]){ return NULL; } if(objects.end() == (iter = objects.find(name))){ return NULL; } return &((*iter).second); } string S3ObjList::GetOrgName(const char* name) const { const s3obj_entry* ps3obj; if(!name || '\0' == name[0]){ return string(""); } if(NULL == (ps3obj = GetS3Obj(name))){ return string(""); } return ps3obj->orgname; } string S3ObjList::GetNormalizedName(const char* name) const { const s3obj_entry* ps3obj; if(!name || '\0' == name[0]){ return string(""); } if(NULL == (ps3obj = GetS3Obj(name))){ return string(""); } if(0 == (ps3obj->normalname).length()){ return string(name); } return ps3obj->normalname; } string S3ObjList::GetETag(const char* name) const { const s3obj_entry* ps3obj; if(!name || '\0' == name[0]){ return string(""); } if(NULL == (ps3obj = GetS3Obj(name))){ return string(""); } return ps3obj->etag; } bool S3ObjList::IsDir(const char* name) const { const s3obj_entry* ps3obj; if(NULL == (ps3obj = GetS3Obj(name))){ return false; } return ps3obj->is_dir; } bool S3ObjList::GetLastName(std::string& lastname) const { bool result = false; lastname = ""; for(s3obj_t::const_iterator iter = objects.begin(); iter != objects.end(); ++iter){ if((*iter).second.orgname.length()){ if(0 > strcmp(lastname.c_str(), (*iter).second.orgname.c_str())){ lastname = (*iter).second.orgname; result = true; } }else{ if(0 > strcmp(lastname.c_str(), (*iter).second.normalname.c_str())){ lastname = (*iter).second.normalname; result = true; } } } return result; } bool S3ObjList::GetNameList(s3obj_list_t& list, bool OnlyNormalized, bool CutSlash) const { s3obj_t::const_iterator iter; for(iter = objects.begin(); objects.end() != iter; ++iter){ if(OnlyNormalized && 0 != (*iter).second.normalname.length()){ continue; } string name = (*iter).first; if(CutSlash && 1 < name.length() && '/' == name[name.length() - 1]){ // only "/" string is skio this. name = name.substr(0, name.length() - 1); } list.push_back(name); } return true; } typedef std::map s3obj_h_t; bool S3ObjList::MakeHierarchizedList(s3obj_list_t& list, bool haveSlash) { s3obj_h_t h_map; s3obj_h_t::iterator hiter; s3obj_list_t::const_iterator liter; for(liter = list.begin(); list.end() != liter; ++liter){ string strtmp = (*liter); if(1 < strtmp.length() && '/' == strtmp[strtmp.length() - 1]){ strtmp = strtmp.substr(0, strtmp.length() - 1); } h_map[strtmp] = true; // check hierarchized directory for(string::size_type pos = strtmp.find_last_of("/"); string::npos != pos; pos = strtmp.find_last_of("/")){ strtmp = strtmp.substr(0, pos); if(0 == strtmp.length() || "/" == strtmp){ break; } if(h_map.end() == h_map.find(strtmp)){ // not found h_map[strtmp] = false; } } } // check map and add lost hierarchized directory. for(hiter = h_map.begin(); hiter != h_map.end(); ++hiter){ if(false == (*hiter).second){ // add hierarchized directory. string strtmp = (*hiter).first; if(haveSlash){ strtmp += "/"; } list.push_back(strtmp); } } return true; } //------------------------------------------------------------------- // Utility functions for moving objects //------------------------------------------------------------------- MVNODE *create_mvnode(const char *old_path, const char *new_path, bool is_dir, bool normdir) { MVNODE *p; char *p_old_path; char *p_new_path; p = (MVNODE *) malloc(sizeof(MVNODE)); if (p == NULL) { printf("create_mvnode: could not allocation memory for p\n"); S3FS_FUSE_EXIT(); return NULL; } if(NULL == (p_old_path = strdup(old_path))){ free(p); printf("create_mvnode: could not allocation memory for p_old_path\n"); S3FS_FUSE_EXIT(); return NULL; } if(NULL == (p_new_path = strdup(new_path))){ free(p); free(p_old_path); printf("create_mvnode: could not allocation memory for p_new_path\n"); S3FS_FUSE_EXIT(); return NULL; } p->old_path = p_old_path; p->new_path = p_new_path; p->is_dir = is_dir; p->is_normdir = normdir; p->prev = NULL; p->next = NULL; return p; } // // Add sorted MVNODE data(Ascending order) // MVNODE *add_mvnode(MVNODE** head, MVNODE** tail, const char *old_path, const char *new_path, bool is_dir, bool normdir) { if(!head || !tail){ return NULL; } MVNODE* cur; MVNODE* mvnew; for(cur = *head; cur; cur = cur->next){ if(cur->is_dir == is_dir){ int nResult = strcmp(cur->old_path, old_path); if(0 == nResult){ // Found same old_path. return cur; }else if(0 > nResult){ // next check. // ex: cur("abc"), mvnew("abcd") // ex: cur("abc"), mvnew("abd") continue; }else{ // Add into before cur-pos. // ex: cur("abc"), mvnew("ab") // ex: cur("abc"), mvnew("abb") if(NULL == (mvnew = create_mvnode(old_path, new_path, is_dir, normdir))){ return NULL; } if(cur->prev){ (cur->prev)->next = mvnew; }else{ *head = mvnew; } mvnew->prev = cur->prev; mvnew->next = cur; cur->prev = mvnew; return mvnew; } } } // Add into tail. if(NULL == (mvnew = create_mvnode(old_path, new_path, is_dir, normdir))){ return NULL; } mvnew->prev = (*tail); if(*tail){ (*tail)->next = mvnew; } (*tail) = mvnew; if(!(*head)){ (*head) = mvnew; } return mvnew; } void free_mvnodes(MVNODE *head) { MVNODE *my_head; MVNODE *next; for(my_head = head, next = NULL; my_head; my_head = next){ next = my_head->next; free(my_head->old_path); free(my_head->new_path); free(my_head); } return; } //------------------------------------------------------------------- // Class AutoLock //------------------------------------------------------------------- AutoLock::AutoLock(pthread_mutex_t* pmutex) : auto_mutex(pmutex) { pthread_mutex_lock(auto_mutex); } AutoLock::~AutoLock() { pthread_mutex_unlock(auto_mutex); } //------------------------------------------------------------------- // Utility for UID/GID //------------------------------------------------------------------- // get user name from uid string get_username(uid_t uid) { static size_t maxlen = 0; // set onece char* pbuf; struct passwd pwinfo; struct passwd* ppwinfo = NULL; // make buffer if(0 == maxlen){ long res = sysconf(_SC_GETPW_R_SIZE_MAX); if(0 > res){ S3FS_PRN_WARN("could not get max pw length."); maxlen = 0; return string(""); } maxlen = res; } if(NULL == (pbuf = (char*)malloc(sizeof(char) * maxlen))){ S3FS_PRN_CRIT("failed to allocate memory."); return string(""); } // get group information if(0 != getpwuid_r(uid, &pwinfo, pbuf, maxlen, &ppwinfo)){ S3FS_PRN_WARN("could not get pw information."); free(pbuf); return string(""); } // check pw if(NULL == ppwinfo){ free(pbuf); return string(""); } string name = SAFESTRPTR(ppwinfo->pw_name); free(pbuf); return name; } int is_uid_inculde_group(uid_t uid, gid_t gid) { static size_t maxlen = 0; // set onece int result; char* pbuf; struct group ginfo; struct group* pginfo = NULL; // make buffer if(0 == maxlen){ long res = sysconf(_SC_GETGR_R_SIZE_MAX); if(0 > res){ S3FS_PRN_ERR("could not get max name length."); maxlen = 0; return -ERANGE; } maxlen = res; } if(NULL == (pbuf = (char*)malloc(sizeof(char) * maxlen))){ S3FS_PRN_CRIT("failed to allocate memory."); return -ENOMEM; } // get group information if(0 != (result = getgrgid_r(gid, &ginfo, pbuf, maxlen, &pginfo))){ S3FS_PRN_ERR("could not get group information."); free(pbuf); return -result; } // check group if(NULL == pginfo){ // there is not gid in group. free(pbuf); return -EINVAL; } string username = get_username(uid); char** ppgr_mem; for(ppgr_mem = pginfo->gr_mem; ppgr_mem && *ppgr_mem; ppgr_mem++){ if(username == *ppgr_mem){ // Found username in group. free(pbuf); return 1; } } free(pbuf); return 0; } //------------------------------------------------------------------- // Utility for file and directory //------------------------------------------------------------------- // safe variant of dirname // dirname clobbers path so let it operate on a tmp copy string mydirname(string path) { return string(dirname((char*)path.c_str())); } // safe variant of basename // basename clobbers path so let it operate on a tmp copy string mybasename(string path) { return string(basename((char*)path.c_str())); } // mkdir --parents int mkdirp(const string& path, mode_t mode) { string base; string component; stringstream ss(path); while (getline(ss, component, '/')) { base += "/" + component; struct stat st; if(0 == stat(base.c_str(), &st)){ if(!S_ISDIR(st.st_mode)){ return EPERM; } }else{ if(0 != mkdir(base.c_str(), mode)){ return errno; } } } return 0; } bool check_exist_dir_permission(const char* dirpath) { if(!dirpath || '\0' == dirpath[0]){ return false; } // exists struct stat st; if(0 != stat(dirpath, &st)){ if(ENOENT == errno){ // dir does not exitst return true; } if(EACCES == errno){ // could not access directory return false; } // somthing error occured return false; } // check type if(!S_ISDIR(st.st_mode)){ // path is not directory return false; } // check permission uid_t myuid = geteuid(); if(myuid == st.st_uid){ if(S_IRWXU != (st.st_mode & S_IRWXU)){ return false; } }else{ if(1 == is_uid_inculde_group(myuid, st.st_gid)){ if(S_IRWXG != (st.st_mode & S_IRWXG)){ return false; } }else{ if(S_IRWXO != (st.st_mode & S_IRWXO)){ return false; } } } return true; } bool delete_files_in_dir(const char* dir, bool is_remove_own) { DIR* dp; struct dirent* dent; if(NULL == (dp = opendir(dir))){ S3FS_PRN_ERR("could not open dir(%s) - errno(%d)", dir, errno); return false; } for(dent = readdir(dp); dent; dent = readdir(dp)){ if(0 == strcmp(dent->d_name, "..") || 0 == strcmp(dent->d_name, ".")){ continue; } string fullpath = dir; fullpath += "/"; fullpath += dent->d_name; struct stat st; if(0 != lstat(fullpath.c_str(), &st)){ S3FS_PRN_ERR("could not get stats of file(%s) - errno(%d)", fullpath.c_str(), errno); closedir(dp); return false; } if(S_ISDIR(st.st_mode)){ // dir -> Reentrant if(!delete_files_in_dir(fullpath.c_str(), true)){ S3FS_PRN_ERR("could not remove sub dir(%s) - errno(%d)", fullpath.c_str(), errno); closedir(dp); return false; } }else{ if(0 != unlink(fullpath.c_str())){ S3FS_PRN_ERR("could not remove file(%s) - errno(%d)", fullpath.c_str(), errno); closedir(dp); return false; } } } closedir(dp); if(is_remove_own && 0 != rmdir(dir)){ S3FS_PRN_ERR("could not remove dir(%s) - errno(%d)", dir, errno); return false; } return true; } //------------------------------------------------------------------- // Utility functions for convert //------------------------------------------------------------------- time_t get_mtime(const char *s) { return static_cast(s3fs_strtoofft(s)); } time_t get_mtime(headers_t& meta, bool overcheck) { headers_t::const_iterator iter; if(meta.end() == (iter = meta.find("x-amz-meta-mtime"))){ if(overcheck){ return get_lastmodified(meta); } return 0; } return get_mtime((*iter).second.c_str()); } off_t get_size(const char *s) { return s3fs_strtoofft(s); } off_t get_size(headers_t& meta) { headers_t::const_iterator iter; if(meta.end() == (iter = meta.find("Content-Length"))){ return 0; } return get_size((*iter).second.c_str()); } mode_t get_mode(const char *s) { return static_cast(s3fs_strtoofft(s)); } mode_t get_mode(headers_t& meta, const char* path, bool checkdir, bool forcedir) { mode_t mode = 0; bool isS3sync = false; headers_t::const_iterator iter; if(meta.end() != (iter = meta.find("x-amz-meta-mode"))){ mode = get_mode((*iter).second.c_str()); }else{ if(meta.end() != (iter = meta.find("x-amz-meta-permissions"))){ // for s3sync mode = get_mode((*iter).second.c_str()); isS3sync = true; } } // Checking the bitmask, if the last 3 bits are all zero then process as a regular // file type (S_IFDIR or S_IFREG), otherwise return mode unmodified so that S_IFIFO, // S_IFSOCK, S_IFCHR, S_IFLNK and S_IFBLK devices can be processed properly by fuse. if(!(mode & S_IFMT)){ if(!isS3sync){ if(checkdir){ if(forcedir){ mode |= S_IFDIR; }else{ if(meta.end() != (iter = meta.find("Content-Type"))){ string strConType = (*iter).second; if(strConType == "application/x-directory"){ mode |= S_IFDIR; }else if(path && 0 < strlen(path) && '/' == path[strlen(path) - 1]){ if(strConType == "binary/octet-stream" || strConType == "application/octet-stream"){ mode |= S_IFDIR; }else{ mode |= S_IFREG; } }else{ mode |= S_IFREG; } }else{ mode |= S_IFREG; } } } }else{ if(!checkdir){ // cut dir/reg flag. mode &= ~S_IFDIR; mode &= ~S_IFREG; } } } return mode; } uid_t get_uid(const char *s) { return static_cast(s3fs_strtoofft(s)); } uid_t get_uid(headers_t& meta) { headers_t::const_iterator iter; if(meta.end() == (iter = meta.find("x-amz-meta-uid"))){ if(meta.end() == (iter = meta.find("x-amz-meta-owner"))){ // for s3sync return 0; } } return get_uid((*iter).second.c_str()); } gid_t get_gid(const char *s) { return static_cast(s3fs_strtoofft(s)); } gid_t get_gid(headers_t& meta) { headers_t::const_iterator iter; if(meta.end() == (iter = meta.find("x-amz-meta-gid"))){ if(meta.end() == (iter = meta.find("x-amz-meta-group"))){ // for s3sync return 0; } } return get_gid((*iter).second.c_str()); } blkcnt_t get_blocks(off_t size) { return size / 512 + 1; } time_t cvtIAMExpireStringToTime(const char* s) { struct tm tm; if(!s){ return 0L; } memset(&tm, 0, sizeof(struct tm)); strptime(s, "%Y-%m-%dT%H:%M:%S", &tm); return timegm(&tm); // GMT } time_t get_lastmodified(const char* s) { struct tm tm; if(!s){ return 0L; } memset(&tm, 0, sizeof(struct tm)); strptime(s, "%a, %d %b %Y %H:%M:%S %Z", &tm); return timegm(&tm); // GMT } time_t get_lastmodified(headers_t& meta) { headers_t::const_iterator iter; if(meta.end() == (iter = meta.find("Last-Modified"))){ return 0; } return get_lastmodified((*iter).second.c_str()); } // // Returns it whether it is an object with need checking in detail. // If this function returns true, the object is possible to be directory // and is needed checking detail(searching sub object). // bool is_need_check_obj_detail(headers_t& meta) { headers_t::const_iterator iter; // directory object is Content-Length as 0. if(0 != get_size(meta)){ return false; } // if the object has x-amz-meta information, checking is no more. if(meta.end() != meta.find("x-amz-meta-mode") || meta.end() != meta.find("x-amz-meta-mtime") || meta.end() != meta.find("x-amz-meta-uid") || meta.end() != meta.find("x-amz-meta-gid") || meta.end() != meta.find("x-amz-meta-owner") || meta.end() != meta.find("x-amz-meta-group") || meta.end() != meta.find("x-amz-meta-permissions") ) { return false; } // if there is not Content-Type, or Content-Type is "x-directory", // checking is no more. if(meta.end() == (iter = meta.find("Content-Type"))){ return false; } if("application/x-directory" == (*iter).second){ return false; } return true; } //------------------------------------------------------------------- // Help //------------------------------------------------------------------- void show_usage (void) { printf("Usage: %s BUCKET:[PATH] MOUNTPOINT [OPTION]...\n", program_name.c_str()); } void show_help (void) { show_usage(); printf( "\n" "Mount an Amazon S3 bucket as a file system.\n" "\n" " General forms for s3fs and FUSE/mount options:\n" " -o opt[,opt...]\n" " -o opt [-o opt] ...\n" "\n" "s3fs Options:\n" "\n" " Most s3fs options are given in the form where \"opt\" is:\n" "\n" " =\n" "\n" " default_acl (default=\"private\")\n" " - the default canned acl to apply to all written s3 objects\n" " see http://aws.amazon.com/documentation/s3/ for the \n" " full list of canned acls\n" "\n" " retries (default=\"2\")\n" " - number of times to retry a failed s3 transaction\n" "\n" " use_cache (default=\"\" which means disabled)\n" " - local folder to use for local file cache\n" "\n" " del_cache (delete local file cache)\n" " - delete local file cache when s3fs starts and exits.\n" "\n" " storage_class (default=\"standard\")\n" " - store object with specified storage class. Possible values:\n" " standard, standard_ia, and reduced_redundancy.\n" "\n" " use_sse (default is disable)\n" " - Specify three type Amazon's Server-Site Encryption: SSE-S3,\n" " SSE-C or SSE-KMS. SSE-S3 uses Amazon S3-managed encryption\n" " keys, SSE-C uses customer-provided encryption keys, and\n" " SSE-KMS uses the master key which you manage in AWS KMS.\n" " You can specify \"use_sse\" or \"use_sse=1\" enables SSE-S3\n" " type(use_sse=1 is old type parameter).\n" " Case of setting SSE-C, you can specify \"use_sse=custom\",\n" " \"use_sse=custom:\" or\n" " \"use_sse=\"(only \n" " specified is old type parameter). You can use \"c\" for\n" " short \"custom\".\n" " The custom key file must be 600 permission. The file can\n" " have some lines, each line is one SSE-C key. The first line\n" " in file is used as Customer-Provided Encryption Keys for\n" " uploading and changing headers etc. If there are some keys\n" " after first line, those are used downloading object which\n" " are encrypted by not first key. So that, you can keep all\n" " SSE-C keys in file, that is SSE-C key history.\n" " If you specify \"custom\"(\"c\") without file path, you\n" " need to set custom key by load_sse_c option or AWSSSECKEYS\n" " environment.(AWSSSECKEYS environment has some SSE-C keys\n" " with \":\" separator.) This option is used to decide the\n" " SSE type. So that if you do not want to encrypt a object\n" " object at uploading, but you need to decrypt encrypted\n" " object at downloaing, you can use load_sse_c option instead\n" " of this option.\n" " For setting SSE-KMS, specify \"use_sse=kmsid\" or\n" " \"use_sse=kmsid:\". You can use \"k\" for short \"kmsid\".\n" " If you san specify SSE-KMS type with your in AWS\n" " KMS, you can set it after \"kmsid:\"(or \"k:\"). If you\n" " specify only \"kmsid\"(\"k\"), you need to set AWSSSEKMSID\n" " environment which value is . You must be careful\n" " about that you can not use the KMS id which is not same EC2\n" " region.\n" "\n" " load_sse_c - specify SSE-C keys\n" " Specify the custom-provided encription keys file path for decrypting\n" " at duwnloading.\n" " If you use the custom-provided encription key at uploading, you\n" " specify with \"use_sse=custom\". The file has many lines, one line\n" " means one custom key. So that you can keep all SSE-C keys in file,\n" " that is SSE-C key history. AWSSSECKEYS environment is as same as this\n" " file contents.\n" "\n" " public_bucket (default=\"\" which means disabled)\n" " - anonymously mount a public bucket when set to 1\n" "\n" " passwd_file (default=\"\")\n" " - specify which s3fs password file to use\n" "\n" " ahbe_conf (default=\"\" which means disabled)\n" " - This option specifies the configuration file path which\n" " file is the additional HTTP header by file(object) extension.\n" " The configuration file format is below:\n" " -----------\n" " line = [file suffix] HTTP-header [HTTP-values]\n" " file suffix = file(object) suffix, if this field is empty,\n" " it means \"*\"(all object).\n" " HTTP-header = additional HTTP header name\n" " HTTP-values = additional HTTP header value\n" " -----------\n" " Sample:\n" " -----------\n" " .gz Content-Encoding gzip\n" " .Z Content-Encoding compress\n" " X-S3FS-MYHTTPHEAD myvalue\n" " -----------\n" " A sample configuration file is uploaded in \"test\" directory.\n" " If you specify this option for set \"Content-Encoding\" HTTP \n" " header, please take care for RFC 2616.\n" "\n" " connect_timeout (default=\"300\" seconds)\n" " - time to wait for connection before giving up\n" "\n" " readwrite_timeout (default=\"60\" seconds)\n" " - time to wait between read/write activity before giving up\n" "\n" " max_stat_cache_size (default=\"1000\" entries (about 4MB))\n" " - maximum number of entries in the stat cache\n" "\n" " stat_cache_expire (default is no expire)\n" " - specify expire time(seconds) for entries in the stat cache.\n" "\n" " enable_noobj_cache (default is disable)\n" " - enable cache entries for the object which does not exist.\n" " s3fs always has to check whether file(or sub directory) exists \n" " under object(path) when s3fs does some command, since s3fs has \n" " recognized a directory which does not exist and has files or \n" " sub directories under itself. It increases ListBucket request \n" " and makes performance bad.\n" " You can specify this option for performance, s3fs memorizes \n" " in stat cache that the object(file or directory) does not exist.\n" "\n" " no_check_certificate\n" " - server certificate won't be checked against the available \n" " certificate authorities.\n" "\n" " nodnscache (disable dns cache)\n" " - s3fs is always using dns cache, this option make dns cache disable.\n" "\n" " nosscache (disable ssl session cache)\n" " - s3fs is always using ssl session cache, this option make ssl \n" " session cache disable.\n" "\n" " multireq_max (default=\"20\")\n" " - maximum number of parallel request for listing objects.\n" "\n" " parallel_count (default=\"5\")\n" " - number of parallel request for uploading big objects.\n" " s3fs uploads large object(over 20MB) by multipart post request, \n" " and sends parallel requests.\n" " This option limits parallel request count which s3fs requests \n" " at once. It is necessary to set this value depending on a CPU \n" " and a network band.\n" "\n" " multipart_size (default=\"10\")\n" " - part size, in MB, for each multipart request.\n" "\n" " singlepart_copy_limit (default=\"5120\")\n" " - maximum size, in MB, of a single-part copy before trying \n" " multipart copy.\n" "\n" " fd_page_size (default=\"52428800\"(50MB))\n" " - number of internal management page size for each file descriptor.\n" " For delayed reading and writing by s3fs, s3fs manages pages which \n" " is separated from object. Each pages has a status that data is \n" " already loaded(or not loaded yet).\n" " This option should not be changed when you don't have a trouble \n" " with performance.\n" "\n" " url (default=\"http://s3.amazonaws.com\")\n" " - sets the url to use to access amazon s3\n" "\n" " endpoint (default=\"us-east-1\")\n" " - sets the endpoint to use on signature version 4\n" " If this option is not specified, s3fs uses \"us-east-1\" region as\n" " the default. If the s3fs could not connect to the region specified\n" " by this option, s3fs could not run. But if you do not specify this\n" " option, and if you can not connect with the default region, s3fs\n" " will retry to automatically connect to the other region. So s3fs\n" " can know the correct region name, because s3fs can find it in an\n" " error from the S3 server.\n" "\n" " sigv2 (default is signature version 4)\n" " - sets signing AWS requests by sing Signature Version 2\n" "\n" " mp_umask (default is \"0000\")\n" " - sets umask for the mount point directory.\n" " If allow_other option is not set, s3fs allows access to the mount\n" " point only to the owner. In the opposite case s3fs allows access\n" " to all users as the default. But if you set the allow_other with\n" " this option, you can control the permissions of the\n" " mount point by this option like umask.\n" "\n" " nomultipart (disable multipart uploads)\n" "\n" " enable_content_md5 (default is disable)\n" " - ensure data integrity during writes with MD5 hash.\n" "\n" " iam_role (default is no role)\n" " - set the IAM Role that will supply the credentials from the \n" " instance meta-data.\n" "\n" " noxmlns (disable registering xml name space)\n" " disable registering xml name space for response of \n" " ListBucketResult and ListVersionsResult etc. Default name \n" " space is looked up from \"http://s3.amazonaws.com/doc/2006-03-01\".\n" " This option should not be specified now, because s3fs looks up\n" " xmlns automatically after v1.66.\n" "\n" " nocopyapi (for other incomplete compatibility object storage)\n" " For a distributed object storage which is compatibility S3\n" " API without PUT(copy api).\n" " If you set this option, s3fs do not use PUT with \n" " \"x-amz-copy-source\"(copy api). Because traffic is increased\n" " 2-3 times by this option, we do not recommend this.\n" "\n" " norenameapi (for other incomplete compatibility object storage)\n" " For a distributed object storage which is compatibility S3\n" " API without PUT(copy api).\n" " This option is a subset of nocopyapi option. The nocopyapi\n" " option does not use copy-api for all command(ex. chmod, chown,\n" " touch, mv, etc), but this option does not use copy-api for\n" " only rename command(ex. mv). If this option is specified with\n" " nocopyapi, then s3fs ignores it.\n" "\n" " use_path_request_style (use legacy API calling style)\n" " Enble compatibility with S3-like APIs which do not support\n" " the virtual-host request style, by using the older path request\n" " style.\n" "\n" " dbglevel (default=\"crit\")\n" " Set the debug message level. set value as crit(critical), err\n" " (error), warn(warning), info(information) to debug level.\n" " default debug level is critical. If s3fs run with \"-d\" option,\n" " the debug level is set information. When s3fs catch the signal\n" " SIGUSR2, the debug level is bumpup.\n" "\n" " curldbg - put curl debug message\n" " Put the debug message from libcurl when this option is specified.\n" "\n" "FUSE/mount Options:\n" "\n" " Most of the generic mount options described in 'man mount' are\n" " supported (ro, rw, suid, nosuid, dev, nodev, exec, noexec, atime,\n" " noatime, sync async, dirsync). Filesystems are mounted with\n" " '-onodev,nosuid' by default, which can only be overridden by a\n" " privileged user.\n" " \n" " There are many FUSE specific mount options that can be specified.\n" " e.g. allow_other See the FUSE's README for the full set.\n" "\n" "Miscellaneous Options:\n" "\n" " -h, --help Output this help.\n" " --version Output version info.\n" " -d --debug Turn on DEBUG messages to syslog. Specifying -d\n" " twice turns on FUSE debug messages to STDOUT.\n" " -f FUSE foreground option - do not run as daemon.\n" " -s FUSE singlethread option\n" " disable multi-threaded operation\n" "\n" "\n" "s3fs home page: \n" ); return; } void show_version(void) { printf( "Amazon Simple Storage Service File System V%s(commit:%s) with %s\n" "Copyright (C) 2010 Randy Rizun \n" "License GPL2: GNU GPL version 2 \n" "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n", VERSION, COMMIT_HASH_VAL, s3fs_crypt_lib_name()); return; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/s3fs_util.h000066400000000000000000000104461260476112200201610ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef S3FS_S3FS_UTIL_H_ #define S3FS_S3FS_UTIL_H_ //------------------------------------------------------------------- // Typedef //------------------------------------------------------------------- // // Struct // struct s3obj_entry{ std::string normalname; // normalized name: if empty, object is nomalized name. std::string orgname; // original name: if empty, object is original name. std::string etag; bool is_dir; s3obj_entry() : is_dir(false) {} }; typedef std::map s3obj_t; typedef std::list s3obj_list_t; // // Class // class S3ObjList { private: s3obj_t objects; private: bool insert_nomalized(const char* name, const char* normalized, bool is_dir); const s3obj_entry* GetS3Obj(const char* name) const; s3obj_t::const_iterator begin(void) const { return objects.begin(); } s3obj_t::const_iterator end(void) const { return objects.end(); } public: S3ObjList() {} ~S3ObjList() {} bool IsEmpty(void) const { return objects.empty(); } bool insert(const char* name, const char* etag = NULL, bool is_dir = false); std::string GetOrgName(const char* name) const; std::string GetNormalizedName(const char* name) const; std::string GetETag(const char* name) const; bool IsDir(const char* name) const; bool GetNameList(s3obj_list_t& list, bool OnlyNormalized = true, bool CutSlash = true) const; bool GetLastName(std::string& lastname) const; static bool MakeHierarchizedList(s3obj_list_t& list, bool haveSlash); }; typedef struct mvnode { char *old_path; char *new_path; bool is_dir; bool is_normdir; struct mvnode *prev; struct mvnode *next; } MVNODE; class AutoLock { private: pthread_mutex_t* auto_mutex; public: explicit AutoLock(pthread_mutex_t* pmutex); ~AutoLock(); }; //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- std::string get_realpath(const char *path); MVNODE *create_mvnode(const char *old_path, const char *new_path, bool is_dir, bool normdir = false); MVNODE *add_mvnode(MVNODE** head, MVNODE** tail, const char *old_path, const char *new_path, bool is_dir, bool normdir = false); void free_mvnodes(MVNODE *head); std::string get_username(uid_t uid); int is_uid_inculde_group(uid_t uid, gid_t gid); std::string mydirname(std::string path); std::string mybasename(std::string path); int mkdirp(const std::string& path, mode_t mode); bool check_exist_dir_permission(const char* dirpath); bool delete_files_in_dir(const char* dir, bool is_remove_own); time_t get_mtime(const char *s); time_t get_mtime(headers_t& meta, bool overcheck = true); off_t get_size(const char *s); off_t get_size(headers_t& meta); mode_t get_mode(const char *s); mode_t get_mode(headers_t& meta, const char* path = NULL, bool checkdir = false, bool forcedir = false); uid_t get_uid(const char *s); uid_t get_uid(headers_t& meta); gid_t get_gid(const char *s); gid_t get_gid(headers_t& meta); blkcnt_t get_blocks(off_t size); time_t cvtIAMExpireStringToTime(const char* s); time_t get_lastmodified(const char* s); time_t get_lastmodified(headers_t& meta); bool is_need_check_obj_detail(headers_t& meta); void show_usage(void); void show_help(void); void show_version(void); #endif // S3FS_S3FS_UTIL_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/string_util.cpp000066400000000000000000000227301260476112200211430ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include "common.h" #include "string_util.h" using namespace std; static const char hexAlphabet[] = "0123456789ABCDEF"; off_t s3fs_strtoofft(const char* str, bool is_base_16) { if(!str || '\0' == *str){ return 0; } off_t result; bool chk_space; bool chk_base16_prefix; for(result = 0, chk_space = false, chk_base16_prefix = false; '\0' != *str; str++){ // check head space if(!chk_space && isspace(*str)){ continue; }else if(!chk_space){ chk_space = true; } // check prefix for base 16 if(!chk_base16_prefix){ chk_base16_prefix = true; if('0' == *str && ('x' == str[1] || 'X' == str[1])){ is_base_16 = true; str++; continue; } } // check like isalnum and set data result *= (is_base_16 ? 16 : 10); if('0' <= *str || '9' < *str){ result += static_cast(*str - '0'); }else if(is_base_16){ if('A' <= *str && *str <= 'F'){ result += static_cast(*str - 'A' + 0x0a); }else if('a' <= *str && *str <= 'f'){ result += static_cast(*str - 'a' + 0x0a); }else{ return 0; } }else{ return 0; } } return result; } string lower(string s) { // change each character of the string to lower case for(unsigned int i = 0; i < s.length(); i++){ s[i] = tolower(s[i]); } return s; } string trim_left(const string &s, const string &t /* = SPACES */) { string d(s); return d.erase(0, s.find_first_not_of(t)); } string trim_right(const string &s, const string &t /* = SPACES */) { string d(s); string::size_type i(d.find_last_not_of(t)); if(i == string::npos){ return ""; }else{ return d.erase(d.find_last_not_of(t) + 1); } } string trim(const string &s, const string &t /* = SPACES */) { string d(s); return trim_left(trim_right(d, t), t); } /** * urlEncode a fuse path, * taking into special consideration "/", * otherwise regular urlEncode. */ string urlEncode(const string &s) { string result; for (unsigned i = 0; i < s.length(); ++i) { char c = s[i]; if (c == '/' // Note- special case for fuse paths... || c == '.' || c == '-' || c == '_' || c == '~' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { result += c; } else { result += "%"; result += hexAlphabet[static_cast(c) / 16]; result += hexAlphabet[static_cast(c) % 16]; } } return result; } /** * urlEncode a fuse path, * taking into special consideration "/", * otherwise regular urlEncode. */ string urlEncode2(const string &s) { string result; for (unsigned i = 0; i < s.length(); ++i) { char c = s[i]; if (c == '=' // Note- special case for fuse paths... || c == '&' // Note- special case for s3... || c == '%' || c == '.' || c == '-' || c == '_' || c == '~' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { result += c; } else { result += "%"; result += hexAlphabet[static_cast(c) / 16]; result += hexAlphabet[static_cast(c) % 16]; } } return result; } string urlDecode(const string& s) { string result; for(unsigned i = 0; i < s.length(); ++i){ if(s[i] != '%'){ result += s[i]; }else{ char ch = 0; if(s.length() <= ++i){ break; // wrong format. } ch += ('0' <= s[i] && s[i] <= '9') ? (s[i] - '0') : ('A' <= s[i] && s[i] <= 'F') ? (s[i] - 'A' + 0x0a) : ('a' <= s[i] && s[i] <= 'f') ? (s[i] - 'a' + 0x0a) : 0x00; if(s.length() <= ++i){ break; // wrong format. } ch *= 16; ch += ('0' <= s[i] && s[i] <= '9') ? (s[i] - '0') : ('A' <= s[i] && s[i] <= 'F') ? (s[i] - 'A' + 0x0a) : ('a' <= s[i] && s[i] <= 'f') ? (s[i] - 'a' + 0x0a) : 0x00; result += ch; } } return result; } bool takeout_str_dquart(string& str) { size_t pos; // '"' for start if(string::npos != (pos = str.find_first_of("\""))){ str = str.substr(pos + 1); // '"' for end if(string::npos == (pos = str.find_last_of("\""))){ return false; } str = str.substr(0, pos); if(string::npos != str.find_first_of("\"")){ return false; } } return true; } // // ex. target="http://......?keyword=value&..." // bool get_keyword_value(string& target, const char* keyword, string& value) { if(!keyword){ return false; } size_t spos; size_t epos; if(string::npos == (spos = target.find(keyword))){ return false; } spos += strlen(keyword); if('=' != target.at(spos)){ return false; } spos++; if(string::npos == (epos = target.find('&', spos))){ value = target.substr(spos); }else{ value = target.substr(spos, (epos - spos)); } return true; } /** * Returns the current date * in a format suitable for a HTTP request header. */ string get_date_rfc850() { char buf[100]; time_t t = time(NULL); strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&t)); return buf; } void get_date_sigv3(string& date, string& date8601) { time_t tm = time(NULL); date = get_date_string(tm); date8601 = get_date_iso8601(tm); } string get_date_string(time_t tm) { char buf[100]; strftime(buf, sizeof(buf), "%Y%m%d", gmtime(&tm)); return buf; } string get_date_iso8601(time_t tm) { char buf[100]; strftime(buf, sizeof(buf), "%Y%m%dT%H%M%SZ", gmtime(&tm)); return buf; } std::string s3fs_hex(const unsigned char* input, size_t length) { std::string hex; for(size_t pos = 0; pos < length; ++pos){ char hexbuf[3]; snprintf(hexbuf, 3, "%02x", input[pos]); hex += hexbuf; } return hex; } char* s3fs_base64(const unsigned char* input, size_t length) { static const char* base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; char* result; if(!input || 0 >= length){ return NULL; } if(NULL == (result = (char*)malloc((((length / 3) + 1) * 4 + 1) * sizeof(char)))){ return NULL; // ENOMEM } unsigned char parts[4]; size_t rpos; size_t wpos; for(rpos = 0, wpos = 0; rpos < length; rpos += 3){ parts[0] = (input[rpos] & 0xfc) >> 2; parts[1] = ((input[rpos] & 0x03) << 4) | ((((rpos + 1) < length ? input[rpos + 1] : 0x00) & 0xf0) >> 4); parts[2] = (rpos + 1) < length ? (((input[rpos + 1] & 0x0f) << 2) | ((((rpos + 2) < length ? input[rpos + 2] : 0x00) & 0xc0) >> 6)) : 0x40; parts[3] = (rpos + 2) < length ? (input[rpos + 2] & 0x3f) : 0x40; result[wpos++] = base[parts[0]]; result[wpos++] = base[parts[1]]; result[wpos++] = base[parts[2]]; result[wpos++] = base[parts[3]]; } result[wpos] = '\0'; return result; } inline unsigned char char_decode64(const char ch) { unsigned char by; if('A' <= ch && ch <= 'Z'){ // A - Z by = static_cast(ch - 'A'); }else if('a' <= ch && ch <= 'z'){ // a - z by = static_cast(ch - 'a' + 26); }else if('0' <= ch && ch <= '9'){ // 0 - 9 by = static_cast(ch - '0' + 52); }else if('+' == ch){ // + by = 62; }else if('/' == ch){ // / by = 63; }else if('=' == ch){ // = by = 64; }else{ // something wrong by = UCHAR_MAX; } return by; } unsigned char* s3fs_decode64(const char* input, size_t* plength) { unsigned char* result; if(!input || 0 == strlen(input) || !plength){ return NULL; } if(NULL == (result = (unsigned char*)malloc((strlen(input) + 1)))){ return NULL; // ENOMEM } unsigned char parts[4]; size_t input_len = strlen(input); size_t rpos; size_t wpos; for(rpos = 0, wpos = 0; rpos < input_len; rpos += 4){ parts[0] = char_decode64(input[rpos]); parts[1] = (rpos + 1) < input_len ? char_decode64(input[rpos + 1]) : 64; parts[2] = (rpos + 2) < input_len ? char_decode64(input[rpos + 2]) : 64; parts[3] = (rpos + 3) < input_len ? char_decode64(input[rpos + 3]) : 64; result[wpos++] = ((parts[0] << 2) & 0xfc) | ((parts[1] >> 4) & 0x03); if(64 == parts[2]){ break; } result[wpos++] = ((parts[1] << 4) & 0xf0) | ((parts[2] >> 2) & 0x0f); if(64 == parts[3]){ break; } result[wpos++] = ((parts[2] << 6) & 0xc0) | (parts[3] & 0x3f); } result[wpos] = '\0'; *plength = wpos; return result; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/string_util.h000066400000000000000000000045601260476112200206110ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2007-2008 Randy Rizun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef S3FS_STRING_UTIL_H_ #define S3FS_STRING_UTIL_H_ /* * A collection of string utilities for manipulating URLs and HTTP responses. */ #include #include #include #include #include #define SPACES " \t\r\n" #define STR2NCMP(str1, str2) strncmp(str1, str2, strlen(str2)) template std::string str(T value) { std::stringstream s; s << value; return s.str(); } off_t s3fs_strtoofft(const char* str, bool is_base_16 = false); std::string trim_left(const std::string &s, const std::string &t = SPACES); std::string trim_right(const std::string &s, const std::string &t = SPACES); std::string trim(const std::string &s, const std::string &t = SPACES); std::string lower(std::string s); std::string get_date_rfc850(void); void get_date_sigv3(std::string& date, std::string& date8601); std::string get_date_string(time_t tm); std::string get_date_iso8601(time_t tm); std::string urlEncode(const std::string &s); std::string urlEncode2(const std::string &s); std::string urlDecode(const std::string& s); bool takeout_str_dquart(std::string& str); bool get_keyword_value(std::string& target, const char* keyword, std::string& value); std::string s3fs_hex(const unsigned char* input, size_t length); char* s3fs_base64(const unsigned char* input, size_t length); unsigned char* s3fs_decode64(const char* input, size_t* plength); #endif // S3FS_STRING_UTIL_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ s3fs-fuse-1.79+git90-g8f11507/src/test_string_util.cpp000066400000000000000000000066771260476112200222160ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2014 Andrew Gaul * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include "string_util.h" #include "test_util.h" void test_trim() { ASSERT_EQUALS(std::string("1234"), trim(" 1234 ")); ASSERT_EQUALS(std::string("1234"), trim("1234 ")); ASSERT_EQUALS(std::string("1234"), trim(" 1234")); ASSERT_EQUALS(std::string("1234"), trim("1234")); ASSERT_EQUALS(std::string("1234 "), trim_left(" 1234 ")); ASSERT_EQUALS(std::string("1234 "), trim_left("1234 ")); ASSERT_EQUALS(std::string("1234"), trim_left(" 1234")); ASSERT_EQUALS(std::string("1234"), trim_left("1234")); ASSERT_EQUALS(std::string(" 1234"), trim_right(" 1234 ")); ASSERT_EQUALS(std::string("1234"), trim_right("1234 ")); ASSERT_EQUALS(std::string(" 1234"), trim_right(" 1234")); ASSERT_EQUALS(std::string("1234"), trim_right("1234")); ASSERT_EQUALS(std::string("0"), str(0)); ASSERT_EQUALS(std::string("1"), str(1)); ASSERT_EQUALS(std::string("-1"), str(-1)); ASSERT_EQUALS(std::string("9223372036854775807"), str(std::numeric_limits::max())); ASSERT_EQUALS(std::string("-9223372036854775808"), str(std::numeric_limits::min())); ASSERT_EQUALS(std::string("0"), str(std::numeric_limits::min())); ASSERT_EQUALS(std::string("18446744073709551615"), str(std::numeric_limits::max())); } void test_base64() { size_t len; ASSERT_STREQUALS(s3fs_base64(NULL, 0), NULL); ASSERT_STREQUALS(reinterpret_cast(s3fs_decode64(NULL, &len)), NULL); ASSERT_STREQUALS(s3fs_base64(reinterpret_cast(""), 0), NULL); ASSERT_STREQUALS(reinterpret_cast(s3fs_decode64("", &len)), NULL); ASSERT_STREQUALS(s3fs_base64(reinterpret_cast("1"), 1), "MQ=="); ASSERT_STREQUALS(reinterpret_cast(s3fs_decode64("MQ==", &len)), "1"); ASSERT_EQUALS(len, static_cast(1)); ASSERT_STREQUALS(s3fs_base64(reinterpret_cast("12"), 2), "MTI="); ASSERT_STREQUALS(reinterpret_cast(s3fs_decode64("MTI=", &len)), "12"); ASSERT_EQUALS(len, static_cast(2)); ASSERT_STREQUALS(s3fs_base64(reinterpret_cast("123"), 3), "MTIz"); ASSERT_STREQUALS(reinterpret_cast(s3fs_decode64("MTIz", &len)), "123"); ASSERT_EQUALS(len, static_cast(3)); ASSERT_STREQUALS(s3fs_base64(reinterpret_cast("1234"), 4), "MTIzNA=="); ASSERT_STREQUALS(reinterpret_cast(s3fs_decode64("MTIzNA==", &len)), "1234"); ASSERT_EQUALS(len, static_cast(4)); // TODO: invalid input } int main(int argc, char *argv[]) { test_trim(); test_base64(); return 0; } s3fs-fuse-1.79+git90-g8f11507/src/test_util.h000066400000000000000000000030041260476112200202520ustar00rootroot00000000000000/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright 2014 Andrew Gaul * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include template void assert_equals(const T &x, const T &y, const char *file, int line) { if (x != y) { std::cerr << x << " != " << y << " at " << file << ":" << line << std::endl; std::exit(1); } } void assert_strequals(const char *x, const char *y, const char *file, int line) { if(x == NULL && y == NULL){ return; } else if((x == NULL || y == NULL) || strcmp(x, y) != 0){ std::cerr << x << " != " << y << " at " << file << ":" << line << std::endl; std::exit(1); } } #define ASSERT_EQUALS(x, y) \ assert_equals((x), (y), __FILE__, __LINE__) #define ASSERT_STREQUALS(x, y) \ assert_strequals((x), (y), __FILE__, __LINE__) s3fs-fuse-1.79+git90-g8f11507/test/000077500000000000000000000000001260476112200162605ustar00rootroot00000000000000s3fs-fuse-1.79+git90-g8f11507/test/Makefile.am000066400000000000000000000022161260476112200203150ustar00rootroot00000000000000###################################################################### # s3fs - FUSE-based file system backed by Amazon S3 # # Copyright 2007-2008 Randy Rizun # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ###################################################################### TESTS=small-integration-test.sh EXTRA_DIST = \ integration-test-common.sh \ require-root.sh \ small-integration-test.sh \ mergedir.sh \ sample_delcache.sh \ sample_ahbe.conf testdir = test s3fs-fuse-1.79+git90-g8f11507/test/integration-test-common.sh000066400000000000000000000012161260476112200234020ustar00rootroot00000000000000#!/bin/bash -e set -x S3FS=../src/s3fs : ${S3FS_CREDENTIALS_FILE:="passwd-s3fs"} : ${TEST_BUCKET_1:="s3fs-integration-test"} TEST_BUCKET_MOUNT_POINT_1=${TEST_BUCKET_1} if [ ! -f "$S3FS_CREDENTIALS_FILE" ] then echo "Missing credentials file: $S3FS_CREDENTIALS_FILE" exit 1 fi chmod 600 "$S3FS_CREDENTIALS_FILE" S3PROXY_VERSION="1.4.0" S3PROXY_BINARY=${S3PROXY_BINARY-"s3proxy-${S3PROXY_VERSION}"} if [ -n "${S3PROXY_BINARY}" ] && [ ! -e "${S3PROXY_BINARY}" ]; then wget "https://github.com/andrewgaul/s3proxy/releases/download/s3proxy-${S3PROXY_VERSION}/s3proxy" \ --quiet -O "${S3PROXY_BINARY}" chmod +x "${S3PROXY_BINARY}" fi s3fs-fuse-1.79+git90-g8f11507/test/integration-test-main.sh000077500000000000000000000213241260476112200230430ustar00rootroot00000000000000#!/bin/bash set -o xtrace set -o errexit COMMON=integration-test-common.sh source $COMMON # Configuration TEST_TEXT="HELLO WORLD" TEST_TEXT_FILE=test-s3fs.txt TEST_DIR=testdir ALT_TEST_TEXT_FILE=test-s3fs-ALT.txt TEST_TEXT_FILE_LENGTH=15 BIG_FILE=big-file-s3fs.txt BIG_FILE_LENGTH=$((25 * 1024 * 1024)) function mk_test_file { if [ $# == 0 ]; then TEXT=$TEST_TEXT else TEXT=$1 fi echo $TEXT > $TEST_TEXT_FILE if [ ! -e $TEST_TEXT_FILE ] then echo "Could not create file ${TEST_TEXT_FILE}, it does not exist" exit 1 fi } function rm_test_file { if [ $# == 0 ]; then FILE=$TEST_TEXT_FILE else FILE=$1 fi rm -f $FILE if [ -e $FILE ] then echo "Could not cleanup file ${TEST_TEXT_FILE}" exit 1 fi } function mk_test_dir { mkdir ${TEST_DIR} if [ ! -d ${TEST_DIR} ]; then echo "Directory ${TEST_DIR} was not created" exit 1 fi } function rm_test_dir { rmdir ${TEST_DIR} if [ -e $TEST_DIR ]; then echo "Could not remove the test directory, it still exists: ${TEST_DIR}" exit 1 fi } function test_append_file { echo "Testing append to file ..." # Write a small test file for x in `seq 1 $TEST_TEXT_FILE_LENGTH` do echo "echo ${TEST_TEXT} to ${TEST_TEXT_FILE}" done > ${TEST_TEXT_FILE} # Verify contents of file echo "Verifying length of test file" FILE_LENGTH=`wc -l $TEST_TEXT_FILE | awk '{print $1}'` if [ "$FILE_LENGTH" -ne "$TEST_TEXT_FILE_LENGTH" ] then echo "error: expected $TEST_TEXT_FILE_LENGTH , got $FILE_LENGTH" exit 1 fi rm_test_file } function test_mv_file { echo "Testing mv file function ..." # if the rename file exists, delete it if [ -e $ALT_TEST_TEXT_FILE ] then rm $ALT_TEST_TEXT_FILE fi if [ -e $ALT_TEST_TEXT_FILE ] then echo "Could not delete file ${ALT_TEST_TEXT_FILE}, it still exists" exit 1 fi # create the test file again mk_test_file #rename the test file mv $TEST_TEXT_FILE $ALT_TEST_TEXT_FILE if [ ! -e $ALT_TEST_TEXT_FILE ] then echo "Could not move file" exit 1 fi # Check the contents of the alt file ALT_TEXT_LENGTH=`echo $TEST_TEXT | wc -c | awk '{print $1}'` ALT_FILE_LENGTH=`wc -c $ALT_TEST_TEXT_FILE | awk '{print $1}'` if [ "$ALT_FILE_LENGTH" -ne "$ALT_TEXT_LENGTH" ] then echo "moved file length is not as expected expected: $ALT_TEXT_LENGTH got: $ALT_FILE_LENGTH" exit 1 fi # clean up rm_test_file $ALT_TEST_TEXT_FILE } function test_mv_directory { echo "Testing mv directory function ..." if [ -e $TEST_DIR ]; then echo "Unexpected, this file/directory exists: ${TEST_DIR}" exit 1 fi mk_test_dir mv ${TEST_DIR} ${TEST_DIR}_rename if [ ! -d "${TEST_DIR}_rename" ]; then echo "Directory ${TEST_DIR} was not renamed" exit 1 fi rmdir ${TEST_DIR}_rename if [ -e "${TEST_DIR}_rename" ]; then echo "Could not remove the test directory, it still exists: ${TEST_DIR}_rename" exit 1 fi } function test_redirects { echo "Testing redirects ..." mk_test_file ABCDEF CONTENT=`cat $TEST_TEXT_FILE` if [ ${CONTENT} != "ABCDEF" ]; then echo "CONTENT read is unexpected, got ${CONTENT}, expected ABCDEF" exit 1 fi echo XYZ > $TEST_TEXT_FILE CONTENT=`cat $TEST_TEXT_FILE` if [ ${CONTENT} != "XYZ" ]; then echo "CONTENT read is unexpected, got ${CONTENT}, expected XYZ" exit 1 fi echo 123456 >> $TEST_TEXT_FILE LINE1=`sed -n '1,1p' $TEST_TEXT_FILE` LINE2=`sed -n '2,2p' $TEST_TEXT_FILE` if [ ${LINE1} != "XYZ" ]; then echo "LINE1 was not as expected, got ${LINE1}, expected XYZ" exit 1 fi if [ ${LINE2} != "123456" ]; then echo "LINE2 was not as expected, got ${LINE2}, expected 123456" exit 1 fi # clean up rm_test_file } function test_mkdir_rmdir { echo "Testing creation/removal of a directory" if [ -e $TEST_DIR ]; then echo "Unexpected, this file/directory exists: ${TEST_DIR}" exit 1 fi mk_test_dir rm_test_dir } function test_chmod { echo "Testing chmod file function ..." # create the test file again mk_test_file ORIGINAL_PERMISSIONS=$(stat --format=%a $TEST_TEXT_FILE) chmod 777 $TEST_TEXT_FILE; # if they're the same, we have a problem. if [ $(stat --format=%a $TEST_TEXT_FILE) == $ORIGINAL_PERMISSIONS ] then echo "Could not modify $TEST_TEXT_FILE permissions" exit 1 fi # clean up rm_test_file } function test_chown { echo "Testing chown file function ..." # create the test file again mk_test_file ORIGINAL_PERMISSIONS=$(stat --format=%u:%g $TEST_TEXT_FILE) chown 1000:1000 $TEST_TEXT_FILE; # if they're the same, we have a problem. if [ $(stat --format=%a $TEST_TEXT_FILE) == $ORIGINAL_PERMISSIONS ] then echo "Could not modify $TEST_TEXT_FILE ownership" exit 1 fi # clean up rm_test_file } function test_list { echo "Testing list" mk_test_file mk_test_dir file_cnt=$(ls -1 | wc -l) if [ $file_cnt != 2 ]; then echo "Expected 2 file but got $file_cnt" exit 1 fi rm_test_file rm_test_dir } function test_remove_nonempty_directory { echo "Testing removing a non-empty directory" mk_test_dir touch "${TEST_DIR}/file" rmdir "${TEST_DIR}" 2>&1 | grep -q "Directory not empty" rm "${TEST_DIR}/file" rm_test_dir } function test_rename_before_close { echo "Testing rename before close ..." ( echo foo mv $TEST_TEXT_FILE ${TEST_TEXT_FILE}.new ) > $TEST_TEXT_FILE if ! cmp <(echo foo) ${TEST_TEXT_FILE}.new; then echo "rename before close failed" exit 1 fi rm_test_file ${TEST_TEXT_FILE}.new rm -f ${TEST_TEXT_FILE} } function test_multipart_upload { echo "Testing multi-part upload ..." dd if=/dev/urandom of="/tmp/${BIG_FILE}" bs=$BIG_FILE_LENGTH count=1 dd if="/tmp/${BIG_FILE}" of="${BIG_FILE}" bs=$BIG_FILE_LENGTH count=1 # Verify contents of file echo "Comparing test file" if ! cmp "/tmp/${BIG_FILE}" "${BIG_FILE}" then exit 1 fi rm -f "/tmp/${BIG_FILE}" rm_test_file "${BIG_FILE}" } function test_multipart_copy { echo "Testing multi-part copy ..." dd if=/dev/urandom of="/tmp/${BIG_FILE}" bs=$BIG_FILE_LENGTH count=1 dd if="/tmp/${BIG_FILE}" of="${BIG_FILE}" bs=$BIG_FILE_LENGTH count=1 mv "${BIG_FILE}" "${BIG_FILE}-copy" # Verify contents of file echo "Comparing test file" if ! cmp "/tmp/${BIG_FILE}" "${BIG_FILE}-copy" then exit 1 fi rm -f "/tmp/${BIG_FILE}" rm_test_file "${BIG_FILE}-copy" } function test_special_characters { echo "Testing special characters ..." ls 'special' 2>&1 | grep -q 'No such file or directory' ls 'special?' 2>&1 | grep -q 'No such file or directory' ls 'special*' 2>&1 | grep -q 'No such file or directory' ls 'special~' 2>&1 | grep -q 'No such file or directory' ls 'specialµ' 2>&1 | grep -q 'No such file or directory' } function test_extended_attributes { command -v setfattr >/dev/null 2>&1 || \ { echo "Skipping extended attribute tests" ; return; } echo "Testing extended attributes ..." rm -f $TEST_TEXT_FILE touch $TEST_TEXT_FILE # set value setfattr -n key1 -v value1 $TEST_TEXT_FILE getfattr -n key1 --only-values $TEST_TEXT_FILE | grep -q '^value1$' # append value setfattr -n key2 -v value2 $TEST_TEXT_FILE getfattr -n key1 --only-values $TEST_TEXT_FILE | grep -q '^value1$' getfattr -n key2 --only-values $TEST_TEXT_FILE | grep -q '^value2$' # remove value setfattr -x key1 $TEST_TEXT_FILE ! getfattr -n key1 --only-values $TEST_TEXT_FILE getfattr -n key2 --only-values $TEST_TEXT_FILE | grep -q '^value2$' } function run_all_tests { test_append_file test_mv_file test_mv_directory test_redirects test_mkdir_rmdir test_chmod test_chown test_list test_remove_nonempty_directory # TODO: broken: https://github.com/s3fs-fuse/s3fs-fuse/issues/145 #test_rename_before_close test_multipart_upload # TODO: test disabled until S3Proxy 1.5.0 is released #test_multipart_copy test_special_characters test_extended_attributes } # Mount the bucket CUR_DIR=`pwd` TEST_BUCKET_MOUNT_POINT_1=$1 if [ "$TEST_BUCKET_MOUNT_POINT_1" == "" ]; then echo "Mountpoint missing" exit 1 fi cd $TEST_BUCKET_MOUNT_POINT_1 if [ -e $TEST_TEXT_FILE ] then rm -f $TEST_TEXT_FILE fi run_all_tests # Unmount the bucket cd $CUR_DIR echo "All tests complete." s3fs-fuse-1.79+git90-g8f11507/test/mergedir.sh000077500000000000000000000103771260476112200204250ustar00rootroot00000000000000#!/bin/sh # # Merge old directory object to new. # For s3fs after v1.64 # ### ### UsageFunction ### UsageFuntion() { echo "Usage: $1 [-h] [-y] [-all] " echo " -h print usage" echo " -y no confirm" echo " -all force all directoris" echo " There is no -all option is only to merge for other S3 client." echo " If -all is specified, this shell script merge all directory" echo " for s3fs old version." echo "" } ### Check parameters WHOAMI=`whoami` OWNNAME=`basename $0` AUTOYES="no" ALLYES="no" DIRPARAM="" while [ "$1" != "" ]; do if [ "X$1" = "X-help" -o "X$1" = "X-h" -o "X$1" = "X-H" ]; then UsageFuntion $OWNNAME exit 0 elif [ "X$1" = "X-y" -o "X$1" = "X-Y" ]; then AUTOYES="yes" elif [ "X$1" = "X-all" -o "X$1" = "X-ALL" ]; then ALLYES="yes" else if [ "X$DIRPARAM" != "X" ]; then echo "*** Input error." echo "" UsageFuntion $OWNNAME exit 1 fi DIRPARAM=$1 fi shift done if [ "X$DIRPARAM" = "X" ]; then echo "*** Input error." echo "" UsageFuntion $OWNNAME exit 1 fi if [ "$WHOAMI" != "root" ]; then echo "" echo "Warning: You run this script by $WHOAMI, should be root." echo "" fi ### Caution echo "#############################################################################" echo "[CAUTION]" echo "This program merges a directory made in s3fs which is older than version 1.64." echo "And made in other S3 client appilication." echo "This program may be have bugs which are not fixed yet." echo "Please execute this program by responsibility of your own." echo "#############################################################################" echo "" DATE=`date +'%Y%m%d-%H%M%S'` LOGFILE="$OWNNAME-$DATE.log" echo -n "Start to merge directory object... [$DIRPARAM]" echo "# Start to merge directory object... [$DIRPARAM]" >> $LOGFILE echo -n "# DATE : " >> $LOGFILE echo `date` >> $LOGFILE echo -n "# BASEDIR : " >> $LOGFILE echo `pwd` >> $LOGFILE echo -n "# TARGET PATH : " >> $LOGFILE echo $DIRPARAM >> $LOGFILE echo "" >> $LOGFILE if [ "$AUTOYES" = "yes" ]; then echo "(no confirmation)" else echo "" fi echo "" ### Get Directory list DIRLIST=`find $DIRPARAM -type d -print | grep -v ^\.$` # # Main loop # for DIR in $DIRLIST; do ### Skip "." and ".." directories BASENAME=`basename $DIR` if [ "$BASENAME" = "." -o "$BASENAME" = ".." ]; then continue fi if [ "$ALLYES" = "no" ]; then ### Skip "d---------" directories. ### Other clients make directory object "dir/" which don't have ### "x-amz-meta-mode" attribyte. ### Then these directories is "d---------", it is target directory. DIRPERMIT=`ls -ld --time-style=+'%Y%m%d%H%M' $DIR | awk '{print $1}'` if [ "$DIRPERMIT" != "d---------" ]; then continue fi fi ### Comfirm ANSWER="" if [ "$AUTOYES" = "yes" ]; then ANSWER="y" fi while [ "X$ANSWER" != "XY" -a "X$ANSWER" != "Xy" -a "X$ANSWER" != "XN" -a "X$ANSWER" != "Xn" ]; do echo -n "Do you merge $DIR? (y/n): " read ANSWER done if [ "X$ANSWER" != "XY" -a "X$ANSWER" != "Xy" ]; then continue fi ### Do CHOWN=`ls -ld --time-style=+'%Y%m%d%H%M' $DIR | awk '{print $3":"$4" "$7}'` CHMOD=`ls -ld --time-style=+'%Y%m%d%H%M' $DIR | awk '{print $7}'` TOUCH=`ls -ld --time-style=+'%Y%m%d%H%M' $DIR | awk '{print $6" "$7}'` echo -n "*** Merge $DIR : " echo -n " $DIR : " >> $LOGFILE chmod 755 $CHMOD > /dev/null 2>&1 RESULT=$? if [ $RESULT -ne 0 ]; then echo "Failed(chmod)" echo "Failed(chmod)" >> $LOGFILE continue fi chown $CHOWN > /dev/null 2>&1 RESULT=$? if [ $RESULT -ne 0 ]; then echo "Failed(chown)" echo "Failed(chown)" >> $LOGFILE continue fi touch -t $TOUCH > /dev/null 2>&1 RESULT=$? if [ $RESULT -ne 0 ]; then echo "Failed(touch)" echo "Failed(touch)" >> $LOGFILE continue fi echo "Succeed" echo "Succeed" >> $LOGFILE done echo "" echo "" >> $LOGFILE echo "Finished." echo -n "# Finished : " >> $LOGFILE echo `date` >> $LOGFILE # # END # s3fs-fuse-1.79+git90-g8f11507/test/passwd-s3fs000066400000000000000000000000401260476112200203520ustar00rootroot00000000000000local-identity:local-credential s3fs-fuse-1.79+git90-g8f11507/test/require-root.sh000077500000000000000000000001471260476112200212560ustar00rootroot00000000000000#!/bin/bash -e if [[ $EUID -ne 0 ]] then echo "This test script must be run as root" 1>&2 exit 1 fi s3fs-fuse-1.79+git90-g8f11507/test/s3proxy.conf000066400000000000000000000003521260476112200205560ustar00rootroot00000000000000s3proxy.endpoint=http://127.0.0.1:8080 s3proxy.authorization=aws-v2 s3proxy.identity=local-identity s3proxy.credential=local-credential jclouds.provider=transient jclouds.identity=remote-identity jclouds.credential=remote-credential s3fs-fuse-1.79+git90-g8f11507/test/sample_ahbe.conf000066400000000000000000000026221260476112200213710ustar00rootroot00000000000000# S3FS: Samlpe ahbe_conf parameter file. # # This file is configuration file for additional header by extension(ahbe). # s3fs loads this file at starting. # # Format: # line = [file suffix] HTTP-header [HTTP-header-values] # file suffix = file(object) suffix, if this field is empty, # it means "*"(all object). # HTTP-header = additional HTTP header name # HTTP-header-values = additional HTTP header value # # # # Example: # " Content-Encoding gzip" --> all object # ".gz Content-Encoding gzip" --> only ".gz" extension file # # Notice: # If you need to set all object, you can specify without "suffix". # Then all of object(file) is added additional header. # If you have this configuration file for Content-Encoding, you should # know about RFC 2616. # # "The default (identity) encoding; the use of no transformation # whatsoever. This content-coding is used only in the Accept- # Encoding header, and SHOULD NOT be used in the Content-Encoding # header." # .gz Content-Encoding gzip .Z Content-Encoding compress .bz2 Content-Encoding bzip2 .svgz Content-Encoding gzip .svg.gz Content-Encoding gzip .tgz Content-Encoding gzip .tar.gz Content-Encoding gzip .taz Content-Encoding gzip .tz Content-Encoding gzip .tbz2 Content-Encoding gzip gz.js Content-Encoding gzip s3fs-fuse-1.79+git90-g8f11507/test/sample_delcache.sh000077500000000000000000000047411260476112200217160ustar00rootroot00000000000000#!/bin/sh # # This is unsupport sample deleting cache files script. # So s3fs's local cache files(stats and objects) grow up, # you need to delete these. # This script deletes these files with total size limit # by sorted atime of files. # You can modify this script for your system. # # [Usage] script [-silent] # func_usage() { echo "" echo "Usage: $1 [-silent]" echo " $1 -h" echo "Sample: $1 mybucket /tmp/s3fs/cache 1073741824" echo "" echo " bucket name = bucket name which specified s3fs option" echo " cache path = cache directory path which specified by" echo " use_cache s3fs option." echo " limit size = limit for total cache files size." echo " specify by BYTE" echo " -silent = silent mode" echo "" } PRGNAME=`basename $0` if [ "X$1" = "X-h" -o "X$1" = "X-H" ]; then func_usage $PRGNAME exit 0 fi if [ "X$1" = "X" -o "X$2" = "X" -o "X$3" = "X" ]; then func_usage $PRGNAME exit -1 fi BUCKET=$1 CDIR=$2 LIMIT=$3 SILENT=0 if [ "X$4" = "X-silent" ]; then SILENT=1 fi FILES_CDIR=$CDIR/$BUCKET STATS_CDIR=$CDIR/\.$BUCKET\.stat # # Check total size # if [ $LIMIT -ge `du -sb $FILES_CDIR | awk '{print $1}'` ]; then if [ $SILENT -ne 1 ]; then echo "$FILES_CDIR is below allowed $LIMIT" fi exit 0 fi # # Make file list by sorted access time # ALL_STATS_ATIMELIST=`find $STATS_CDIR -type f -exec echo -n {} \; -exec echo -n " " \; -exec stat -c %X {} \; | awk '{print $2":"$1}' | sort` # # Remove loop # TMP_ATIME=0 TMP_STATS="" TMP_CFILE="" for part in $ALL_STATS_ATIMELIST; do TMP_ATIME=`echo $part | sed 's/\:/ /' | awk '{print $1}'` TMP_STATS=`echo $part | sed 's/\:/ /' | awk '{print $2}'` TMP_CFILE=`echo $TMP_STATS | sed s/\.$BUCKET\.stat/$BUCKET/` if [ `stat -c %X $TMP_STATS` -eq $TMP_ATIME ]; then rm -f $TMP_STATS $TMP_CFILE > /dev/null 2>&1 if [ $? -ne 0 ]; then if [ $SILENT -ne 1 ]; then echo "ERROR: Could not remove files($TMP_STATS,$TMP_CFILE)" fi exit -1 else if [ $SILENT -ne 1 ]; then echo "remove file: $TMP_CFILE $TMP_STATS" fi fi fi if [ $LIMIT -ge `du -sb $FILES_CDIR | awk '{print $1}'` ]; then if [ $SILENT -ne 1 ]; then echo "finish removing files" fi break fi done if [ $SILENT -ne 1 ]; then TOTAL_SIZE=`du -sb $FILES_CDIR | awk '{print $1}'` echo "Finish: $FILES_CDIR total size is $TOTAL_SIZE" fi exit 0 # # End # s3fs-fuse-1.79+git90-g8f11507/test/small-integration-test.sh000077500000000000000000000043361260476112200232330ustar00rootroot00000000000000#!/bin/bash # # By default tests run against a local s3proxy instance. To run against # Amazon S3, specify the following variables: # # S3FS_CREDENTIALS_FILE=keyfile s3fs format key file # TEST_BUCKET_1=bucket Name of bucket to use # S3PROXY_BINARY="" Leave empty # S3_URL="http://s3.amazonaws.com" Specify Amazon server # # Example: # # S3FS_CREDENTIALS_FILE=keyfile TEST_BUCKET_1=bucket S3PROXY_BINARY="" S3_URL="http://s3.amazonaws.com" ./small-integration-test.sh # set -o xtrace set -o errexit : ${S3_URL:="http://127.0.0.1:8080"} # Require root REQUIRE_ROOT=require-root.sh #source $REQUIRE_ROOT source integration-test-common.sh function retry { set +o errexit N=$1; shift; status=0 for i in $(seq $N); do $@ status=$? if [ $status == 0 ]; then break fi sleep 1 done if [ $status != 0 ]; then echo "timeout waiting for $@" fi set -o errexit return $status } function exit_handler { if [ -n "${S3PROXY_PID}" ] then kill $S3PROXY_PID fi retry 30 fusermount -u $TEST_BUCKET_MOUNT_POINT_1 } trap exit_handler EXIT if [ -n "${S3PROXY_BINARY}" ] then stdbuf -oL -eL java -jar "$S3PROXY_BINARY" --properties s3proxy.conf | stdbuf -oL -eL sed -u "s/^/s3proxy: /" & # wait for S3Proxy to start for i in $(seq 30); do if exec 3<>"/dev/tcp/127.0.0.1/8080"; then exec 3<&- # Close for read exec 3>&- # Close for write break fi sleep 1 done S3PROXY_PID=$(netstat -lpnt | grep :8080 | awk '{ print $7 }' | sed -u 's|/java||') fi # Mount the bucket if [ ! -d $TEST_BUCKET_MOUNT_POINT_1 ] then mkdir -p $TEST_BUCKET_MOUNT_POINT_1 fi stdbuf -oL -eL $S3FS $TEST_BUCKET_1 $TEST_BUCKET_MOUNT_POINT_1 \ -o createbucket \ -o enable_content_md5 \ -o passwd_file=$S3FS_CREDENTIALS_FILE \ -o sigv2 \ -o singlepart_copy_limit=$((10 * 1024)) \ -o url=${S3_URL} \ -o use_path_request_style -f -o f2 -d -d |& stdbuf -oL -eL sed -u "s/^/s3fs: /" & retry 30 grep $TEST_BUCKET_MOUNT_POINT_1 /proc/mounts || exit 1 ./integration-test-main.sh $TEST_BUCKET_MOUNT_POINT_1 echo "All tests complete."