id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
18,399
addcommanddialog.h
hluk_CopyQ/src/gui/addcommanddialog.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef ADDCOMMANDDIALOG_H #define ADDCOMMANDDIALOG_H #include "common/command.h" #include <QDialog> #include <QtContainerFwd> namespace Ui { class AddCommandDialog; } class QSortFilterProxyModel; class AddCommandDialog final : public QDialog { Q_OBJECT public: explicit AddCommandDialog(const QVector<Command> &pluginCommands, QWidget *parent = nullptr); ~AddCommandDialog(); void accept() override; signals: void addCommands(const QVector<Command> &commands); private: void onLineEditFilterTextChanged(const QString &text); void onListViewCommandsActivated(); Ui::AddCommandDialog *ui; QSortFilterProxyModel *m_filterModel; }; #endif // ADDCOMMANDDIALOG_H
751
C++
.h
26
26.038462
97
0.792426
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,400
commandwidget.h
hluk_CopyQ/src/gui/commandwidget.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef COMMANDWIDGET_H #define COMMANDWIDGET_H #include <QWidget> namespace Ui { class CommandWidget; } class QComboBox; struct Command; /** Widget (set of widgets) for creating or modifying Command object. */ class CommandWidget final : public QWidget { Q_OBJECT public: explicit CommandWidget(QWidget *parent = nullptr); ~CommandWidget(); /** Return command for the widget. */ Command command() const; /** Set current command. */ void setCommand(const Command &c); /** Set formats for format selection combo boxes. */ void setFormats(const QStringList &formats); signals: void iconChanged(); void nameChanged(const QString &name); void commandTextChanged(const QString &command); protected: void showEvent(QShowEvent *event) override; private: void onLineEditNameTextChanged(const QString &text); void onButtonIconCurrentIconChanged(); void onCheckBoxShowAdvancedStateChanged(int state); void onCommandEditCommandTextChanged(const QString &command); void init(); void updateWidgets(); void updateShowAdvanced(); void setShowAdvanced(bool showAdvanced); void emitIconChanged(); QString description() const; Ui::CommandWidget *ui; bool m_showAdvanced = true; QString m_internalId; }; #endif // COMMANDWIDGET_H
1,385
C++
.h
44
27.545455
72
0.74924
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,401
pixelratio.h
hluk_CopyQ/src/gui/pixelratio.h
#ifndef PIXEL_RATIO_H #define PIXEL_RATIO_H #include <QPaintDevice> static qreal pixelRatio(QPaintDevice *pd) { return pd->devicePixelRatioF(); } #endif // PIXEL_RATIO_H
177
C++
.h
8
20.25
41
0.777108
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,402
actiondialog.h
hluk_CopyQ/src/gui/actiondialog.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef ACTIONDIALOG_H #define ACTIONDIALOG_H #include <QDialog> #include <QModelIndex> #include <QPersistentModelIndex> #include <QRegularExpression> #include <QVariantMap> class QAbstractButton; struct Command; namespace Ui { class ActionDialog; } /** Dialog class for executing Command objects. */ class ActionDialog final : public QDialog { Q_OBJECT public: explicit ActionDialog(QWidget *parent = nullptr); ~ActionDialog(); /** Restore command history from configuration. */ void restoreHistory(); /** Save command history. */ void saveHistory(); /** Return filename for storing command history. */ const QString dataFilename() const; /** Set action input data. */ void setInputData(const QVariantMap &data); /** Set command for dialog. */ void setCommand(const Command &cmd); /** Set texts for tabs in combo box. */ void setOutputTabs(const QStringList &tabs); void setCurrentTab(const QString &currentTabName); /** Load settings. */ void loadSettings(); /** Return current command. */ Command command() const; signals: /** Emitted if dialog was accepted. */ void commandAccepted(const Command &command, const QStringList &arguments, const QVariantMap &data); private: void onButtonBoxClicked(QAbstractButton* button); void onComboBoxCommandsCurrentIndexChanged(int index); void onComboBoxInputFormatCurrentTextChanged(const QString &format); void onComboBoxOutputFormatEditTextchanged(const QString &text); void onComboBoxOutputTabEditTextChanged(const QString &text); void onSeparatorEditTextEdited(const QString &text); void previousCommand(); void nextCommand(); void acceptCommand(); QVariant createCurrentItemData(); void saveCurrentCommandToHistory(); Ui::ActionDialog *ui; QVariantMap m_data; int m_currentCommandIndex; }; #endif // ACTIONDIALOG_H
1,974
C++
.h
56
31.267857
104
0.746709
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,403
commanddialog.h
hluk_CopyQ/src/gui/commanddialog.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef COMMANDDIALOG_H #define COMMANDDIALOG_H #include "common/command.h" #include "common/commandstore.h" #include <QDialog> namespace Ui { class CommandDialog; } class QAbstractButton; class CommandDialog final : public QDialog { Q_OBJECT friend class CommandItem; public: CommandDialog( const Commands &pluginCommands, const QStringList &formats, QWidget *parent = nullptr); ~CommandDialog(); /** Create new commands. */ void addCommands(const Commands &commands); void apply(); bool maybeClose(QWidget *saveMessageBoxParent); void reject() override; signals: void commandsSaved(); private: void tryPasteCommandFromClipboard(); void copySelectedCommandsToClipboard(); void onCommandDropped(const QString &text, int row); void onCommandEnabledDisabled(int row); void onCurrentCommandWidgetIconChanged(); void onCurrentCommandWidgetNameChanged(const QString &name); void onFinished(int result); void onAddCommands(const QVector<Command> &commands); void onCommandTextChanged(const QString &command); void onItemOrderListCommandsAddButtonClicked(); void onItemOrderListCommandsItemSelectionChanged(); void onPushButtonLoadCommandsClicked(); void onPushButtonSaveCommandsClicked(); void onPushButtonCopyCommandsClicked(); void onPushButtonPasteCommandsClicked(); void onLineEditFilterCommandsTextChanged(const QString &text); void onButtonBoxClicked(QAbstractButton* button); Command currentCommand(int row) const; Commands currentCommands() const; void addCommandsWithoutSave(const Commands &commands, int targetRow); Commands selectedCommands() const; QString serializeSelectedCommands(); bool hasUnsavedChanges() const; void updateIcon(int row); QString commandsToPaste(); Ui::CommandDialog *ui; Commands m_savedCommands; Commands m_pluginCommands; QStringList m_formats; }; #endif // COMMANDDIALOG_H
2,056
C++
.h
58
30.896552
73
0.771805
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,404
tabicons.h
hluk_CopyQ/src/gui/tabicons.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef TABICONS_H #define TABICONS_H #include <QtContainerFwd> class QIcon; class QComboBox; class QString; class QWidget; /** Return list of saved tabs (ordered by "tabs" option if possible). */ QList<QString> savedTabs(); QString getIconNameForTabName(const QString &tabName); void setIconNameForTabName(const QString &name, const QString &icon); QIcon getIconForTabName(const QString &tabName); void initTabComboBox(QComboBox *comboBox); void setDefaultTabItemCounterStyle(QWidget *widget); void setComboBoxItems(QComboBox *comboBox, const QList<QString> &items); #endif // TABICONS_H
644
C++
.h
17
36.294118
72
0.815235
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,405
notificationdaemon.h
hluk_CopyQ/src/gui/notificationdaemon.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef NOTIFICATIONDAEMON_H #define NOTIFICATIONDAEMON_H #include "gui/notificationbutton.h" #include <QColor> #include <QList> #include <QObject> #include <QVariantMap> #include <QTimer> class Notification; class QPixmap; class QPoint; class QWidget; class NotificationDaemon final : public QObject { Q_OBJECT public: enum Position { Top = 0x2, Bottom = 0x4, Right = 0x8, Left = 0x10, TopRight = Top | Right, BottomRight = Bottom | Right, BottomLeft = Bottom | Left, TopLeft = Top | Left }; explicit NotificationDaemon(QObject *parent = nullptr); ~NotificationDaemon(); Notification *createNotification(const QString &id = QString()); Notification *findNotification(const QString &id); void setPosition(Position position); void setOffset(int horizontalPoints, int verticalPoints); void setMaximumSize(int maximumWidthPoints, int maximumHeightPoints); void updateNotificationWidgets(); void setNotificationOpacity(qreal opacity); void setNotificationStyleSheet(const QString &styleSheet); void setIconColor(const QColor &color); void setNativeNotificationsEnabled(bool enable) { m_nativeNotificationsEnabled = enable; } void removeNotification(const QString &id); signals: void notificationButtonClicked(const NotificationButton &button); private: void onNotificationClose(Notification *notification); void doUpdateNotificationWidgets(); struct NotificationData { QString id; Notification *notification; }; Notification *findNotification(Notification *notification); int offsetX() const; int offsetY() const; Position m_position; QList<NotificationData> m_notifications; QColor m_iconColor; qreal m_opacity; int m_horizontalOffsetPoints; int m_verticalOffsetPoints; int m_maximumWidthPoints; int m_maximumHeightPoints; QString m_styleSheet; QTimer m_timerUpdate; bool m_nativeNotificationsEnabled = true; }; #endif // NOTIFICATIONDAEMON_H
2,129
C++
.h
65
28
94
0.745588
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,406
pluginwidget.h
hluk_CopyQ/src/gui/pluginwidget.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef PLUGINWIDGET_H #define PLUGINWIDGET_H #include "item/itemwidget.h" #include <QWidget> class QSettings; namespace Ui { class PluginWidget; } class PluginWidget final : public QWidget { Q_OBJECT public: explicit PluginWidget(const ItemLoaderPtr &loader, QWidget *parent = nullptr); ~PluginWidget(); const ItemLoaderPtr &loader() const { return m_loader; } private: Ui::PluginWidget *ui; ItemLoaderPtr m_loader; }; #endif // PLUGINWIDGET_H
524
C++
.h
21
22.333333
82
0.762677
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,407
tabpropertieswidget.h
hluk_CopyQ/src/gui/tabpropertieswidget.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef TABPROPERTIESWIDGET_H #define TABPROPERTIESWIDGET_H #include <QWidget> namespace Ui { class TabPropertiesWidget; } class TabPropertiesWidget : public QWidget { Q_OBJECT public: explicit TabPropertiesWidget(QWidget *parent = nullptr); ~TabPropertiesWidget(); void setTabName(const QString &name); void setIconName(const QString &iconName); void setMaxItemCount(int maxItemCount); void setStoreItems(bool storeItems); signals: void iconNameChanged(const QString &iconName); void maxItemCountChanged(int maxItemCount); void storeItemsChanged(bool storeItems); private: Ui::TabPropertiesWidget *ui; }; #endif // TABPROPERTIESWIDGET_H
736
C++
.h
25
26.32
60
0.789174
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,408
screen.h
hluk_CopyQ/src/gui/screen.h
#ifndef SCREEN_H #define SCREEN_H class QPoint; class QRect; class QWidget; int screenCount(); int screenNumberAt(const QPoint &pos); QRect screenGeometry(int i); QRect screenAvailableGeometry(const QWidget &w); #endif // SCREEN_H
237
C++
.h
10
22.1
48
0.81448
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,409
commandsyntaxhighlighter.h
hluk_CopyQ/src/gui/commandsyntaxhighlighter.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef COMMANDSYNTAXHIGHLIGHTER_H #define COMMANDSYNTAXHIGHLIGHTER_H #include <QtContainerFwd> class QPlainTextEdit; class QTextEdit; QList<QString> scriptableKeywords(); QList<QString> scriptableProperties(); QList<QString> scriptableFunctions(); /// Constructors and functions from ECMA specification supported by Qt plus ByteArray. QList<QString> scriptableObjects(); void installCommandSyntaxHighlighter(QTextEdit *editor); void installCommandSyntaxHighlighter(QPlainTextEdit *editor); #endif // COMMANDSYNTAXHIGHLIGHTER_H
579
C++
.h
14
39.928571
86
0.853309
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,410
configurationmanager.h
hluk_CopyQ/src/gui/configurationmanager.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef CONFIGURATIONMANAGER_H #define CONFIGURATIONMANAGER_H #include "item/itemwidget.h" #include <QDialog> #include <QHash> #include <memory> namespace Ui { class ConfigTabGeneral; class ConfigTabHistory; class ConfigTabLayout; class ConfigTabNotifications; class ConfigTabTray; class ConfigurationManager; } class AppConfig; class ConfigTabAppearance; class ConfigTabTabs; class ItemFactory; class ItemOrderList; class Option; class ShortcutsWidget; class QAbstractButton; class QCheckBox; class QComboBox; class QLineEdit; class QListWidgetItem; class QSpinBox; enum class NavigationStyle; /** * Configuration dialog. */ class ConfigurationManager final : public QDialog { Q_OBJECT public: explicit ConfigurationManager(ItemFactory *itemFactory, QWidget *parent = nullptr); /// Simple version of dialog for accessing and settings options from API. ConfigurationManager(); ~ConfigurationManager(); /** Return list of options that can be set or view using command line. */ QStringList options() const; /** Return value of an option. */ QVariant optionValue(const QString &name) const; /** Set value of an option and returns true only if the value changes. */ bool setOptionValue(const QString &name, const QVariant &value, AppConfig *appConfig); /** Return tooltip text for option with given @a name. */ QString optionToolTip(const QString &name) const; void setVisible(bool visible) override; /** Load settings from default file. */ void loadSettings(AppConfig *appConfig); /** Enable/disable autostarting the application. */ void setAutostartEnable(AppConfig *appConfig); void done(int result) override; signals: /** Emitted if configuration changes (after saveSettings() call). */ void configurationChanged(AppConfig *appConfig); void error(const QString &error); private: void connectSlots(); void apply(AppConfig *appConfig); void onButtonBoxClicked(QAbstractButton* button); void onCheckBoxMenuTabIsCurrentStateChanged(int); void onSpinBoxTrayItemsValueChanged(int value); void updateCommandItem(QListWidgetItem *item); void shortcutButtonClicked(QObject *button); void initTabIcons(); void initPluginWidgets(ItemFactory *itemFactory); void initLanguages(); /** Update autostarting the application. */ void updateAutostart(); void initOptions(); template <typename Config, typename Widget> void bind(Widget *obj); template <typename Config> void bind(); void bind(const QString &optionKey, QCheckBox *obj, bool defaultValue); void bind(const QString &optionKey, QSpinBox *obj, int defaultValue); void bind(const QString &optionKey, QLineEdit *obj, const QString &defaultValue); void bind(const QString &optionKey, QComboBox *obj, int defaultValue); void bind(const QString &optionKey, QComboBox *obj, NavigationStyle defaultValue); void bind(const QString &optionKey, const QVariant &defaultValue, const char *description); void updateTabComboBoxes(); Ui::ConfigurationManager *ui; ConfigTabAppearance *m_tabAppearance = nullptr; ConfigTabTabs *m_tabTabs = nullptr; ItemOrderList *m_tabItems = nullptr; ShortcutsWidget *m_tabShortcuts = nullptr; std::shared_ptr<Ui::ConfigTabGeneral> m_tabGeneral; std::shared_ptr<Ui::ConfigTabHistory> m_tabHistory; std::shared_ptr<Ui::ConfigTabLayout> m_tabLayout; std::shared_ptr<Ui::ConfigTabNotifications> m_tabNotifications; std::shared_ptr<Ui::ConfigTabTray> m_tabTray; QHash<QString, Option> m_options; }; #endif // CONFIGURATIONMANAGER_H
3,726
C++
.h
96
34.78125
95
0.761481
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,411
menuitems.h
hluk_CopyQ/src/gui/menuitems.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef MENUITEMS_H #define MENUITEMS_H #include <QList> #include <QKeySequence> #include <QString> #include <QSettings> #include <array> namespace Actions { enum Id { File_New, File_Import, File_Export, File_Preferences, File_Commands, File_ShowClipboardContent, File_ShowPreview, File_ToggleClipboardStoring, File_ProcessManager, File_Exit, Edit_SortSelectedItems, Edit_ReverseSelectedItems, Edit_PasteItems, Edit_CopySelectedItems, Edit_FindItems, Editor_Save, Editor_Cancel, Editor_Undo, Editor_Redo, Editor_Font, Editor_Bold, Editor_Italic, Editor_Underline, Editor_Strikethrough, Editor_Foreground, Editor_Background, Editor_EraseStyle, Editor_Search, Item_MoveToClipboard, Item_ShowContent, Item_Remove, Item_Edit, Item_EditNotes, Item_EditWithEditor, Item_Action, Item_MoveUp, Item_MoveDown, Item_MoveToTop, Item_MoveToBottom, Tabs_NewTab, Tabs_RenameTab, Tabs_RemoveTab, Tabs_ChangeTabIcon, Tabs_NextTab, Tabs_PreviousTab, Help_Help, Help_ShowLog, Help_About, ItemMenu, Count }; } // Actions struct MenuItem { QString iconName; ushort iconId = 0; QString text; QString settingsKey; QKeySequence defaultShortcut; QList<QKeySequence> shortcuts; }; using MenuItems = std::array<MenuItem, Actions::Count>; MenuItems menuItems(); void loadShortcuts(MenuItems *items, const QSettings &settings); #endif // MENUITEMS_H
1,608
C++
.h
74
17.459459
64
0.718338
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,412
commandedit.h
hluk_CopyQ/src/gui/commandedit.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef COMMANDEDIT_H #define COMMANDEDIT_H #include <QWidget> namespace Ui { class CommandEdit; } class CommandEdit final : public QWidget { Q_OBJECT public: explicit CommandEdit(QWidget *parent = nullptr); ~CommandEdit(); void setCommand(const QString &command) const; QString command() const; bool isEmpty() const; void setReadOnly(bool readOnly); signals: void changed(); void commandTextChanged(const QString &command); private: void onPlainTextEditCommandTextChanged(); Ui::CommandEdit *ui; }; #endif // COMMANDEDIT_H
625
C++
.h
25
21.76
52
0.751701
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,413
clipboardspy.h
hluk_CopyQ/src/gui/clipboardspy.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef CLIPBOARDSPY_H #define CLIPBOARDSPY_H #include "common/clipboardmode.h" #include "platform/platformnativeinterface.h" #include <QObject> class ClipboardSpy final : public QObject { Q_OBJECT public: explicit ClipboardSpy(ClipboardMode mode, const QByteArray &owner); /// Actively wait for clipboard/selection to change. void wait(int ms = 2000, int checkIntervalMs = 100); bool setClipboardData(const QVariantMap &data); QByteArray currentOwnerData() const; void stop(); signals: void changed(); void stopped(); private: bool check(); ClipboardMode m_mode; PlatformClipboardPtr m_clipboard; QByteArray m_oldOwnerData; }; #endif // CLIPBOARDSPY_H
762
C++
.h
26
25.846154
71
0.756906
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,414
clipboardbrowsershared.h
hluk_CopyQ/src/gui/clipboardbrowsershared.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef CLIPBOARDBROWSERSHARED_H #define CLIPBOARDBROWSERSHARED_H #include "common/navigationstyle.h" #include "gui/menuitems.h" #include "gui/theme.h" #include <QString> #include <memory> class ActionHandler; class ItemFactory; class NotificationDaemon; struct ClipboardBrowserShared { QString editor; int maxItems = 100; bool textWrap = true; NavigationStyle navigationStyle = NavigationStyle::Default; bool saveOnReturnKey = false; bool moveItemOnReturnKey = false; bool showSimpleItems = false; bool numberSearch = false; int minutesToExpire = 0; int saveDelayMsOnItemAdded = 0; int saveDelayMsOnItemModified = 0; int saveDelayMsOnItemRemoved = 0; int saveDelayMsOnItemMoved = 0; int saveDelayMsOnItemEdited = 0; bool rowIndexFromOne = true; ItemFactory *itemFactory = nullptr; ActionHandler *actions = nullptr; NotificationDaemon *notifications = nullptr; Theme theme; MenuItems menuItems; }; using ClipboardBrowserSharedPtr = std::shared_ptr<ClipboardBrowserShared>; #endif // CLIPBOARDBROWSERSHARED_H
1,140
C++
.h
35
29.085714
74
0.775956
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,415
icon_list.h
hluk_CopyQ/src/gui/icon_list.h
// This file is generated with "update_icon_font.py" from FontAwesome's metadata. struct Icon { unsigned short unicode; bool isBrand; const char *searchTerms; }; constexpr Icon iconList[] = { {0x30, false, "0|Digit Zero|nada|none|zero|zilch"}, {0x31, false, "1|Digit One|one"}, {0x32, false, "2|Digit Two|two"}, {0x33, false, "3|Digit Three|three"}, {0x34, false, "4|Digit Four|four"}, {0x35, false, "5|Digit Five|five"}, {0x36, false, "6|Digit Six|six"}, {0x37, false, "7|Digit Seven|seven"}, {0x38, false, "8|Digit Eight|eight"}, {0x39, false, "9|Digit Nine|nine"}, {0x41, false, "a|Latin Capital Letter A|Latin Small Letter A|letter"}, {0xf2b9, false, "address book|contact|directory|employee|index|little black book|portfolio|rolodex|uer|username"}, {0xf2bb, false, "address card|about|contact|employee|id|identification|portfolio|postcard|profile|registration|uer|username"}, {0xf037, false, "align center|format|middle|paragraph|text"}, {0xf039, false, "align justify|format|paragraph|text"}, {0xf036, false, "align left|format|paragraph|text"}, {0xf038, false, "align right|format|paragraph|text"}, {0xf13d, false, "anchor|anchor|berth|boat|dock|embed|link|maritime|moor|port|secure|ship|tool"}, {0xe4aa, false, "anchor circle check|enable|marina|not affected|ok|okay|port|validate|working"}, {0xe4ab, false, "anchor circle exclamation|affected|failed|marina|port"}, {0xe4ac, false, "anchor circle xmark|destroy|marina|port|uncheck"}, {0xe4ad, false, "anchor lock|closed|lockdown|marina|padlock|port|privacy|quarantine"}, {0xf107, false, "angle down|Down Arrowhead|arrow|caret|download|expand|insert"}, {0xf104, false, "angle left|Single Left-Pointing Angle Quotation Mark|arrow|back|caret|less|previous"}, {0xf105, false, "angle right|Single Right-Pointing Angle Quotation Mark|arrow|care|forward|more|next"}, {0xf106, false, "angle up|Up Arrowhead|arrow|caret|collapse|upgrade|upload"}, {0xf103, false, "angles down|arrows|caret|download|expand"}, {0xf100, false, "angles left|Left-Pointing Double Angle Quotation Mark|arrows|back|caret|laquo|previous|quote"}, {0xf101, false, "angles right|Right-Pointing Double Angle Quotation Mark|arrows|caret|forward|more|next|quote|raquo"}, {0xf102, false, "angles up|arrows|caret|collapse|upload"}, {0xf644, false, "ankh|Ankh|amulet|copper|coptic christianity|copts|crux ansata|egypt|venus"}, {0xf5d1, false, "apple whole|apple|fall|fruit|fuji|green|green apple|macintosh|orchard|red|red apple|seasonal|vegan"}, {0xf557, false, "archway|arc|monument|road|street|tunnel"}, {0xf063, false, "arrow down|Downwards Arrow|download"}, {0xf162, false, "arrow down 1 9|arrange|filter|numbers|order|sort-numeric-asc"}, {0xf886, false, "arrow down 9 1|arrange|filter|numbers|order|sort-numeric-asc"}, {0xf15d, false, "arrow down a z|alphabetical|arrange|filter|order|sort-alpha-asc"}, {0xf175, false, "arrow down long|download|long-arrow-down"}, {0xf884, false, "arrow down short wide|arrange|filter|order|sort-amount-asc"}, {0xe4af, false, "arrow down up across line|border|crossing|transfer"}, {0xe4b0, false, "arrow down up lock|border|closed|crossing|lockdown|padlock|privacy|quarantine|transfer"}, {0xf160, false, "arrow down wide short|arrange|filter|number|order|sort-amount-asc"}, {0xf881, false, "arrow down z a|alphabetical|arrange|filter|order|sort-alpha-asc"}, {0xf060, false, "arrow left|Leftwards Arrow|back|previous"}, {0xf177, false, "arrow left long|back|long-arrow-left|previous"}, {0xf245, false, "arrow pointer|arrow|cursor|select"}, {0xf061, false, "arrow right|Rightwards Arrow|forward|next"}, {0xf0ec, false, "arrow right arrow left|Rightwards Arrow Over Leftwards Arrow|arrow|arrows|reciprocate|return|swap|transfer"}, {0xf08b, false, "arrow right from bracket|arrow|exit|leave|log out|logout"}, {0xf178, false, "arrow right long|forward|long-arrow-right|next"}, {0xf090, false, "arrow right to bracket|arrow|enter|insert|join|log in|login|sign in|sign up|sign-in|signin|signup"}, {0xe4b3, false, "arrow right to city|building|city|exodus|insert|rural|urban"}, {0xf0e2, false, "arrow rotate left|Anticlockwise Open Circle Arrow|back|control z|exchange|oops|return|rotate|swap"}, {0xf01e, false, "arrow rotate right|Clockwise Open Circle Arrow|forward|refresh|reload|renew|repeat|retry"}, {0xe097, false, "arrow trend down|line|stocks|trend"}, {0xe098, false, "arrow trend up|line|stocks|trend"}, {0xf149, false, "arrow turn down|arrow"}, {0xf148, false, "arrow turn up|arrow"}, {0xf062, false, "arrow up|Upwards Arrow|forward|upgrade|upload"}, {0xf163, false, "arrow up 1 9|arrange|filter|numbers|order|sort-numeric-desc"}, {0xf887, false, "arrow up 9 1|arrange|filter|numbers|order|sort-numeric-desc"}, {0xf15e, false, "arrow up a z|alphabetical|arrange|filter|order|sort-alpha-desc"}, {0xe09a, false, "arrow up from bracket|share|transfer|upgrade|upload"}, {0xe4b5, false, "arrow up from ground water|groundwater|spring|upgrade|water supply|water table"}, {0xe4b6, false, "arrow up from water pump|flood|groundwater|pump|submersible|sump pump|upgrade"}, {0xf176, false, "arrow up long|long-arrow-up|upload"}, {0xe4b7, false, "arrow up right dots|growth|increase|population|upgrade"}, {0xf08e, false, "arrow up right from square|new|open|send|share|upgrade"}, {0xf885, false, "arrow up short wide|arrange|filter|order|sort-amount-desc"}, {0xf161, false, "arrow up wide short|arrange|filter|order|sort-amount-desc|upgrade"}, {0xf882, false, "arrow up z a|alphabetical|arrange|filter|order|sort-alpha-desc"}, {0xe4b8, false, "arrows down to line|insert|scale down|sink"}, {0xe4b9, false, "arrows down to people|affected|focus|insert|targeted|together|uer"}, {0xf07e, false, "arrows left right|expand|horizontal|landscape|resize|wide"}, {0xe4ba, false, "arrows left right to line|analysis|expand|gap"}, {0xf021, false, "arrows rotate|Clockwise Right and Left Semicircle Arrows|clockwise|exchange|modify|refresh|reload|renew|retry|rotate|swap"}, {0xe4bb, false, "arrows spin|cycle|rotate|spin|whirl"}, {0xe4bc, false, "arrows split up and left|agile|split"}, {0xe4bd, false, "arrows to circle|center|concentrate|coordinate|coordination|focal point|focus|insert"}, {0xe4be, false, "arrows to dot|assembly point|center|condense|focus|insert|minimize"}, {0xe4bf, false, "arrows to eye|center|coordinated assessment|focus"}, {0xe4c0, false, "arrows turn right|arrows"}, {0xe4c1, false, "arrows turn to dots|destination|insert|nexus"}, {0xf07d, false, "arrows up down|expand|portrait|resize|tall|vertical"}, {0xf047, false, "arrows up down left right|arrow|arrows|bigger|enlarge|expand|fullscreen|move|position|reorder|resize"}, {0xe4c2, false, "arrows up to line|rise|scale up|upgrade"}, {0x2a, false, "asterisk|Asterisk|Heavy Asterisk|annotation|details|reference|required|star"}, {0x40, false, "at|Commercial At|address|author|e-mail|email|fluctuate|handle"}, {0xf5d2, false, "atom|atheism|atheist|atom|atom symbol|chemistry|electron|ion|isotope|knowledge|neutron|nuclear|proton|science"}, {0xf29e, false, "audio description|blind|narration|video|visual"}, {0xe0a9, false, "austral sign|Austral Sign|currency"}, {0xf559, false, "award|guarantee|honor|praise|prize|recognition|ribbon|trophy|warranty"}, {0x42, false, "b|Latin Capital Letter B|Latin Small Letter B|letter"}, {0xf77c, false, "baby|uer|users-people"}, {0xf77d, false, "baby carriage|buggy|carrier|infant|push|stroller|transportation|walk|wheels"}, {0xf04a, false, "backward|arrow|double|fast reverse button|previous|rewind"}, {0xf049, false, "backward fast|arrow|beginning|first|last track button|previous|previous scene|previous track|quick|rewind|start|triangle"}, {0xf048, false, "backward step|beginning|first|previous|rewind|start"}, {0xf7e5, false, "bacon|bacon|blt|breakfast|food|ham|lard|meat|pancetta|pork|rasher"}, {0xe059, false, "bacteria|antibiotic|antibody|covid-19|health|organism|sick"}, {0xe05a, false, "bacterium|antibiotic|antibody|covid-19|germ|health|organism|sick"}, {0xf290, false, "bag shopping|buy|checkout|grocery|payment|purchase"}, {0xf666, false, "bahai|bahai|bahá'í|star"}, {0xe0ac, false, "baht sign|currency"}, {0xf05e, false, "ban|404|abort|ban|block|cancel|delete|deny|disabled|entry|failed|forbidden|hide|no|not|not found|prohibit|prohibited|remove|stop|trash"}, {0xf54d, false, "ban smoking|ban|cancel|deny|disabled|forbidden|no|no smoking|non-smoking|not|prohibited|smoking"}, {0xf462, false, "bandage|adhesive bandage|bandage|boo boo|first aid|modify|ouch"}, {0xe2e6, false, "bangladeshi taka sign|bdt|currency|tk"}, {0xf02a, false, "barcode|info|laser|price|scan|upc"}, {0xf0c9, false, "bars|checklist|drag|hamburger|list|menu|nav|navigation|ol|reorder|settings|todo|ul"}, {0xf828, false, "bars progress|checklist|downloading|downloads|loading|poll|progress|project management|settings|to do"}, {0xf550, false, "bars staggered|flow|list|timeline"}, {0xf433, false, "baseball|ball|baseball|foul|glove|hardball|league|leather|mlb|softball|sport|underarm"}, {0xf432, false, "baseball bat ball|bat|league|mlb|slugger|softball|sport"}, {0xf291, false, "basket shopping|buy|checkout|grocery|payment|purchase"}, {0xf434, false, "basketball|ball|basketball|dribble|dunk|hoop|nba"}, {0xf2cd, false, "bath|bath|bathtub|clean|shower|tub|wash"}, {0xf244, false, "battery empty|charge|dead|power|status"}, {0xf240, false, "battery full|batter|battery|charge|power|status"}, {0xf242, false, "battery half|charge|power|status"}, {0xf243, false, "battery quarter|charge|low|power|status"}, {0xf241, false, "battery three quarters|charge|power|status"}, {0xf236, false, "bed|hospital|hotel|lodging|mattress|patient|person in bed|rest|sleep|travel|uer"}, {0xf487, false, "bed pulse|EKG|bed|electrocardiogram|health|hospital|life|patient|vital"}, {0xf0fc, false, "beer mug empty|alcohol|ale|bar|beverage|brew|brewery|drink|foam|lager|liquor|mug|stein"}, {0xf0f3, false, "bell|alarm|alert|bel|bell|chime|notification|reminder|request"}, {0xf562, false, "bell concierge|attention|bell|bellhop|bellhop bell|hotel|receptionist|request|service|support"}, {0xf1f6, false, "bell slash|alert|bell|bell with slash|cancel|disabled|forbidden|mute|notification|off|quiet|reminder|silent"}, {0xf55b, false, "bezier curve|curves|illustrator|lines|path|vector"}, {0xf206, false, "bicycle|bicycle|bike|gears|pedal|transportation|vehicle"}, {0xf1e5, false, "binoculars|glasses|inspection|magnifier|magnify|scenic|spyglass|view"}, {0xf780, false, "biohazard|biohazard|covid-19|danger|dangerous|epidemic|hazmat|medical|pandemic|radioactive|sign|toxic|waste|zombie"}, {0xe0b4, false, "bitcoin sign|Bitcoin Sign|currency"}, {0xf517, false, "blender|cocktail|milkshake|mixer|puree|smoothie"}, {0xf6b6, false, "blender phone|appliance|cocktail|fantasy|milkshake|mixer|puree|silly|smoothie"}, {0xf781, false, "blog|journal|log|online|personal|post|web 2.0|wordpress|writing"}, {0xf032, false, "bold|emphasis|format|text"}, {0xf0e7, false, "bolt|charge|danger|electric|electricity|flash|high voltage|lightning|voltage|weather|zap"}, {0xe0b7, false, "bolt lightning|electricity|flash|lightning|weather|zap"}, {0xf1e2, false, "bomb|bomb|comic|error|explode|fuse|grenade|warning"}, {0xf5d7, false, "bone|bone|calcium|dog|skeletal|skeleton|tibia"}, {0xf55c, false, "bong|aparatus|cannabis|marijuana|pipe|smoke|smoking"}, {0xf02d, false, "book|book|cover|decorated|diary|documentation|journal|knowledge|library|notebook|notebook with decorative cover|read|research|scholar"}, {0xf558, false, "book atlas|book|directions|geography|globe|knowledge|library|map|research|travel|wayfinding"}, {0xf647, false, "book bible|book|catholicism|christianity|god|holy"}, {0xe0bb, false, "book bookmark|knowledge|library|research"}, {0xf66a, false, "book journal whills|book|force|jedi|sith|star wars|yoda"}, {0xf7e6, false, "book medical|diary|documentation|health|history|journal|library|read|record|research"}, {0xf518, false, "book open|Book|book|flyer|knowledge|library|notebook|open|open book|pamphlet|reading|research"}, {0xf5da, false, "book open reader|flyer|library|notebook|open book|pamphlet|reading|research"}, {0xf687, false, "book quran|book|islam|muslim|religion"}, {0xf6b7, false, "book skull|Dungeons & Dragons|crossbones|d&d|dark arts|death|dnd|documentation|evil|fantasy|halloween|holiday|library|necronomicon|read|research|skull|spell"}, {0xf827, false, "book tanakh|book|jewish|judaism|religion"}, {0xf02e, false, "bookmark|bookmark|favorite|library|mark|marker|read|remember|research|save"}, {0xf84c, false, "border all|cell|grid|outline|stroke|table"}, {0xf850, false, "border none|cell|grid|outline|stroke|table"}, {0xf853, false, "border top left|cell|outline|stroke|table"}, {0xe4c3, false, "bore hole|bore|bury|drill|hole"}, {0xe4c4, false, "bottle droplet|alcohol|drink|oil|olive oil|wine"}, {0xe4c5, false, "bottle water|h2o|plastic|water"}, {0xe4c6, false, "bowl food|catfood|dogfood|food|rice"}, {0xe2eb, false, "bowl rice|boiled|cooked|cooked rice|rice|steamed"}, {0xf436, false, "bowling ball|alley|candlepin|gutter|lane|strike|tenpin"}, {0xf466, false, "box|archive|box|container|package|parcel|storage"}, {0xf187, false, "box archive|box|package|save|storage"}, {0xf49e, false, "box open|archive|container|package|storage|unpack"}, {0xe05b, false, "box tissue|cough|covid-19|kleenex|mucus|nose|sneeze|snot"}, {0xe4c7, false, "boxes packing|archive|box|package|storage|supplies"}, {0xf468, false, "boxes stacked|archives|inventory|storage|warehouse"}, {0xf2a1, false, "braille|alphabet|blind|dots|raised|vision"}, {0xf5dc, false, "brain|brain|cerebellum|gray matter|intellect|intelligent|knowledge|medulla oblongata|mind|noodle|scholar|wit"}, {0xe46c, false, "brazilian real sign|brazilian real sign|currency"}, {0xf7ec, false, "bread slice|bake|bakery|baking|dough|flour|gluten|grain|sandwich|sourdough|toast|wheat|yeast"}, {0xe4c8, false, "bridge|bridge|road"}, {0xe4c9, false, "bridge circle check|bridge|enable|not affected|ok|okay|road|validate|working"}, {0xe4ca, false, "bridge circle exclamation|affected|bridge|failed|road"}, {0xe4cb, false, "bridge circle xmark|bridge|destroy|road|uncheck"}, {0xe4cc, false, "bridge lock|bridge|closed|lockdown|padlock|privacy|quarantine|road"}, {0xe4ce, false, "bridge water|bridge|road"}, {0xf0b1, false, "briefcase|bag|briefcas|briefcase|business|luggage|offer|office|portfolio|work"}, {0xf469, false, "briefcase medical|doctor|emt|first aid|health"}, {0xf51a, false, "broom|broom|clean|cleaning|firebolt|fly|halloween|nimbus 2000|quidditch|sweep|sweeping|witch"}, {0xf458, false, "broom ball|ball|bludger|broom|golden snitch|harry potter|hogwarts|quaffle|sport|wizard"}, {0xf55d, false, "brush|art|bristles|color|handle|maintenance|modify|paint"}, {0xe4cf, false, "bucket|bucket|pail|sandcastle"}, {0xf188, false, "bug|beetle|error|glitch|insect|repair|report"}, {0xe490, false, "bug slash|beetle|disabled|fix|glitch|insect|optimize|repair|report|warning"}, {0xe4d0, false, "bugs|bedbug|infestation|lice|plague|ticks"}, {0xf1ad, false, "building|apartment|building|business|city|company|office|office building|urban|work"}, {0xe4d1, false, "building circle arrow right|building|city|distribution center|office"}, {0xe4d2, false, "building circle check|building|city|enable|not affected|office|ok|okay|validate|working"}, {0xe4d3, false, "building circle exclamation|affected|building|city|failed|office"}, {0xe4d4, false, "building circle xmark|building|city|destroy|office|uncheck"}, {0xf19c, false, "building columns|bank|building|college|education|institution|museum|students"}, {0xe4d5, false, "building flag| city|building|diplomat|embassy|flag|headquarters|united nations"}, {0xe4d6, false, "building lock|building|city|closed|lock|lockdown|padlock|privacy|quarantine|secure"}, {0xe4d7, false, "building ngo| city|building|non governmental organization|office"}, {0xe4d8, false, "building shield|building|city|police|protect|safety"}, {0xe4d9, false, "building un|building|city|office|united nations"}, {0xe4da, false, "building user|apartment|building|city|employee|uer"}, {0xe4db, false, "building wheat|agriculture|building|city|usda"}, {0xf0a1, false, "bullhorn|Bullhorn|announcement|broadcast|loud|louder|loudspeaker|megaphone|public address|request|share"}, {0xf140, false, "bullseye|archery|goal|objective|strategy|target"}, {0xf805, false, "burger|bacon|beef|burger|burger king|cheeseburger|fast food|grill|ground beef|mcdonalds|sandwich"}, {0xe4dc, false, "burst|boom|crash|explosion"}, {0xf207, false, "bus|bus|oncoming|oncoming bus|public transportation|transportation|travel|vehicle"}, {0xf55e, false, "bus simple|mta|public transportation|transportation|travel|vehicle"}, {0xf64a, false, "business time|alarm|briefcase|business socks|clock|flight of the conchords|portfolio|reminder|wednesday"}, {0x43, false, "c|Latin Capital Letter C|Latin Small Letter C|letter"}, {0xf7da, false, "cable car|aerial tramway|cable|gondola|lift|mountain|mountain cableway|tram|tramway|trolley"}, {0xf1fd, false, "cake candles|anniversary|bakery|birthday|birthday cake|cake|candles|celebration|dessert|frosting|holiday|party|pastry|sweet"}, {0xf1ec, false, "calculator|Pocket Calculator|abacus|addition|arithmetic|counting|math|multiplication|subtraction"}, {0xf133, false, "calendar|calendar|calendar-o|date|day|event|month|schedule|tear-off calendar|time|when|year"}, {0xf274, false, "calendar check|accept|agree|appointment|confirm|correct|date|day|done|enable|event|month|ok|schedule|select|success|tick|time|todo|validate|warranty|when|working|year"}, {0xf783, false, "calendar day|date|day|detail|event|focus|month|schedule|single day|time|today|when|year"}, {0xf073, false, "calendar days|calendar|date|day|event|month|schedule|time|when|year"}, {0xf272, false, "calendar minus|calendar|date|day|delete|event|month|negative|remove|schedule|time|when|year"}, {0xf271, false, "calendar plus|add|calendar|create|date|day|event|month|new|positive|schedule|time|when|year"}, {0xf784, false, "calendar week|date|day|detail|event|focus|month|schedule|single week|time|today|when|year"}, {0xf273, false, "calendar xmark|archive|calendar|date|day|delete|event|month|remove|schedule|time|uncheck|when|x|year"}, {0xf030, false, "camera|image|img|lens|photo|picture|record|shutter|video"}, {0xf083, false, "camera retro|camera|image|img|lens|photo|picture|record|shutter|video"}, {0xe0d8, false, "camera rotate|flip|front-facing|img|photo|selfie"}, {0xf6bb, false, "campground|camping|fall|outdoors|teepee|tent|tipi"}, {0xf786, false, "candy cane|candy|christmas|holiday|mint|peppermint|striped|xmas"}, {0xf55f, false, "cannabis|bud|chronic|drugs|endica|endo|ganja|marijuana|mary jane|pot|reefer|sativa|spliff|weed|whacky-tabacky"}, {0xf46b, false, "capsules|drugs|medicine|pills|prescription"}, {0xf1b9, false, "car|auto|automobile|car|oncoming|oncoming automobile|sedan|transportation|travel|vehicle"}, {0xf5df, false, "car battery|auto|electric|mechanic|power"}, {0xf5e1, false, "car burst|accident|auto|automobile|insurance|sedan|transportation|vehicle|wreck"}, {0xe4dd, false, "car on|alarm|car|carjack|warning"}, {0xf5de, false, "car rear|auto|automobile|sedan|transportation|travel|vehicle"}, {0xf5e4, false, "car side|auto|automobile|car|sedan|transportation|travel|vehicle"}, {0xe4de, false, "car tunnel|road|tunnel"}, {0xf8ff, false, "caravan|camper|motor home|rv|trailer|travel"}, {0xf0d7, false, "caret down|arrow|dropdown|expand|menu|more|triangle"}, {0xf0d9, false, "caret left|arrow|back|previous|triangle"}, {0xf0da, false, "caret right|arrow|forward|next|triangle"}, {0xf0d8, false, "caret up|arrow|collapse|triangle|upgrade"}, {0xf787, false, "carrot|bugs bunny|carrot|food|orange|vegan|vegetable"}, {0xf218, false, "cart arrow down|download|insert|save|shopping"}, {0xf474, false, "cart flatbed|carry|inventory|shipping|transport"}, {0xf59d, false, "cart flatbed suitcase|airport|bag|baggage|suitcase|travel"}, {0xf217, false, "cart plus|add|create|new|positive|shopping"}, {0xf07a, false, "cart shopping|buy|cart|checkout|grocery|payment|purchase|shopping|shopping cart|trolley"}, {0xf788, false, "cash register|buy|cha-ching|change|checkout|commerce|leaerboard|machine|pay|payment|purchase|store"}, {0xf6be, false, "cat|cat|feline|halloween|holiday|kitten|kitty|meow|pet"}, {0xe0df, false, "cedi sign|Cedi Sign|currency"}, {0xe3f5, false, "cent sign|Cent Sign|currency"}, {0xf0a3, false, "certificate|badge|guarantee|star|verified"}, {0xf6c0, false, "chair|chair|furniture|seat|sit"}, {0xf51b, false, "chalkboard|blackboard|learning|school|teaching|whiteboard|writing"}, {0xf51c, false, "chalkboard user|blackboard|instructor|learning|professor|school|uer|whiteboard|writing"}, {0xf79f, false, "champagne glasses|alcohol|bar|beverage|celebrate|celebration|champagne|clink|clinking glasses|drink|glass|holiday|new year's eve|party|toast"}, {0xf5e7, false, "charging station|electric|ev|tesla|vehicle"}, {0xf1fe, false, "chart area|analytics|area|chart|graph|performance|revenue|statistics"}, {0xf080, false, "chart bar|analytics|bar|chart|graph|performance|statistics"}, {0xe0e3, false, "chart column|bar|bar chart|chart|graph|performance|revenue|statistics|track|trend"}, {0xe0e4, false, "chart gantt|chart|graph|performance|statistics|track|trend"}, {0xf201, false, "chart line|activity|analytics|chart|dashboard|gain|graph|increase|line|performance|revenue|statistics"}, {0xf200, false, "chart pie|analytics|chart|diagram|graph|performance|pie|revenue|statistics"}, {0xe473, false, "chart simple|analytics|bar|chart|column|graph|performance|revenue|row|statistics|trend"}, {0xf00c, false, "check|Check Mark|accept|agree|check|check mark|checkmark|confirm|correct|coupon|done|enable|mark|notice|notification|notify|ok|select|success|tick|todo|true|validate|working|yes|✓"}, {0xf560, false, "check double|accept|agree|checkmark|confirm|correct|coupon|done|enable|notice|notification|notify|ok|select|select all|success|tick|todo|validate|working"}, {0xf772, false, "check to slot|accept|cast|election|enable|politics|positive|validate|voting|working|yes"}, {0xf7ef, false, "cheese|cheddar|curd|gouda|melt|parmesan|sandwich|swiss|wedge"}, {0xf439, false, "chess|board|castle|checkmate|game|king|rook|strategy|tournament"}, {0xf43a, false, "chess bishop|Black Chess Bishop|board|checkmate|game|strategy"}, {0xf43c, false, "chess board|board|checkmate|game|strategy"}, {0xf43f, false, "chess king|Black Chess King|board|checkmate|game|strategy"}, {0xf441, false, "chess knight|Black Chess Knight|board|checkmate|game|horse|strategy"}, {0xf443, false, "chess pawn|board|checkmate|chess|chess pawn|dupe|expendable|game|strategy"}, {0xf445, false, "chess queen|Black Chess Queen|board|checkmate|game|strategy"}, {0xf447, false, "chess rook|Black Chess Rook|board|castle|checkmate|game|strategy"}, {0xf078, false, "chevron down|arrow|download|expand|insert"}, {0xf053, false, "chevron left|Left-Pointing Angle Bracket|arrow|back|bracket|previous"}, {0xf054, false, "chevron right|Right-Pointing Angle Bracket|arrow|bracket|forward|next"}, {0xf077, false, "chevron up|arrow|collapse|upgrade|upload"}, {0xf1ae, false, "child|boy|girl|kid|toddler|uer|young|youth"}, {0xe4e0, false, "child combatant|combatant"}, {0xe59c, false, "child dress|boy|girl|kid|toddler|uer|young|youth"}, {0xe59d, false, "child reaching|boy|girl|kid|toddler|uer|young|youth"}, {0xe4e1, false, "children|boy|child|girl|kid|kids|together|uer|young|youth"}, {0xf51d, false, "church|Christian|building|cathedral|chapel|church|community|cross|religion"}, {0xf111, false, "circle|Black Circle|Black Large Circle|black circle|blue|blue circle|brown|brown circle|chart|circle|circle-thin|diameter|dot|ellipse|fill|geometric|green|green circle|notification|orange|orange circle|progress|purple|purple circle|red|red circle|round|white circle|yellow|yellow circle"}, {0xf0ab, false, "circle arrow down|download"}, {0xf0a8, false, "circle arrow left|back|previous"}, {0xf0a9, false, "circle arrow right|forward|next"}, {0xf0aa, false, "circle arrow up|upgrade|upload"}, {0xf058, false, "circle check|accept|affected|agree|clear|confirm|correct|coupon|done|enable|ok|select|success|tick|todo|validate|working|yes"}, {0xf13a, false, "circle chevron down|arrow|download|dropdown|menu|more"}, {0xf137, false, "circle chevron left|arrow|back|previous"}, {0xf138, false, "circle chevron right|arrow|forward|next"}, {0xf139, false, "circle chevron up|arrow|collapse|upgrade|upload"}, {0xf4b9, false, "circle dollar to slot|contribute|generosity|gift|give|premium"}, {0xf192, false, "circle dot|bullseye|button|geometric|notification|radio|radio button|target"}, {0xf358, false, "circle down|arrow-circle-o-down|download"}, {0xf06a, false, "circle exclamation|affect|alert|attention|damage|danger|error|failed|important|notice|notification|notify|problem|required|warning"}, {0xf47e, false, "circle h|Circled Latin Capital Letter H|clinic|covid-19|emergency|letter|map"}, {0xf042, false, "circle half stroke|Circle with Left Half Black|adjust|chart|contrast|dark|fill|light|pie|progress|saturation"}, {0xf05a, false, "circle info|details|help|information|more|support"}, {0xf359, false, "circle left|arrow-circle-o-left|back|previous"}, {0xf056, false, "circle minus|delete|hide|negative|remove|shape|trash"}, {0xe4e2, false, "circle nodes|cluster|connect|network"}, {0xf1ce, false, "circle notch|circle-o-notch|diameter|dot|ellipse|round|spinner"}, {0xf28b, false, "circle pause|hold|wait"}, {0xf144, false, "circle play|audio|music|playing|sound|start|video"}, {0xf055, false, "circle plus|add|create|expand|new|positive|shape"}, {0xf059, false, "circle question|faq|help|information|support|unknown"}, {0xf7ba, false, "circle radiation|danger|dangerous|deadly|hazard|nuclear|radioactive|sign|warning"}, {0xf35a, false, "circle right|arrow-circle-o-right|forward|next"}, {0xf28d, false, "circle stop|block|box|circle|square"}, {0xf35b, false, "circle up|arrow-circle-o-up|upgrade"}, {0xf2bd, false, "circle user|employee|uer|username|users-people"}, {0xf057, false, "circle xmark|close|cross|destroy|exit|incorrect|notice|notification|notify|problem|uncheck|wrong|x"}, {0xf64f, false, "city|buildings|busy|city|cityscape|skyscrapers|urban|windows"}, {0xe131, false, "clapperboard|camera|clapper|clapper board|director|film|movie|record"}, {0xf328, false, "clipboard|clipboar|clipboard|copy|notepad|notes|paste|record"}, {0xf46c, false, "clipboard check|accept|agree|confirm|coupon|done|enable|ok|select|success|tick|todo|validate|working|yes"}, {0xf46d, false, "clipboard list|cheatsheet|checklist|completed|done|finished|intinerary|ol|schedule|summary|survey|tick|todo|ul|wishlist"}, {0xe4e3, false, "clipboard question|assistance|faq|interview|query|question"}, {0xf7f3, false, "clipboard user|attendance|employee|record|roster|staff|uer"}, {0xf017, false, "clock|00|4|4:00|clock|date|four|four o’clock|hour|late|minute|o'clock|o’clock|pending|schedule|ticking|time|timer|timestamp|watch"}, {0xf1da, false, "clock rotate left|Rewind|clock|pending|reverse|time|time machine|time travel|waiting"}, {0xf24d, false, "clone|arrange|copy|duplicate|paste"}, {0xf20a, false, "closed captioning|cc|deaf|hearing|subtitle|subtitling|text|video"}, {0xf0c2, false, "cloud|atmosphere|cloud|fog|overcast|save|upload|weather"}, {0xf0ed, false, "cloud arrow down|download|export|save"}, {0xf0ee, false, "cloud arrow up|import|save|upgrade|upload"}, {0xf76c, false, "cloud bolt|bolt|cloud|cloud with lightning|lightning|precipitation|rain|storm|weather"}, {0xf73b, false, "cloud meatball|FLDSMDFR|food|spaghetti|storm"}, {0xf6c3, false, "cloud moon|crescent|evening|lunar|night|partly cloudy|sky"}, {0xf73c, false, "cloud moon rain|crescent|evening|lunar|night|partly cloudy|precipitation|rain|sky|storm"}, {0xf73d, false, "cloud rain|Rain|cloud|cloud with rain|precipitation|rain|sky|storm"}, {0xf740, false, "cloud showers heavy|precipitation|rain|sky|storm"}, {0xe4e4, false, "cloud showers water|cloud|deluge|flood|rain|storm|surge"}, {0xf6c4, false, "cloud sun|clear|cloud|day|daytime|fall|outdoors|overcast|partly cloudy|sun|sun behind cloud"}, {0xf743, false, "cloud sun rain|cloud|day|overcast|precipitation|rain|storm|summer|sun|sun behind rain cloud|sunshower"}, {0xe139, false, "clover|4|charm|clover|four|four leaf clover|four-leaf clover|leaf|leprechaun|luck|lucky"}, {0xf121, false, "code|brackets|code|development|html|mysql|sql"}, {0xf126, false, "code branch|branch|git|github|mysql|rebase|sql|svn|vcs|version"}, {0xf386, false, "code commit|commit|git|github|hash|rebase|svn|vcs|version"}, {0xe13a, false, "code compare|compare|git|github|svn|version"}, {0xe13b, false, "code fork|fork|git|github|svn|version"}, {0xf387, false, "code merge|git|github|merge|pr|rebase|svn|vcs|version"}, {0xe13c, false, "code pull request|git|github|pr|svn|version"}, {0xf51e, false, "coins|currency|dime|financial|gold|money|penny|premium"}, {0xe140, false, "colon sign|Colon Sign|currency"}, {0xf075, false, "comment| conversation| discussion| talking|Right Speech Bubble|answer|bubble|chat|commenting|conversation|feedback|message|note|notification|sms|speech|talk|texting"}, {0xf651, false, "comment dollar|answer|bubble|chat|commenting|conversation|feedback|message|money|note|notification|pay|salary|sms|speech|spend|texting|transfer"}, {0xf4ad, false, "comment dots|answer|balloon|bubble|chat|comic|commenting|conversation|dialog|feedback|message|more|note|notification|reply|request|sms|speech|speech balloon|texting"}, {0xf7f5, false, "comment medical|advice|answer|bubble|chat|commenting|conversation|diagnose|feedback|message|note|notification|prescription|sms|speech|texting"}, {0xf4b3, false, "comment slash|answer|bubble|cancel|chat|commenting|conversation|disabled|feedback|message|mute|note|notification|quiet|sms|speech|texting"}, {0xf7cd, false, "comment sms|answer|chat|conversation|message|mobile|notification|phone|sms|texting"}, {0xf086, false, "comments| conversation| discussion| talking|Two Speech Bubbles|answer|bubble|chat|commenting|conversation|feedback|message|note|notification|sms|speech|talk|texting"}, {0xf653, false, "comments dollar|answer|bubble|chat|commenting|conversation|feedback|message|money|note|notification|pay|salary|sms|speech|spend|texting|transfer"}, {0xf51f, false, "compact disc|Optical Disc Icon|album|blu-ray|bluray|cd|computer|disc|disk|dvd|media|movie|music|optical|optical disk|record|video|vinyl"}, {0xf14e, false, "compass|compass|directions|directory|location|magnetic|menu|navigation|orienteering|safari|travel"}, {0xf568, false, "compass drafting|design|map|mechanical drawing|plot|plotting"}, {0xf066, false, "compress|collapse|fullscreen|minimize|move|resize|shrink|smaller"}, {0xe4e5, false, "computer|computer|desktop|display|monitor|tower"}, {0xf8cc, false, "computer mouse|click|computer|computer mouse|cursor|input|peripheral"}, {0xf563, false, "cookie|baked good|chips|chocolate|cookie|dessert|eat|snack|sweet|treat"}, {0xf564, false, "cookie bite|baked good|bitten|chips|chocolate|eat|snack|sweet|treat"}, {0xf0c5, false, "copy|clone|duplicate|file|files-o|paper|paste"}, {0xf1f9, false, "copyright|brand|c|copyright|mark|register|trademark"}, {0xf4b8, false, "couch|chair|cushion|furniture|relax|sofa"}, {0xf6c8, false, "cow|agriculture|animal|beef|bovine|co|cow|farm|fauna|livestock|mammal|milk|moo"}, {0xf09d, false, "credit card|buy|card|checkout|credit|credit card|credit-card-alt|debit|money|payment|purchase"}, {0xf125, false, "crop|design|frame|mask|modify|resize|shrink"}, {0xf565, false, "crop simple|design|frame|mask|modify|resize|shrink"}, {0xf654, false, "cross|Christian|Heavy Latin Cross|catholicism|christianity|church|cross|jesus|latin cross|religion"}, {0xf05b, false, "crosshairs|aim|bullseye|gpd|picker|position"}, {0xf520, false, "crow|bird|bullfrog|fauna|halloween|holiday|toad"}, {0xf521, false, "crown|award|clothing|crown|favorite|king|queen|royal|tiara|vip"}, {0xf7f7, false, "crutch|cane|injury|mobility|wheelchair"}, {0xe152, false, "cruzeiro sign|Cruzeiro Sign|currency"}, {0xf1b2, false, "cube|3d|block|dice|package|square|tesseract"}, {0xf1b3, false, "cubes|3d|block|dice|package|pyramid|square|stack|tesseract"}, {0xe4e6, false, "cubes stacked|blocks|cubes|sugar"}, {0x44, false, "d|Latin Capital Letter D|Latin Small Letter D|letter"}, {0xf1c0, false, "database|computer|development|directory|memory|mysql|sql|storage"}, {0xf55a, false, "delete left|Erase to the Left|command|delete|erase|keyboard|undo"}, {0xf747, false, "democrat|american|democratic party|donkey|election|left|left-wing|liberal|politics|usa"}, {0xf390, false, "desktop|computer|cpu|demo|desktop|desktop computer|device|imac|machine|monitor|pc|screen"}, {0xf655, false, "dharmachakra|Buddhist|buddhism|buddhist|dharma|religion|wheel|wheel of dharma"}, {0xe476, false, "diagram next|cells|chart|gantt|row|subtask|successor|table"}, {0xe477, false, "diagram predecessor|cells|chart|gantt|predecessor|previous|row|subtask|table"}, {0xf542, false, "diagram project|chart|graph|network|pert|statistics"}, {0xe47a, false, "diagram successor|cells|chart|gantt|next|row|subtask|successor|table"}, {0xf219, false, "diamond|ace|card|cards|diamond suit|game|gem|gemstone|poker|suit"}, {0xf5eb, false, "diamond turn right|map|navigation|sign|turn"}, {0xf522, false, "dice|chance|dice|die|gambling|game|game die|roll"}, {0xf6cf, false, "dice d20|Dungeons & Dragons|chance|d&d|dnd|fantasy|gambling|game|roll"}, {0xf6d1, false, "dice d6|Dungeons & Dragons|chance|d&d|dnd|fantasy|gambling|game|roll"}, {0xf523, false, "dice five|Die Face-5|chance|gambling|game|roll"}, {0xf524, false, "dice four|Die Face-4|chance|gambling|game|roll"}, {0xf525, false, "dice one|Die Face-1|chance|gambling|game|roll"}, {0xf526, false, "dice six|Die Face-6|chance|gambling|game|roll"}, {0xf527, false, "dice three|Die Face-3|chance|gambling|game|roll"}, {0xf528, false, "dice two|Die Face-2|chance|gambling|game|roll"}, {0xf7fa, false, "disease|bacteria|cancer|coronavirus|covid-19|flu|illness|infection|pandemic|sickness|virus"}, {0xe163, false, "display|Screen|computer|desktop|imac"}, {0xf529, false, "divide|Division Sign|arithmetic|calculus|divide|division|math|sign|÷"}, {0xf471, false, "dna|biologist|dna|double helix|evolution|gene|genetic|genetics|helix|life|molecule|protein"}, {0xf6d3, false, "dog|animal|canine|dog|fauna|mammal|pet|pooch|puppy|woof"}, {0x24, false, "dollar sign|Dollar Sign|coupon|currency|dollar|heavy dollar sign|investment|money|premium|revenue|salary"}, {0xf472, false, "dolly|carry|shipping|transport"}, {0xe169, false, "dong sign|Dong Sign|currency"}, {0xf52a, false, "door closed|doo|door|enter|exit|locked|privacy"}, {0xf52b, false, "door open|enter|exit|welcome"}, {0xf4ba, false, "dove|bird|dove|fauna|fly|flying|peace|war"}, {0xf422, false, "down left and up right to center| scale|collapse|fullscreen|minimize|move|resize|shrink|size|smaller"}, {0xf309, false, "down long|download|long-arrow-down"}, {0xf019, false, "download|export|hard drive|insert|save|transfer"}, {0xf6d5, false, "dragon|Dungeons & Dragons|d&d|dnd|dragon|fairy tale|fantasy|fire|lizard|serpent"}, {0xf5ee, false, "draw polygon|anchors|lines|object|render|shape"}, {0xf043, false, "droplet|blood|cold|color|comic|drop|droplet|raindrop|sweat|waterdrop"}, {0xf5c7, false, "droplet slash|blood|color|disabled|drop|droplet|raindrop|waterdrop"}, {0xf569, false, "drum|drum|drumsticks|instrument|music|percussion|snare|sound"}, {0xf56a, false, "drum steelpan|calypso|instrument|music|percussion|reggae|snare|sound|steel|tropical"}, {0xf6d7, false, "drumstick bite|bone|chicken|leg|meat|poultry|turkey"}, {0xf44b, false, "dumbbell|exercise|gym|strength|weight|weight-lifting|workout"}, {0xf793, false, "dumpster|alley|bin|commercial|trash|waste"}, {0xf794, false, "dumpster fire|alley|bin|commercial|danger|dangerous|euphemism|flame|heat|hot|trash|waste"}, {0xf6d9, false, "dungeon|Dungeons & Dragons|building|d&d|dnd|door|entrance|fantasy|gate"}, {0x45, false, "e|Latin Capital Letter E|Latin Small Letter E|letter"}, {0xf2a4, false, "ear deaf|ear|hearing|sign language"}, {0xf2a2, false, "ear listen|amplify|audio|deaf|ear|headset|hearing|sound"}, {0xf57c, false, "earth africa|africa|all|country|earth|europe|global|globe|gps|language|localize|location|map|online|place|planet|translate|travel|world"}, {0xf57d, false, "earth americas|all|america|country|earth|global|globe|gps|language|localize|location|map|online|place|planet|translate|travel|world"}, {0xf57e, false, "earth asia|all|asia|australia|country|earth|global|globe|gps|language|localize|location|map|online|place|planet|translate|travel|world"}, {0xf7a2, false, "earth europe|all|country|earth|europe|global|globe|gps|language|localize|location|map|online|place|planet|translate|travel|world"}, {0xe47b, false, "earth oceania|all|australia|country|earth|global|globe|gps|language|localize|location|map|melanesia|micronesia|new zealand|online|place|planet|polynesia|translate|travel|world"}, {0xf7fb, false, "egg|breakfast|chicken|easter|egg|food|shell|yolk"}, {0xf052, false, "eject|abort|cancel|cd|discharge|eject|eject button"}, {0xe16d, false, "elevator|accessibility|elevator|hoist|lift|uer|users-people"}, {0xf141, false, "ellipsis|dots|drag|kebab|list|menu|nav|navigation|ol|pacman|reorder|settings|three dots|ul"}, {0xf142, false, "ellipsis vertical|bullet|dots|drag|kebab|list|menu|nav|navigation|ol|reorder|settings|three dots|ul"}, {0xf0e0, false, "envelope|Back of Envelope|e-mail|email|envelope|letter|mail|message|newsletter|notification|offer|support"}, {0xe4e8, false, "envelope circle check|check|email|enable|envelope|mail|not affected|ok|okay|read|sent|validate|working"}, {0xf2b6, false, "envelope open|e-mail|email|letter|mail|message|newsletter|notification|offer|support"}, {0xf658, false, "envelope open text|e-mail|email|letter|mail|message|newsletter|notification|offer|support"}, {0xf674, false, "envelopes bulk|archive|envelope|letter|newsletter|offer|post office|postal|postcard|send|stamp|usps"}, {0x3d, false, "equals|Equals Sign|arithmetic|even|match|math"}, {0xf12d, false, "eraser|art|delete|remove|rubber"}, {0xf796, false, "ethernet|cable|cat 5|cat 6|connection|hardware|internet|network|wired"}, {0xf153, false, "euro sign|Euro Sign|currency"}, {0x21, false, "exclamation|!|Exclamation Mark|alert|attention|danger|error|exclamation|failed|important|mark|notice|notification|notify|outlined|problem|punctuation|red exclamation mark|required|warning|white exclamation mark"}, {0xf065, false, "expand| maximize| resize| scale| arrows| bigger| enlarge| fullscreen| resize| size|expand|viewfinder"}, {0xe4e9, false, "explosion|blast|blowup|boom|crash|detonation|explosion"}, {0xf06e, false, "eye|body|eye|look|optic|see|seen|show|sight|views|visible"}, {0xf1fb, false, "eye dropper|beaker|clone|color|copy|eyedropper|pipette"}, {0xf2a8, false, "eye low vision|blind|eye|sight"}, {0xf070, false, "eye slash|blind|disabled|hide|show|toggle|unseen|views|visible|visiblity"}, {0x46, false, "f|Latin Capital Letter F|Latin Small Letter F|letter"}, {0xf556, false, "face angry|angry|angry face|disapprove|emoticon|face|mad|upset"}, {0xf567, false, "face dizzy|dazed|dead|disapprove|emoticon|face"}, {0xf579, false, "face flushed|dazed|embarrassed|emoticon|face|flushed|flushed face"}, {0xf119, false, "face frown|disapprove|emoticon|face|frown|frowning face|rating|sad|uer"}, {0xf57a, false, "face frown open|disapprove|emoticon|face|frown|frowning face with open mouth|mouth|open|rating|sad"}, {0xf57f, false, "face grimace|cringe|emoticon|face|grimace|grimacing face|teeth"}, {0xf580, false, "face grin|emoticon|face|grin|grinning face|laugh|smile"}, {0xf582, false, "face grin beam|emoticon|eye|face|grinning face with smiling eyes|laugh|mouth|open|smile"}, {0xf583, false, "face grin beam sweat|cold|embarass|emoticon|face|grinning face with sweat|open|smile|sweat"}, {0xf584, false, "face grin hearts|emoticon|eye|face|love|smile|smiling face with heart-eyes"}, {0xf585, false, "face grin squint|emoticon|face|grinning squinting face|laugh|mouth|satisfied|smile"}, {0xf586, false, "face grin squint tears|emoticon|face|floor|happy|laugh|rolling|rolling on the floor laughing|smile"}, {0xf587, false, "face grin stars|emoticon|eyes|face|grinning|quality|star|star-struck|starry-eyed|vip"}, {0xf588, false, "face grin tears|LOL|emoticon|face|face with tears of joy|joy|laugh|tear"}, {0xf589, false, "face grin tongue|LOL|emoticon|face|face with tongue|tongue"}, {0xf58a, false, "face grin tongue squint|LOL|emoticon|eye|face|horrible|squinting face with tongue|taste|tongue"}, {0xf58b, false, "face grin tongue wink|LOL|emoticon|eye|face|joke|tongue|wink|winking face with tongue"}, {0xf581, false, "face grin wide|emoticon|face|grinning face with big eyes|laugh|mouth|open|smile"}, {0xf58c, false, "face grin wink|emoticon|face|flirt|laugh|smile"}, {0xf596, false, "face kiss|beso|emoticon|face|kiss|kissing face|love|smooch"}, {0xf597, false, "face kiss beam|beso|emoticon|eye|face|kiss|kissing face with smiling eyes|love|smile|smooch"}, {0xf598, false, "face kiss wink heart|beso|emoticon|face|face blowing a kiss|kiss|love|smooch"}, {0xf599, false, "face laugh|LOL|emoticon|face|laugh|smile"}, {0xf59a, false, "face laugh beam|LOL|beaming face with smiling eyes|emoticon|eye|face|grin|happy|smile"}, {0xf59b, false, "face laugh squint|LOL|emoticon|face|happy|smile"}, {0xf59c, false, "face laugh wink|LOL|emoticon|face|happy|smile"}, {0xf11a, false, "face meh|deadpan|default|emoticon|face|meh|neutral|neutral face|rating|uer"}, {0xf5a4, false, "face meh blank|emoticon|face|face without mouth|mouth|neutral|quiet|rating|silent"}, {0xf5a5, false, "face rolling eyes|emoticon|eyeroll|eyes|face|face with rolling eyes|neutral|rating|rolling"}, {0xf5b3, false, "face sad cry|cry|emoticon|face|loudly crying face|sad|sob|tear|tears"}, {0xf5b4, false, "face sad tear|cry|crying face|emoticon|face|sad|tear|tears"}, {0xf118, false, "face smile|approve|default|emoticon|face|happy|rating|satisfied|slightly smiling face|smile|uer"}, {0xf5b8, false, "face smile beam|blush|emoticon|eye|face|happy|positive|smile|smiling face with smiling eyes"}, {0xf4da, false, "face smile wink|emoticon|face|happy|hint|joke|wink|winking face"}, {0xf5c2, false, "face surprise|emoticon|face|face with open mouth|mouth|open|shocked|sympathy"}, {0xf5c8, false, "face tired|angry|emoticon|face|grumpy|tired|tired face|upset"}, {0xf863, false, "fan|ac|air conditioning|blade|blower|cool|hot"}, {0xe005, false, "faucet|covid-19|drinking|drip|house|hygiene|kitchen|potable|potable water|sanitation|sink|water"}, {0xe006, false, "faucet drip|drinking|drip|house|hygiene|kitchen|potable|potable water|sanitation|sink|water"}, {0xf1ac, false, "fax|Fax Icon|business|communicate|copy|facsimile|fax|fax machine|send"}, {0xf52d, false, "feather|bird|feather|flight|light|plucked|plumage|quill|write"}, {0xf56b, false, "feather pointed|bird|light|plucked|quill|write"}, {0xe4ea, false, "ferry|barge|boat|carry|ferryboat|ship"}, {0xf15b, false, "file|Empty Document|cv|document|new|page|page facing up|pdf|resume"}, {0xf56d, false, "file arrow down|archive|document|export|insert|save"}, {0xf574, false, "file arrow up|document|import|page|save|upgrade"}, {0xf1c7, false, "file audio|document|mp3|music|page|play|sound"}, {0xe5a0, false, "file circle check|document|enable|file|not affected|ok|okay|paper|validate|working"}, {0xe4eb, false, "file circle exclamation|document|failed|file|paper"}, {0xe4ed, false, "file circle minus|document|file|paper"}, {0xe494, false, "file circle plus|add|document|file|new|page|paper|pdf"}, {0xe4ef, false, "file circle question|document|file|paper"}, {0xe5a1, false, "file circle xmark|document|file|paper|uncheck"}, {0xf1c9, false, "file code|css|development|document|html|mysql|sql"}, {0xf56c, false, "file contract|agreement|binding|document|legal|signature|username"}, {0xf6dd, false, "file csv|document|excel|numbers|spreadsheets|table"}, {0xf1c3, false, "file excel|csv|document|numbers|spreadsheets|table"}, {0xf56e, false, "file export|download|save"}, {0xf1c5, false, "file image|Document with Picture|document|image|img|jpg|photo|png"}, {0xf56f, false, "file import|copy|document|insert|send|upload"}, {0xf570, false, "file invoice|account|bill|charge|document|payment|receipt"}, {0xf571, false, "file invoice dollar|$|account|bill|charge|document|dollar-sign|money|payment|receipt|revenue|salary|usd"}, {0xf15c, false, "file lines|Document|Document with Text|document|file-text|invoice|new|page|pdf"}, {0xf477, false, "file medical|document|health|history|prescription|record"}, {0xf1c1, false, "file pdf|acrobat|document|preview|save"}, {0xf31c, false, "file pen|edit|memo|modify|pen|pencil|update|write"}, {0xf1c4, false, "file powerpoint|display|document|keynote|presentation"}, {0xf572, false, "file prescription|document|drugs|medical|medicine|rx"}, {0xe4f0, false, "file shield|antivirus|data|document|protect|safe|safety|secure"}, {0xf573, false, "file signature|John Hancock|contract|document|name|username"}, {0xf1c8, false, "file video|document|m4v|movie|mp4|play"}, {0xf478, false, "file waveform|document|health|history|prescription|record"}, {0xf1c2, false, "file word|document|edit|page|text|writing"}, {0xf1c6, false, "file zipper|.zip|bundle|compress|compression|download|zip"}, {0xf575, false, "fill|bucket|color|paint|paint bucket"}, {0xf576, false, "fill drip|bucket|color|drop|paint|paint bucket|spill"}, {0xf008, false, "film|cinema|film|film frames|frames|movie|strip|video"}, {0xf0b0, false, "filter|funnel|options|separate|sort"}, {0xf662, false, "filter circle dollar|filter|money|options|premium|separate|sort"}, {0xe17b, false, "filter circle xmark|cancel|funnel|options|remove|separate|sort|uncheck"}, {0xf577, false, "fingerprint|human|id|identification|lock|privacy|smudge|touch|unique|unlock"}, {0xf06d, false, "fire|burn|caliente|fire|flame|heat|hot|popular|tool"}, {0xe4f1, false, "fire burner|cook|fire|flame|kitchen|stove"}, {0xf134, false, "fire extinguisher|burn|caliente|extinguish|fire|fire extinguisher|fire fighter|flame|heat|hot|quench|rescue"}, {0xf7e4, false, "fire flame curved|burn|caliente|flame|heat|hot|popular"}, {0xf46a, false, "fire flame simple|caliente|energy|fire|flame|gas|heat|hot"}, {0xf578, false, "fish|Pisces|fauna|fish|gold|seafood|swimming|zodiac"}, {0xe4f2, false, "fish fins|fish|fishery|pisces|seafood"}, {0xf024, false, "flag|black flag|country|notice|notification|notify|pole|report|symbol|waving"}, {0xf11e, false, "flag checkered|checkered|chequered|chequered flag|finish|notice|notification|notify|pole|racing|report|start|symbol|win"}, {0xf74d, false, "flag usa|betsy ross|country|fla|flag: United States|old glory|stars|stripes|symbol"}, {0xf0c3, false, "flask|beaker|chemicals|experiment|experimental|knowledge|labs|liquid|potion|science|vial"}, {0xe4f3, false, "flask vial| beaker| chemicals| experiment| experimental| labs| liquid| science| vial|ampule|chemistry|lab|laboratory|potion|test|test tube"}, {0xf0c7, false, "floppy disk|Black Hard Shell Floppy Disk|computer|disk|download|floppy|floppy disk|floppy-o"}, {0xe184, false, "florin sign|currency"}, {0xf07b, false, "folder|Black Folder|archive|directory|document|file|file folder|folder"}, {0xe185, false, "folder closed|file"}, {0xf65d, false, "folder minus|archive|delete|directory|document|file|negative|remove"}, {0xf07c, false, "folder open|Open Folder|archive|directory|document|empty|file|folder|new|open|open file folder"}, {0xf65e, false, "folder plus|add|archive|create|directory|document|file|new|positive"}, {0xf802, false, "folder tree|archive|directory|document|file|search|structure"}, {0xf031, false, "font|alphabet|glyph|text|type|typeface"}, {0xf2b4, false, "font awesome|awesome|flag|font|icons|typeface"}, {0xf44e, false, "football|american|american football|ball|fall|football|nfl|pigskin|seasonal"}, {0xf04e, false, "forward|arrow|double|fast|fast-forward button|forward|next|skip"}, {0xf050, false, "forward fast|arrow|end|last|next|next scene|next track|next track button|quick|triangle"}, {0xf051, false, "forward step|end|last|next"}, {0xe18f, false, "franc sign|French Franc Sign|currency"}, {0xf52e, false, "frog|amphibian|bullfrog|fauna|hop|kermit|kiss|prince|ribbit|toad|wart"}, {0xf1e3, false, "futbol|ball|football|mls|soccer|soccer ball"}, {0x47, false, "g|Latin Capital Letter G|Latin Small Letter G|letter"}, {0xf11b, false, "gamepad|arcade|controller|d-pad|joystick|playstore|video|video game"}, {0xf52f, false, "gas pump|car|diesel|fuel|fuel pump|fuelpump|gas|gasoline|petrol|pump|station"}, {0xf624, false, "gauge|dashboard|fast|odometer|speed|speedometer"}, {0xf625, false, "gauge high|dashboard|fast|odometer|quick|speed|speedometer"}, {0xf629, false, "gauge simple|dashboard|fast|odometer|speed|speedometer"}, {0xf62a, false, "gauge simple high|dashboard|fast|odometer|quick|speed|speedometer"}, {0xf0e3, false, "gavel|hammer|judge|law|lawyer|opinion"}, {0xf013, false, "gear|cog|cogwheel|configuration|gear|mechanical|modify|settings|sprocket|tool|wheel"}, {0xf085, false, "gears|configuration|gears|mechanical|modify|settings|sprocket|wheel"}, {0xf3a5, false, "gem|diamond|gem|gem stone|jewel|jewelry|sapphire|stone|treasure"}, {0xf22d, false, "genderless|androgynous|asexual|gender|sexless"}, {0xf6e2, false, "ghost|apparition|blinky|clyde|creature|face|fairy tale|fantasy|floating|ghost|halloween|holiday|inky|monster|pacman|pinky|spirit"}, {0xf06b, false, "gift|box|celebration|christmas|generosity|gift|giving|holiday|party|present|wrapped|wrapped gift|xmas"}, {0xf79c, false, "gifts|christmas|generosity|giving|holiday|party|present|wrapped|xmas"}, {0xe4f4, false, "glass water|potable|water"}, {0xe4f5, false, "glass water droplet|potable|water"}, {0xf530, false, "glasses|hipster|nerd|reading|sight|spectacles|vision"}, {0xf0ac, false, "globe|all|coordinates|country|earth|global|globe|globe with meridians|gps|internet|language|localize|location|map|meridians|network|online|place|planet|translate|travel|world|www"}, {0xf450, false, "golf ball tee|caddy|eagle|putt|tee"}, {0xf664, false, "gopuram|building|entrance|hinduism|temple|tower"}, {0xf19d, false, "graduation cap|cap|celebration|ceremony|clothing|college|graduate|graduation|graduation cap|hat|learning|school|student"}, {0x3e, false, "greater than|Greater-Than Sign|arithmetic|compare|math"}, {0xf532, false, "greater than equal|arithmetic|compare|math"}, {0xf58d, false, "grip|affordance|drag|drop|grab|handle"}, {0xf7a4, false, "grip lines|affordance|drag|drop|grab|handle"}, {0xf7a5, false, "grip lines vertical|affordance|drag|drop|grab|handle"}, {0xf58e, false, "grip vertical|affordance|drag|drop|grab|handle"}, {0xe4f6, false, "group arrows rotate|community|engagement|spin|sync"}, {0xe19a, false, "guarani sign|Guarani Sign|currency"}, {0xf7a6, false, "guitar|acoustic|instrument|music|rock|rock and roll|song|strings"}, {0xe19b, false, "gun|firearm|pistol|weapon"}, {0x48, false, "h|Latin Capital Letter H|Latin Small Letter H|letter"}, {0xf6e3, false, "hammer|admin|configuration|equipment|fix|hammer|maintenance|modify|recovery|repair|settings|tool"}, {0xf665, false, "hamsa|amulet|christianity|islam|jewish|judaism|muslim|protection"}, {0xf256, false, "hand|Raised Hand|backhand|game|halt|palm|raised|raised back of hand|request|roshambo|stop"}, {0xf255, false, "hand back fist|fist|game|roshambo"}, {0xf461, false, "hand dots|allergy|freckles|hand|hives|palm|pox|skin|spots"}, {0xf6de, false, "hand fist|Dungeons & Dragons|clenched|d&d|dnd|fantasy|fist|hand|ki|monk|punch|raised fist|resist|strength|unarmed combat"}, {0xf4bd, false, "hand holding|carry|lift"}, {0xf4c0, false, "hand holding dollar|$|carry|coupon|dollar sign|donate|donation|giving|investment|lift|money|premium|price|revenue|salary"}, {0xf4c1, false, "hand holding droplet|blood|carry|covid-19|drought|grow|lift|sanitation"}, {0xe4f7, false, "hand holding hand|care|give|help|hold|protect"}, {0xf4be, false, "hand holding heart|carry|charity|gift|lift|package|wishlist"}, {0xe05c, false, "hand holding medical|care|covid-19|donate|help"}, {0xf258, false, "hand lizard|game|roshambo"}, {0xf806, false, "hand middle finger|finger|flip the bird|gesture|hand|hate|middle finger|rude"}, {0xf25b, false, "hand peace|hand|rest|truce|v|victory|victory hand"}, {0xf0a7, false, "hand point down|finger|hand-o-down|point"}, {0xf0a5, false, "hand point left|back|finger|hand-o-left|left|point|previous"}, {0xf0a4, false, "hand point right|finger|forward|hand-o-right|next|point|right"}, {0xf0a6, false, "hand point up|finger|hand|hand-o-up|index|index pointing up|point|request|up|upgrade"}, {0xf25a, false, "hand pointer|arrow|cursor|select"}, {0xf257, false, "hand scissors|cut|game|roshambo"}, {0xe05d, false, "hand sparkles|clean|covid-19|hygiene|magic|palm|soap|wash"}, {0xf259, false, "hand spock|finger|hand|live long|palm|prosper|salute|spock|star trek|vulcan|vulcan salute"}, {0xe4f8, false, "handcuffs|arrest|criminal|handcuffs|jail|lock|police|wrist"}, {0xf2a7, false, "hands|Translate|asl|deaf|hands"}, {0xf2a3, false, "hands asl interpreting|asl|deaf|finger|hand|interpret|speak"}, {0xe4f9, false, "hands bound|abduction|bound|handcuff|wrist"}, {0xe05e, false, "hands bubbles|covid-19|hygiene|soap|wash"}, {0xe1a8, false, "hands clapping|applause|clap|clapping hands|hand"}, {0xf4c2, false, "hands holding|carry|hold|lift"}, {0xe4fa, false, "hands holding child|care|give|help|hold|parent|protect"}, {0xe4fb, false, "hands holding circle|circle|gift|protection"}, {0xf684, false, "hands praying|kneel|preach|religion|worship"}, {0xf2b5, false, "handshake|agreement|greeting|meeting|partnership"}, {0xf4c4, false, "handshake angle|aid|assistance|handshake|partnership|volunteering"}, {0xf4c6, false, "handshake simple|agreement|greeting|hand|handshake|meeting|partnership|shake"}, {0xe05f, false, "handshake simple slash|broken|covid-19|disabled|social distance"}, {0xe060, false, "handshake slash|broken|covid-19|disabled|social distance"}, {0xf6e6, false, "hanukiah|candelabrum|candle|candlestick|hanukkah|jewish|judaism|light|menorah|religion"}, {0xf0a0, false, "hard drive|Hard Disk|cpu|hard drive|harddrive|machine|save|storage"}, {0x23, false, "hashtag|Number Sign|Twitter|instagram|pound|social media|tag"}, {0xf8c0, false, "hat cowboy|buckaroo|horse|jackeroo|john b.|old west|pardner|ranch|rancher|rodeo|western|wrangler"}, {0xf8c1, false, "hat cowboy side|buckaroo|horse|jackeroo|john b.|old west|pardner|ranch|rancher|rodeo|western|wrangler"}, {0xf6e8, false, "hat wizard|Dungeons & Dragons|accessory|buckle|clothing|d&d|dnd|fantasy|halloween|head|holiday|mage|magic|pointy|witch"}, {0xe061, false, "head side cough|cough|covid-19|germs|lungs|respiratory|sick|uer"}, {0xe062, false, "head side cough slash|cough|covid-19|disabled|germs|lungs|respiratory|sick|uer"}, {0xe063, false, "head side mask|breath|coronavirus|covid-19|filter|flu|infection|pandemic|respirator|uer|virus"}, {0xe064, false, "head side virus|cold|coronavirus|covid-19|flu|infection|pandemic|sick|uer"}, {0xf1dc, false, "heading|format|header|text|title"}, {0xf025, false, "headphones|audio|earbud|headphone|listen|music|sound|speaker"}, {0xf58f, false, "headphones simple|audio|listen|music|sound|speaker"}, {0xf590, false, "headset|audio|gamer|gaming|listen|live chat|microphone|shot caller|sound|support|telemarketer"}, {0xf004, false, "heart|ace|black|black heart|blue|blue heart|brown|brown heart|card|evil|favorite|game|green|green heart|heart|heart suit|like|love|orange|orange heart|purple|purple heart|red heart|relationship|valentine|white|white heart|wicked|wishlist|yellow|yellow heart"}, {0xe4fc, false, "heart circle bolt|cardiogram|ekg|electric|heart|love|pacemaker"}, {0xe4fd, false, "heart circle check|enable|favorite|heart|love|not affected|ok|okay|validate|working"}, {0xe4fe, false, "heart circle exclamation|failed|favorite|heart|love"}, {0xe4ff, false, "heart circle minus|favorite|heart|love"}, {0xe500, false, "heart circle plus|favorite|heart|love"}, {0xe501, false, "heart circle xmark|favorite|heart|love|uncheck"}, {0xf7a9, false, "heart crack|break|breakup|broken|broken heart|crushed|dislike|dumped|grief|love|lovesick|relationship|sad"}, {0xf21e, false, "heart pulse|ekg|electrocardiogram|health|lifeline|vital signs"}, {0xf533, false, "helicopter|airwolf|apache|chopper|flight|fly|helicopter|travel|vehicle"}, {0xe502, false, "helicopter symbol|chopper|helicopter|landing pad|whirlybird"}, {0xf807, false, "helmet safety|construction|hardhat|helmet|maintenance|safety"}, {0xe503, false, "helmet un|helmet|united nations"}, {0xf591, false, "highlighter|edit|marker|modify|sharpie|update|write"}, {0xe507, false, "hill avalanche|mudslide|snow|winter"}, {0xe508, false, "hill rockslide|mudslide"}, {0xf6ed, false, "hippo|animal|fauna|hippo|hippopotamus|hungry|mammal"}, {0xf453, false, "hockey puck|ice|nhl|sport"}, {0xf7aa, false, "holly berry|catwoman|christmas|decoration|flora|halle|holiday|ororo munroe|plant|storm|xmas"}, {0xf6f0, false, "horse|equestrian|equus|fauna|horse|mammmal|mare|neigh|pony|racehorse|racing"}, {0xf7ab, false, "horse head|equus|fauna|mammmal|mare|neigh|pony"}, {0xf0f8, false, "hospital|building|covid-19|doctor|emergency room|hospital|medical center|medicine"}, {0xf80d, false, "hospital user|covid-19|doctor|network|patient|primary care|uer"}, {0xf593, false, "hot tub person|jacuzzi|spa|uer"}, {0xf80f, false, "hotdog|bun|chili|frankfurt|frankfurter|hot dog|hotdog|kosher|polish|sandwich|sausage|vienna|weiner"}, {0xf594, false, "hotel|building|hotel|inn|lodging|motel|resort|travel"}, {0xf254, false, "hourglass|hour|hourglass|hourglass not done|minute|sand|stopwatch|time|timer"}, {0xf253, false, "hourglass end|hour|hourglass done|minute|pending|sand|stopwatch|time|timer|waiting"}, {0xf252, false, "hourglass half|hour|minute|pending|sand|stopwatch|time|waiting"}, {0xf251, false, "hourglass start|hour|minute|sand|stopwatch|time|waiting"}, {0xf015, false, "house|abode|building|home|house|main|residence"}, {0xe3af, false, "house chimney|abode|building|chimney|house|main|residence|smokestack"}, {0xf6f1, false, "house chimney crack|building|devastation|disaster|earthquake|home|insurance"}, {0xf7f2, false, "house chimney medical|covid-19|doctor|general practitioner|hospital|infirmary|medicine|office|outpatient"}, {0xe065, false, "house chimney user|covid-19|home|isolation|quarantine|uer"}, {0xe00d, false, "house chimney window|abode|building|family|home|residence"}, {0xe509, false, "house circle check|abode|enable|home|house|not affected|ok|okay|validate|working"}, {0xe50a, false, "house circle exclamation|abode|affected|failed|home|house"}, {0xe50b, false, "house circle xmark|abode|destroy|home|house|uncheck"}, {0xe3b1, false, "house crack|building|devastation|disaster|earthquake|home|insurance"}, {0xe50c, false, "house fire|burn|emergency|home"}, {0xe50d, false, "house flag|camp|home"}, {0xe50e, false, "house flood water|damage|flood|water"}, {0xe50f, false, "house flood water circle arrow right|damage|flood|water"}, {0xe066, false, "house laptop|computer|covid-19|device|office|remote|work from home"}, {0xe510, false, "house lock|closed|home|house|lockdown|padlock|privacy|quarantine"}, {0xe3b2, false, "house medical|covid-19|doctor|facility|general practitioner|health|hospital|infirmary|medicine|office|outpatient"}, {0xe511, false, "house medical circle check|clinic|enable|hospital|not affected|ok|okay|validate|working"}, {0xe512, false, "house medical circle exclamation|affected|clinic|failed|hospital"}, {0xe513, false, "house medical circle xmark|clinic|destroy|hospital|uncheck"}, {0xe514, false, "house medical flag|clinic|hospital|mash"}, {0xe012, false, "house signal|abode|building|connect|family|home|residence|smart home|wifi|www"}, {0xe515, false, "house tsunami|damage|flood|tidal wave|wave"}, {0xe1b0, false, "house user|house|uer"}, {0xf6f2, false, "hryvnia sign|Hryvnia Sign|currency"}, {0xf751, false, "hurricane|coriolis effect|eye|storm|tropical cyclone|typhoon"}, {0x49, false, "i|Latin Capital Letter I|Latin Small Letter I|letter"}, {0xf246, false, "i cursor|editing|i-beam|type|writing"}, {0xf810, false, "ice cream|chocolate|cone|cream|dessert|frozen|ice|ice cream|scoop|sorbet|sweet|vanilla|yogurt"}, {0xf7ad, false, "icicles|cold|frozen|hanging|ice|seasonal|sharp"}, {0xf86d, false, "icons|bolt|category|emoji|heart|image|music|photo|symbols"}, {0xf2c1, false, "id badge|address|contact|identification|license|profile|uer|username"}, {0xf2c2, false, "id card|contact|demographics|document|identification|issued|profile|registration|uer|username"}, {0xf47f, false, "id card clip|contact|demographics|document|identification|issued|profile|uer|username"}, {0xf7ae, false, "igloo|dome|dwelling|eskimo|home|house|ice|snow"}, {0xf03e, false, "image|album|img|landscape|photo|picture"}, {0xf3e0, false, "image portrait|id|image|img|photo|picture|selfie|uer|username"}, {0xf302, false, "images|album|img|landscape|photo|picture"}, {0xf01c, false, "inbox|archive|desk|email|mail|message"}, {0xf03c, false, "indent|align|justify|paragraph|tab"}, {0xe1bc, false, "indian rupee sign|Indian Rupee Sign|currency"}, {0xf275, false, "industry|building|factory|industrial|manufacturing|mill|warehouse"}, {0xf534, false, "infinity|Infinity|eternity|forever|infinity|math|unbounded|universal"}, {0xf129, false, "info|details|help|information|more|support"}, {0xf033, false, "italic|edit|emphasis|font|format|text|type"}, {0x4a, false, "j|Latin Capital Letter J|Latin Small Letter J|letter"}, {0xe516, false, "jar|jam|jelly|storage"}, {0xe517, false, "jar wheat|flour|storage"}, {0xf669, false, "jedi|crest|force|sith|skywalker|star wars|yoda"}, {0xf0fb, false, "jet fighter|airforce|airplane|airport|fast|fly|goose|marines|maverick|military|plane|quick|top gun|transportation|travel"}, {0xe518, false, "jet fighter up|airforce|airplane|airport|fast|fly|goose|marines|maverick|military|plane|quick|top gun|transportation|travel"}, {0xf595, false, "joint|blunt|cannabis|doobie|drugs|marijuana|roach|smoke|smoking|spliff"}, {0xe519, false, "jug detergent|detergent|laundry|soap|wash"}, {0x4b, false, "k|Latin Capital Letter K|Latin Small Letter K|letter"}, {0xf66b, false, "kaaba|Muslim|building|cube|islam|kaaba|muslim|religion"}, {0xf084, false, "key|key|lock|password|private|secret|unlock"}, {0xf11c, false, "keyboard|accessory|computer|edit|input|keyboard|text|type|write"}, {0xf66d, false, "khanda|Adi Shakti|chakkar|sikh|sikhism|sword"}, {0xe1c4, false, "kip sign|Kip Sign|currency"}, {0xf479, false, "kit medical|emergency|emt|health|medical|rescue"}, {0xe51a, false, "kitchen set|chef|cook|cup|kitchen|pan|pot|skillet"}, {0xf535, false, "kiwi bird|bird|fauna|new zealand"}, {0x4c, false, "l|Latin Capital Letter L|Latin Small Letter L|letter"}, {0xe51b, false, "land mine on|bomb|danger|explosion|war"}, {0xf66f, false, "landmark|building|classical|historic|memorable|monument|museum|politics|society"}, {0xf752, false, "landmark dome|building|historic|memorable|monument|politics"}, {0xe51c, false, "landmark flag|capitol|flag|landmark|memorial"}, {0xf1ab, false, "language|dialect|idiom|localize|speech|translate|vernacular"}, {0xf109, false, "laptop|computer|cpu|dell|demo|device|fabook|fb|laptop|mac|macbook|machine|pc|personal"}, {0xf5fc, false, "laptop code|computer|cpu|dell|demo|develop|device|fabook|fb|mac|macbook|machine|mysql|pc|sql"}, {0xe51d, false, "laptop file|computer|education|laptop|learning|remote work"}, {0xf812, false, "laptop medical|computer|device|ehr|electronic health records|history"}, {0xe1c8, false, "lari sign|Lari Sign|currency"}, {0xf5fd, false, "layer group|arrange|category|develop|layers|map|platform|stack"}, {0xf06c, false, "leaf|eco|flora|nature|plant|vegan"}, {0xf30a, false, "left long|back|long-arrow-left|previous"}, {0xf337, false, "left right|arrow|arrows-h|expand|horizontal|landscape|left-right arrow|resize|wide"}, {0xf094, false, "lemon|citrus|fruit|lemon|lemonade|lime|tart"}, {0x3c, false, "less than|Less-Than Sign|arithmetic|compare|math"}, {0xf537, false, "less than equal|arithmetic|compare|math"}, {0xf1cd, false, "life ring|coast guard|help|overboard|save|support"}, {0xf0eb, false, "lightbulb| comic| electric| idea| innovation| inspiration| light| light bulb| bulb|bulb|comic|electric|energy|idea|inspiration|mechanical"}, {0xe51e, false, "lines leaning|canted|domino|falling|resilience|resilient|tipped"}, {0xf0c1, false, "link|attach|attachment|chain|connect|lin|link"}, {0xf127, false, "link slash|attachment|chain|chain-broken|disabled|disconnect|remove"}, {0xf195, false, "lira sign|Lira Sign|currency"}, {0xf03a, false, "list|bullet|category|cheatsheet|checklist|completed|done|finished|ol|summary|todo|ul"}, {0xf0ae, false, "list check|bullet|cheatsheet|checklist|downloading|downloads|enable|loading|progress|project management|settings|summary|to do|validate|working"}, {0xf0cb, false, "list ol|cheatsheet|checklist|completed|done|finished|numbers|ol|summary|todo|ul"}, {0xf0ca, false, "list ul|bullet|cheatsheet|checklist|completed|done|finished|ol|summary|survey|todo|ul"}, {0xe1d3, false, "litecoin sign|currency"}, {0xf124, false, "location arrow|address|compass|coordinate|direction|gps|map|navigation|place"}, {0xf601, false, "location crosshairs|address|coordinate|direction|gps|location|map|navigation|place|where"}, {0xf3c5, false, "location dot|address|coordinates|destination|gps|localize|location|map|navigation|paper|pin|place|point of interest|position|route|travel"}, {0xf041, false, "location pin|address|coordinates|destination|gps|localize|location|map|navigation|paper|pin|place|point of interest|position|route|travel"}, {0xe51f, false, "location pin lock|closed|lockdown|map|padlock|privacy|quarantine"}, {0xf023, false, "lock|admin|closed|lock|locked|open|padlock|password|privacy|private|protect|security"}, {0xf3c1, false, "lock open|admin|lock|open|padlock|password|privacy|private|protect|security|unlock"}, {0xe520, false, "locust|horde|infestation|locust|plague|swarm"}, {0xf604, false, "lungs|air|breath|covid-19|exhalation|inhalation|lungs|organ|respiration|respiratory"}, {0xe067, false, "lungs virus|breath|coronavirus|covid-19|flu|infection|pandemic|respiratory|sick"}, {0x4d, false, "m|Latin Capital Letter M|Latin Small Letter M|letter"}, {0xf076, false, "magnet|Attract|attraction|horseshoe|lodestone|magnet|magnetic|tool"}, {0xf002, false, "magnifying glass|bigger|enlarge|equipment|find|glass|inspection|magnifier|magnify|magnifying|magnifying glass tilted left|preview|search|tool|zoom"}, {0xe521, false, "magnifying glass arrow right|find|magnifier|next|search"}, {0xe522, false, "magnifying glass chart| data| graph| intelligence|analysis|chart|magnifier|market|revenue"}, {0xf688, false, "magnifying glass dollar|bigger|enlarge|find|magnifier|magnify|money|preview|zoom"}, {0xf689, false, "magnifying glass location|bigger|enlarge|find|magnifier|magnify|preview|zoom"}, {0xf010, false, "magnifying glass minus|magnifier|minify|negative|smaller|zoom|zoom out"}, {0xf00e, false, "magnifying glass plus|bigger|enlarge|magnifier|magnify|positive|zoom|zoom in"}, {0xe1d5, false, "manat sign|Manat Sign|currency"}, {0xf279, false, "map|address|coordinates|destination|gps|localize|location|map|navigation|paper|pin|place|point of interest|position|route|travel|world|world map"}, {0xf59f, false, "map location|address|coordinates|destination|gps|localize|location|map|navigation|paper|pin|place|point of interest|position|route|travel"}, {0xf5a0, false, "map location dot|address|coordinates|destination|gps|localize|location|map|navigation|paper|pin|place|point of interest|position|route|travel"}, {0xf276, false, "map pin|address|agree|coordinates|destination|gps|localize|location|map|marker|navigation|pin|place|position|pushpin|round pushpin|travel"}, {0xf5a1, false, "marker|design|edit|modify|sharpie|update|write"}, {0xf222, false, "mars|gender|male|male sign|man"}, {0xf224, false, "mars and venus|Male and Female Sign|female|gender|intersex|male|transgender"}, {0xe523, false, "mars and venus burst|gender|uer|violence"}, {0xf227, false, "mars double|Doubled Male Sign|gay|gender|male|men"}, {0xf229, false, "mars stroke|Male with Stroke Sign|gender|transgender"}, {0xf22b, false, "mars stroke right|Horizontal Male with Stroke Sign|gender"}, {0xf22a, false, "mars stroke up|Vertical Male with Stroke Sign|gender"}, {0xf57b, false, "martini glass|alcohol|bar|beverage|cocktail|cocktail glass|drink|glass|liquor"}, {0xf561, false, "martini glass citrus|alcohol|beverage|drink|gin|glass|margarita|martini|vodka"}, {0xf000, false, "martini glass empty|alcohol|bar|beverage|drink|liquor"}, {0xf6fa, false, "mask|carnivale|costume|disguise|halloween|secret|super hero"}, {0xe1d7, false, "mask face|breath|coronavirus|covid-19|filter|flu|infection|pandemic|respirator|virus"}, {0xe524, false, "mask ventilator|breath|gas|mask|oxygen|respirator|ventilator"}, {0xf630, false, "masks theater|art|comedy|mask|perform|performing|performing arts|theater|theatre|tragedy"}, {0xe525, false, "mattress pillow|air mattress|mattress|pillow|rest|sleep"}, {0xf31e, false, "maximize| maximize| resize| scale| arrows| bigger| enlarge| fullscreen| resize| size|expand"}, {0xf5a2, false, "medal|award|guarantee|medal|quality|ribbon|sports medal|star|trophy|warranty"}, {0xf538, false, "memory|DIMM|RAM|hardware|storage|technology"}, {0xf676, false, "menorah|candle|hanukkah|jewish|judaism|light"}, {0xf223, false, "mercury|Mercury|gender|hybrid|transgender"}, {0xf27a, false, "message| conversation| discussion| talking|answer|bubble|chat|commenting|conversation|feedback|message|note|notification|sms|speech|talk|texting"}, {0xf753, false, "meteor|armageddon|asteroid|comet|shooting star|space"}, {0xf2db, false, "microchip|cpu|hardware|processor|technology"}, {0xf130, false, "microphone|address|audio|information|podcast|public|record|sing|sound|talking|voice"}, {0xf3c9, false, "microphone lines|audio|mic|microphone|music|podcast|record|sing|sound|studio|studio microphone|talking|voice"}, {0xf539, false, "microphone lines slash|audio|disable|disabled|disconnect|disconnect|mute|podcast|record|sing|sound|voice"}, {0xf131, false, "microphone slash|audio|disable|disabled|mute|podcast|record|sing|sound|voice"}, {0xf610, false, "microscope|covid-19|electron|knowledge|lens|microscope|optics|science|shrink|testing|tool"}, {0xe1ed, false, "mill sign|Mill Sign|currency"}, {0xf78c, false, "minimize|collapse|fullscreen|minimize|move|resize|shrink|smaller"}, {0xf068, false, "minus|En Dash|Minus Sign|collapse|delete|hide|math|minify|minus|negative|remove|sign|trash|−"}, {0xf7b5, false, "mitten|clothing|cold|glove|hands|knitted|seasonal|warmth"}, {0xf3ce, false, "mobile|android|call|cell|cell phone|device|mobile|mobile phone|number|phone|screen|telephone|text"}, {0xf10b, false, "mobile button|apple|call|cell phone|device|iphone|number|screen|telephone"}, {0xe527, false, "mobile retro|cellphone|cellular|phone"}, {0xf3cf, false, "mobile screen|android|call|cell phone|device|number|screen|telephone|text"}, {0xf3cd, false, "mobile screen button|apple|call|cell phone|device|iphone|number|screen|telephone"}, {0xf0d6, false, "money bill|buy|cash|checkout|coupon|investment|money|payment|premium|price|purchase|revenue|salary"}, {0xf3d1, false, "money bill 1|buy|cash|checkout|money|payment|premium|price|purchase|salary"}, {0xf53b, false, "money bill 1 wave|buy|cash|checkout|money|payment|premium|price|purchase|salary"}, {0xe528, false, "money bill transfer|bank|conversion|deposit|investment|money|salary|transfer|withdrawal"}, {0xe529, false, "money bill trend up|bank|bonds|inflation|investment|market|revenue|salary|stocks|trade"}, {0xf53a, false, "money bill wave|buy|cash|checkout|money|payment|premium|price|purchase|salary"}, {0xe52a, false, "money bill wheat|agribusiness|agriculture|farming|food|investment|livelihood|subsidy"}, {0xe1f3, false, "money bills|atm|cash|investment|money|moolah|premium|revenue|salary"}, {0xf53c, false, "money check|bank check|buy|checkout|cheque|money|payment|price|purchase|salary"}, {0xf53d, false, "money check dollar|bank check|buy|checkout|cheque|money|payment|price|purchase|salary"}, {0xf5a6, false, "monument|building|historic|landmark|memorable"}, {0xf186, false, "moon|Power Sleep Symbol|contrast|crescent|crescent moon|dark|lunar|moon|night"}, {0xf5a7, false, "mortar pestle|crush|culinary|grind|medical|mix|pharmacy|prescription|spices"}, {0xf678, false, "mosque|Muslim|building|islam|landmark|mosque|muslim|religion"}, {0xe52b, false, "mosquito|bite|bug|mosquito|west nile"}, {0xe52c, false, "mosquito net|bite|malaria|mosquito|net"}, {0xf21c, false, "motorcycle|bike|machine|motorcycle|racing|transportation|vehicle"}, {0xe52d, false, "mound|barrier|hill|pitcher|speedbump"}, {0xf6fc, false, "mountain|cold|glacier|hiking|hill|landscape|mountain|snow|snow-capped mountain|travel|view"}, {0xe52e, false, "mountain city|location|rural|urban"}, {0xe52f, false, "mountain sun|country|hiking|landscape|rural|travel|view"}, {0xf7b6, false, "mug hot|beverage|caliente|cocoa|coffee|cup|drink|holiday|hot|hot beverage|hot chocolate|steam|steaming|tea|warmth"}, {0xf0f4, false, "mug saucer|beverage|breakfast|cafe|drink|fall|morning|mug|seasonal|tea"}, {0xf001, false, "music|lyrics|melody|music|musical note|note|sing|sound"}, {0x4e, false, "n|Latin Capital Letter N|Latin Small Letter N|letter|nay|no"}, {0xe1f6, false, "naira sign|Naira Sign|currency"}, {0xf6ff, false, "network wired|computer|connect|ethernet|internet|intranet"}, {0xf22c, false, "neuter|Neuter|gender"}, {0xf1ea, false, "newspaper|article|editorial|headline|journal|journalism|news|newsletter|newspaper|paper|press"}, {0xf53e, false, "not equal|arithmetic|compare|math"}, {0xe1fe, false, "notdef|404|close|missing|not found"}, {0xf249, false, "note sticky|message|note|paper|reminder|sticker"}, {0xf481, false, "notes medical|clipboard|doctor|ehr|health|history|records"}, {0x4f, false, "o|Latin Capital Letter O|Latin Small Letter O|letter"}, {0xf247, false, "object group|combine|copy|design|merge|select"}, {0xf248, false, "object ungroup|copy|design|merge|select|separate"}, {0xf613, false, "oil can|auto|crude|gasoline|grease|lubricate|petroleum"}, {0xe532, false, "oil well|drill|oil|rig"}, {0xf679, false, "om|Hindu|buddhism|hinduism|jainism|mantra|om|religion"}, {0xf700, false, "otter|animal|badger|fauna|fishing|fur|mammal|marten|otter|playful"}, {0xf03b, false, "outdent|align|justify|paragraph|tab"}, {0x50, false, "p|Latin Capital Letter P|Latin Small Letter P|letter"}, {0xf815, false, "pager|beeper|cell phone|communication|page|pager"}, {0xf5aa, false, "paint roller|acrylic|art|brush|color|fill|maintenance|paint|pigment|watercolor"}, {0xf1fc, false, "paintbrush|acrylic|art|brush|color|fill|modify|paint|paintbrush|painting|pigment|watercolor"}, {0xf53f, false, "palette|acrylic|art|artist palette|brush|color|fill|museum|paint|painting|palette|pigment|watercolor"}, {0xf482, false, "pallet|archive|box|inventory|shipping|warehouse"}, {0xe209, false, "panorama|image|img|landscape|photo|wide"}, {0xf1d8, false, "paper plane|air|float|fold|mail|paper|send"}, {0xf0c6, false, "paperclip|attach|attachment|connect|link|papercli|paperclip"}, {0xf4cd, false, "parachute box|aid|assistance|goods|relief|rescue|supplies"}, {0xf1dd, false, "paragraph|Pilcrow Sign|edit|format|text|writing"}, {0xf5ab, false, "passport|document|id|identification|issued|travel"}, {0xf0ea, false, "paste|clipboard|copy|document|paper"}, {0xf04c, false, "pause|bar|double|hold|pause|pause button|vertical|wait"}, {0xf1b0, false, "paw|animal|cat|dog|pet|print"}, {0xf67c, false, "peace|peace|peace symbol|serenity|tranquility|truce|war"}, {0xf304, false, "pen|ballpoint|design|edit|modify|pen|update|write"}, {0xf305, false, "pen clip|design|edit|modify|update|write"}, {0xf5ac, false, "pen fancy|black nib|design|edit|fountain|fountain pen|modify|nib|pen|update|write"}, {0xf5ad, false, "pen nib|design|edit|fountain pen|modify|update|write"}, {0xf5ae, false, "pen ruler|design|draft|draw|maintenance|modify|pencil"}, {0xf044, false, "pen to square|edit|modify|pen|pencil|update|write"}, {0xf303, false, "pencil|Lower Left Pencil|design|draw|edit|lead|maintenance|modify|pencil|update|write"}, {0xe068, false, "people arrows| conversation| discussion| talking|distance|insert|isolation|separate|social distancing|talk|together|uer|users-people"}, {0xf4ce, false, "people carry box|together|uer|users-people"}, {0xe533, false, "people group|crowd|family|group|team|together|uer"}, {0xe534, false, "people line|crowd|group|need|together|uer"}, {0xe535, false, "people pulling|forced return|together|uer|yanking"}, {0xe536, false, "people robbery|criminal|hands up|looting|robbery|steal|uer"}, {0xe537, false, "people roof|crowd|family|group|manage|people|safe|shelter|together|uer"}, {0xf816, false, "pepper hot|buffalo wings|capsicum|chili|chilli|habanero|hot|hot pepper|jalapeno|mexican|pepper|spicy|tabasco|vegetable"}, {0x25, false, "percent|Percent Sign|discount|fraction|proportion|rate|ratio"}, {0xf183, false, "person|default|man|person standing|stand|standing|uer|woman"}, {0xe538, false, "person arrow down to line|ground|indigenous|insert|native|uer"}, {0xe539, false, "person arrow up from line|population|rise|uer|upgrade"}, {0xf84a, false, "person biking|bicycle|bike|biking|cyclist|pedal|person biking|summer|uer|wheel"}, {0xf756, false, "person booth|changing room|curtain|uer|vote|voting"}, {0xe53a, false, "person breastfeeding|baby|child|infant|mother|nutrition|parent|sustenance|uer"}, {0xe53b, false, "person burst|abuse|accident|crash|explode|uer|violence"}, {0xe53c, false, "person cane|aging|cane|elderly|old|staff|uer"}, {0xe53d, false, "person chalkboard|blackboard|instructor|keynote|lesson|presentation|teacher|uer"}, {0xe53e, false, "person circle check|approved|enable|not affected|ok|okay|uer|validate|working"}, {0xe53f, false, "person circle exclamation|affected|alert|failed|lost|missing|uer"}, {0xe540, false, "person circle minus|delete|remove|uer"}, {0xe541, false, "person circle plus|add|follow|found|uer"}, {0xe542, false, "person circle question|faq|lost|missing|request|uer"}, {0xe543, false, "person circle xmark|dead|removed|uer|uncheck"}, {0xf85e, false, "person digging|bury|construction|debris|dig|maintenance|men at work|uer"}, {0xf470, false, "person dots from line|allergy|diagnosis|uer"}, {0xf182, false, "person dress|man|skirt|uer|woman"}, {0xe544, false, "person dress burst|abuse|accident|crash|explode|uer|violence"}, {0xe545, false, "person drowning|drown|emergency|swim|uer"}, {0xe546, false, "person falling|accident|fall|trip|uer"}, {0xe547, false, "person falling burst|accident|crash|death|fall|homicide|murder|uer"}, {0xe548, false, "person half dress|gender|man|restroom|transgender|uer|woman"}, {0xe549, false, "person harassing|abuse|scream|shame|shout|uer|yell"}, {0xf6ec, false, "person hiking|autumn|fall|follow|hike|mountain|outdoors|summer|uer|walk"}, {0xe54a, false, "person military pointing|army|customs|guard|uer"}, {0xe54b, false, "person military rifle|armed forces|army|military|rifle|uer|war"}, {0xe54c, false, "person military to person|civilian|coordination|military|uer"}, {0xf683, false, "person praying|kneel|place of worship|religion|thank|uer|worship"}, {0xe31e, false, "person pregnant|baby|birth|child|parent|pregnant|pregnant woman|uer|woman"}, {0xe54d, false, "person rays|affected|focus|shine|uer"}, {0xe54e, false, "person rifle|army|combatant|gun|military|rifle|uer|war"}, {0xf70c, false, "person running|exit|flee|follow|marathon|person running|race|running|uer|workout"}, {0xe54f, false, "person shelter|house|inside|roof|safe|safety|shelter|uer"}, {0xf7c5, false, "person skating|figure skating|ice|olympics|rink|skate|uer|winter"}, {0xf7c9, false, "person skiing|downhill|olympics|ski|skier|snow|uer|winter"}, {0xf7ca, false, "person skiing nordic|cross country|olympics|uer|winter"}, {0xf7ce, false, "person snowboarding|olympics|ski|snow|snowboard|snowboarder|uer|winter"}, {0xf5c4, false, "person swimming|ocean|person swimming|pool|sea|swim|uer|water"}, {0xe5a9, false, "person through window|door|exit|forced entry|leave|robbery|steal|uer|window"}, {0xf554, false, "person walking|crosswalk|exercise|follow|hike|move|person walking|uer|walk|walking|workout"}, {0xe551, false, "person walking arrow loop left|follow|population return|return|uer"}, {0xe552, false, "person walking arrow right|exit|follow|internally displaced|leave|refugee|uer"}, {0xe553, false, "person walking dashed line arrow right|exit|follow|refugee|uer"}, {0xe554, false, "person walking luggage|bag|baggage|briefcase|carry-on|deployment|follow|rolling|uer"}, {0xf29d, false, "person walking with cane|blind|cane|follow|uer"}, {0xe221, false, "peseta sign|Peseta Sign|currency"}, {0xe222, false, "peso sign|Peso Sign|currency"}, {0xf095, false, "phone|Left Hand Telephone Receiver|call|earphone|number|phone|receiver|support|talking|telephone|telephone receiver|voice"}, {0xf879, false, "phone flip|Right Hand Telephone Receiver|call|earphone|number|support|telephone|voice"}, {0xf3dd, false, "phone slash|call|cancel|disabled|disconnect|earphone|mute|number|support|telephone|voice"}, {0xf2a0, false, "phone volume|call|earphone|number|ring|ringing|sound|support|talking|telephone|voice|volume-control-phone"}, {0xf87c, false, "photo film|av|film|image|library|media"}, {0xf4d3, false, "piggy bank|bank|salary|save|savings"}, {0xf484, false, "pills|drugs|medicine|prescription|tablets"}, {0xf818, false, "pizza slice|cheese|chicago|italian|mozzarella|new york|pepperoni|pie|slice|teenage mutant ninja turtles|tomato"}, {0xf67f, false, "place of worship|building|church|holy|mosque|synagogue"}, {0xf072, false, "plane|airplane|airport|destination|fly|location|mode|travel|trip"}, {0xf5af, false, "plane arrival|aeroplane|airplane|airplane arrival|airport|arrivals|arriving|destination|fly|land|landing|location|mode|travel|trip"}, {0xe555, false, "plane circle check|airplane|airport|enable|flight|fly|not affected|ok|okay|travel|validate|working"}, {0xe556, false, "plane circle exclamation|affected|airplane|airport|failed|flight|fly|travel"}, {0xe557, false, "plane circle xmark|airplane|airport|destroy|flight|fly|travel|uncheck"}, {0xf5b0, false, "plane departure|aeroplane|airplane|airplane departure|airport|check-in|departing|departure|departures|destination|fly|location|mode|take off|taking off|travel|trip"}, {0xe558, false, "plane lock|airplane|airport|closed|flight|fly|lockdown|padlock|privacy|quarantine|travel"}, {0xe069, false, "plane slash|airplane mode|airport|canceled|covid-19|delayed|disabled|grounded|travel"}, {0xe22d, false, "plane up|airplane|airport|internet|signal|sky|wifi|wireless"}, {0xe5aa, false, "plant wilt|drought|planting|vegetation|wilt"}, {0xe55a, false, "plate wheat|bowl|hunger|rations|wheat"}, {0xf04b, false, "play|arrow|audio|music|play|play button|playing|right|sound|start|triangle|video"}, {0xf1e6, false, "plug|connect|electric|electric plug|electricity|online|plug|power"}, {0xe55b, false, "plug circle bolt|electric|electricity|plug|power"}, {0xe55c, false, "plug circle check|electric|electricity|enable|not affected|ok|okay|plug|power|validate|working"}, {0xe55d, false, "plug circle exclamation|affected|electric|electricity|failed|plug|power"}, {0xe55e, false, "plug circle minus|disconnect|electric|electricity|plug|power"}, {0xe55f, false, "plug circle plus|electric|electricity|plug|power"}, {0xe560, false, "plug circle xmark|destroy|disconnect|electric|electricity|outage|plug|power|uncheck"}, {0x2b, false, "plus|+|Plus Sign|add|create|expand|follow|math|modify|new|plus|positive|shape|sign"}, {0xe43c, false, "plus minus|Plus-Minus Sign|add|math|subtract"}, {0xf2ce, false, "podcast|audio|broadcast|music|sound"}, {0xf2fe, false, "poo|crap|dung|face|monster|pile of poo|poo|poop|shit|smile|turd|uer"}, {0xf75a, false, "poo storm|bolt|cloud|euphemism|lightning|mess|poop|shit|turd"}, {0xf619, false, "poop|crap|poop|shit|smile|turd"}, {0xf011, false, "power off|Power Symbol|cancel|computer|on|reboot|restart"}, {0xf5b1, false, "prescription|drugs|medical|medicine|pharmacy|rx"}, {0xf485, false, "prescription bottle|drugs|medical|medicine|pharmacy|rx"}, {0xf486, false, "prescription bottle medical|drugs|medical|medicine|pharmacy|rx"}, {0xf02f, false, "print|Print Screen Symbol|Printer Icon|business|computer|copy|document|office|paper|printer"}, {0xe06a, false, "pump medical|anti-bacterial|clean|covid-19|disinfect|hygiene|medical grade|sanitizer|soap"}, {0xe06b, false, "pump soap|anti-bacterial|clean|covid-19|disinfect|hygiene|sanitizer|soap"}, {0xf12e, false, "puzzle piece|add-on|addon|clue|game|interlocking|jigsaw|piece|puzzle|puzzle piece|section"}, {0x51, false, "q|Latin Capital Letter Q|Latin Small Letter Q|letter"}, {0xf029, false, "qrcode|barcode|info|information|scan"}, {0x3f, false, "question|?|Question Mark|faq|help|information|mark|outlined|punctuation|question|red question mark|request|support|unknown|white question mark"}, {0xf10d, false, "quote left|Left Double Quotation Mark|mention|note|phrase|text|type"}, {0xf10e, false, "quote right|Right Double Quotation Mark|mention|note|phrase|text|type"}, {0x52, false, "r|Latin Capital Letter R|Latin Small Letter R|letter"}, {0xf7b9, false, "radiation|danger|dangerous|deadly|hazard|nuclear|radioactive|warning"}, {0xf8d7, false, "radio|am|broadcast|fm|frequency|music|news|radio|receiver|transmitter|tuner|video"}, {0xf75b, false, "rainbow|gold|leprechaun|prism|rain|rainbow|sky"}, {0xe561, false, "ranking star|chart|first place|podium|quality|rank|revenue|win"}, {0xf543, false, "receipt|accounting|bookkeeping|check|coupon|evidence|invoice|money|pay|proof|receipt|table"}, {0xf8d9, false, "record vinyl|LP|album|analog|music|phonograph|sound"}, {0xf641, false, "rectangle ad|advertisement|media|newspaper|promotion|publicity"}, {0xf022, false, "rectangle list|cheatsheet|checklist|completed|done|finished|ol|summary|todo|ul"}, {0xf410, false, "rectangle xmark|browser|cancel|computer|development|uncheck"}, {0xf1b8, false, "recycle|Recycling Symbol For Generic Materials|Universal Recycling Symbol|Waste|compost|garbage|recycle|recycling symbol|reuse|trash"}, {0xf25d, false, "registered|copyright|mark|r|registered|trademark"}, {0xf363, false, "repeat|arrow|clockwise|flip|reload|renew|repeat|repeat button|retry|rewind|switch"}, {0xf3e5, false, "reply|mail|message|respond"}, {0xf122, false, "reply all|mail|message|respond"}, {0xf75e, false, "republican|american|conservative|election|elephant|politics|republican party|right|right-wing|usa"}, {0xf7bd, false, "restroom|bathroom|toilet|uer|water closet|wc"}, {0xf079, false, "retweet|refresh|reload|renew|retry|share|swap"}, {0xf4d6, false, "ribbon|badge|cause|celebration|lapel|pin|reminder|reminder ribbon|ribbon"}, {0xf2f5, false, "right from bracket|arrow|exit|leave|log out|logout|sign-out"}, {0xf362, false, "right left|arrow|arrows|exchange|reciprocate|return|swap|transfer"}, {0xf30b, false, "right long|forward|long-arrow-right|next"}, {0xf2f6, false, "right to bracket|arrow|enter|join|log in|login|sign in|sign up|sign-in|signin|signup"}, {0xf70b, false, "ring|Dungeons & Dragons|Gollum|band|binding|d&d|dnd|engagement|fantasy|gold|jewelry|marriage|precious|premium"}, {0xf018, false, "road|highway|map|motorway|pavement|road|route|street|travel"}, {0xe562, false, "road barrier|block|border|no entry|roadblock"}, {0xe563, false, "road bridge|bridge|infrastructure|road|travel"}, {0xe564, false, "road circle check|enable|freeway|highway|not affected|ok|okay|pavement|road|validate|working"}, {0xe565, false, "road circle exclamation|affected|failed|freeway|highway|pavement|road"}, {0xe566, false, "road circle xmark|destroy|freeway|highway|pavement|road|uncheck"}, {0xe567, false, "road lock|closed|freeway|highway|lockdown|padlock|pavement|privacy|quarantine|road"}, {0xe568, false, "road spikes|barrier|roadblock|spikes"}, {0xf544, false, "robot|android|automate|computer|cyborg|face|monster|robot"}, {0xf135, false, "rocket|aircraft|app|jet|launch|nasa|space"}, {0xf2f1, false, "rotate|arrow|clockwise|exchange|modify|refresh|reload|renew|retry|rotate|swap|withershins"}, {0xf2ea, false, "rotate left|back|control z|exchange|oops|return|swap"}, {0xf2f9, false, "rotate right|forward|refresh|reload|renew|repeat|retry"}, {0xf4d7, false, "route|directions|navigation|travel"}, {0xf09e, false, "rss|blog|feed|journal|news|writing"}, {0xf158, false, "ruble sign|Ruble Sign|currency"}, {0xe569, false, "rug|blanket|carpet|rug|textile"}, {0xf545, false, "ruler|design|draft|length|measure|planning|ruler|straight edge|straight ruler"}, {0xf546, false, "ruler combined|design|draft|length|measure|planning"}, {0xf547, false, "ruler horizontal|design|draft|length|measure|planning"}, {0xf548, false, "ruler vertical|design|draft|length|measure|planning"}, {0xf156, false, "rupee sign|Rupee Sign|currency"}, {0xe23d, false, "rupiah sign|currency"}, {0x53, false, "s|Latin Capital Letter S|Latin Small Letter S|letter"}, {0xf81d, false, "sack dollar|bag|burlap|cash|dollar|investment|money|money bag|moneybag|premium|robber|salary|santa|usd"}, {0xe56a, false, "sack xmark|bag|burlap|coupon|rations|salary|uncheck"}, {0xe445, false, "sailboat|dinghy|mast|sailboat|sailing|yacht"}, {0xf7bf, false, "satellite|communications|hardware|orbit|satellite|space"}, {0xf7c0, false, "satellite dish|SETI|antenna|communications|dish|hardware|radar|receiver|satellite|satellite antenna|saucer|signal|space"}, {0xf24e, false, "scale balanced|Libra|balance|balance scale|balanced|justice|law|legal|measure|rule|scale|weight|zodiac"}, {0xf515, false, "scale unbalanced|justice|legal|measure|unbalanced|weight"}, {0xf516, false, "scale unbalanced flip|justice|legal|measure|unbalanced|weight"}, {0xf549, false, "school|building|education|learn|school|student|teacher"}, {0xe56b, false, "school circle check|enable|not affected|ok|okay|schoolhouse|validate|working"}, {0xe56c, false, "school circle exclamation|affected|failed|schoolhouse"}, {0xe56d, false, "school circle xmark|destroy|schoolhouse|uncheck"}, {0xe56e, false, "school flag|educate|flag|school|schoolhouse"}, {0xe56f, false, "school lock|closed|lockdown|padlock|privacy|quarantine|schoolhouse"}, {0xf0c4, false, "scissors|Black Safety Scissors|White Scissors|clip|cutting|equipment|modify|scissors|snip|tool"}, {0xf54a, false, "screwdriver|admin|configuration|equipment|fix|maintenance|mechanic|modify|repair|screw|screwdriver|settings|tool"}, {0xf7d9, false, "screwdriver wrench|admin|configuration|equipment|fix|maintenance|modify|repair|screwdriver|settings|tools|wrench"}, {0xf70e, false, "scroll|Dungeons & Dragons|announcement|d&d|dnd|fantasy|paper|scholar|script|scroll"}, {0xf6a0, false, "scroll torah|book|jewish|judaism|religion|scroll"}, {0xf7c2, false, "sd card|image|img|memory|photo|save"}, {0xe447, false, "section|Section Sign|law|legal|silcrow"}, {0xf4d8, false, "seedling|environment|flora|grow|investment|plant|sapling|seedling|vegan|young"}, {0xf233, false, "server|computer|cpu|database|hardware|mysql|network|sql"}, {0xf61f, false, "shapes|blocks|build|circle|square|triangle"}, {0xf064, false, "share|forward|save|send|social"}, {0xf14d, false, "share from square|forward|save|send|social"}, {0xf1e0, false, "share nodes|forward|save|send|social"}, {0xe571, false, "sheet plastic|plastic|plastic wrap|protect|tarp|tarpaulin|waterproof"}, {0xf20b, false, "shekel sign|New Sheqel Sign|currency|ils|money"}, {0xf132, false, "shield|achievement|armor|award|block|cleric|defend|defense|holy|paladin|protect|safety|security|shield|weapon|winner"}, {0xe572, false, "shield cat|animal|feline|pet|protect|safety|veterinary"}, {0xe573, false, "shield dog|animal|canine|pet|protect|safety|veterinary"}, {0xf3ed, false, "shield halved|achievement|armor|award|block|cleric|defend|defense|holy|paladin|privacy|security|shield|weapon|winner"}, {0xe574, false, "shield heart|love|protect|safe|safety|shield|wishlist"}, {0xe06c, false, "shield virus|antibodies|barrier|coronavirus|covid-19|flu|health|infection|pandemic|protect|safety|vaccine"}, {0xf21a, false, "ship|boat|passenger|sea|ship|water"}, {0xf553, false, "shirt|clothing|fashion|garment|shirt|short sleeve|t-shirt|tshirt"}, {0xf54b, false, "shoe prints|feet|footprints|steps|walk"}, {0xf54f, false, "shop|bodega|building|buy|market|purchase|shopping|store"}, {0xe4a5, false, "shop lock|bodega|building|buy|closed|lock|lockdown|market|padlock|privacy|purchase|quarantine|shop|shopping|store"}, {0xe070, false, "shop slash|building|buy|closed|covid-19|disabled|purchase|shopping"}, {0xf2cc, false, "shower|bath|clean|faucet|shower|water"}, {0xe448, false, "shrimp|allergy|crustacean|prawn|seafood|shellfish|shrimp|tail"}, {0xf074, false, "shuffle|arrow|arrows|crossed|shuffle|shuffle tracks button|sort|swap|switch|transfer"}, {0xf197, false, "shuttle space|astronaut|machine|nasa|rocket|space|transportation"}, {0xf4d9, false, "sign hanging|directions|real estate|signage|wayfinding"}, {0xf012, false, "signal|antenna|antenna bars|bar|bars|cell|graph|mobile|online|phone|reception|status"}, {0xf5b7, false, "signature|John Hancock|cursive|name|username|writing"}, {0xf277, false, "signs post|directions|directory|map|signage|wayfinding"}, {0xf7c4, false, "sim card|hard drive|hardware|portable|storage|technology|tiny"}, {0xe06d, false, "sink|bathroom|covid-19|faucet|kitchen|wash"}, {0xf0e8, false, "sitemap|directory|hierarchy|ia|information architecture|organization"}, {0xf54c, false, "skull|bones|death|face|fairy tale|monster|skeleton|skull|uer|x-ray|yorick"}, {0xf714, false, "skull crossbones|Black Skull and Crossbones|Dungeons & Dragons|alert|bones|crossbones|d&d|danger|dangerous area|dead|deadly|death|dnd|face|fantasy|halloween|holiday|jolly-roger|monster|pirate|poison|skeleton|skull|skull and crossbones|warning"}, {0xf715, false, "slash|cancel|close|mute|off|stop|x"}, {0xf7cc, false, "sleigh|christmas|claus|fly|holiday|santa|sled|snow|xmas"}, {0xf1de, false, "sliders|adjust|configuration|modify|settings|sliders|toggle"}, {0xf75f, false, "smog|dragon|fog|haze|pollution|smoke|weather"}, {0xf48d, false, "smoking|cancer|cigarette|nicotine|smoking|smoking status|tobacco"}, {0xf2dc, false, "snowflake|Heavy Chevron Snowflake|cold|precipitation|rain|snow|snowfall|snowflake|winter"}, {0xf7d0, false, "snowman|cold|decoration|frost|frosty|holiday|snow|snowman|snowman without snow"}, {0xf7d2, false, "snowplow|clean up|cold|road|storm|winter"}, {0xe06e, false, "soap|bar|bathing|bubbles|clean|cleaning|covid-19|hygiene|lather|soap|soapdish|wash"}, {0xf696, false, "socks|business socks|business time|clothing|feet|flight of the conchords|socks|stocking|wednesday"}, {0xf5ba, false, "solar panel|clean|eco-friendly|energy|green|sun"}, {0xf0dc, false, "sort|filter|order"}, {0xf0dd, false, "sort down|arrow|descending|filter|insert|order|sort-desc"}, {0xf0de, false, "sort up|arrow|ascending|filter|order|sort-asc|upgrade"}, {0xf5bb, false, "spa|flora|massage|mindfulness|plant|wellness"}, {0xf67b, false, "spaghetti monster flying|agnosticism|atheism|flying spaghetti monster|fsm"}, {0xf891, false, "spell check|dictionary|edit|editor|enable|grammar|text|validate|working"}, {0xf717, false, "spider|arachnid|bug|charlotte|crawl|eight|halloween|insect|spider"}, {0xf110, false, "spinner|circle|loading|pending|progress"}, {0xf5bc, false, "splotch|Ink|blob|blotch|glob|stain"}, {0xf2e5, false, "spoon|cutlery|dining|scoop|silverware|spoon|tableware"}, {0xf5bd, false, "spray can|Paint|aerosol|design|graffiti|tag"}, {0xf5d0, false, "spray can sparkles|car|clean|deodorize|fresh|pine|scent"}, {0xf0c8, false, "square|Black Square|black medium square|block|box|geometric|shape|square|white medium square"}, {0xf14c, false, "square arrow up right|diagonal|new|open|send|share"}, {0xf150, false, "square caret down|arrow|caret-square-o-down|dropdown|expand|insert|menu|more|triangle"}, {0xf191, false, "square caret left|arrow|back|caret-square-o-left|previous|triangle"}, {0xf152, false, "square caret right|arrow|caret-square-o-right|forward|next|triangle"}, {0xf151, false, "square caret up|arrow|caret-square-o-up|collapse|triangle|upgrade|upload"}, {0xf14a, false, "square check|accept|agree|box|button|check|check box with check|check mark button|checkmark|confirm|correct|coupon|done|enable|mark|ok|select|success|tick|todo|validate|working|yes|✓"}, {0xf199, false, "square envelope|e-mail|email|letter|mail|message|notification|offer|support"}, {0xf45c, false, "square full|black large square|block|blue|blue square|box|brown|brown square|geometric|green|green square|orange|orange square|purple|purple square|red|red square|shape|square|white large square|yellow|yellow square"}, {0xf0fd, false, "square h|directions|emergency|hospital|hotel|letter|map"}, {0xf146, false, "square minus|collapse|delete|hide|minify|negative|remove|shape|trash"}, {0xe576, false, "square nfi|non-food item|supplies"}, {0xf540, false, "square parking|auto|car|garage|meter|parking"}, {0xf14b, false, "square pen|edit|modify|pencil-square|update|write"}, {0xe577, false, "square person confined|captivity|confined|uer"}, {0xf098, false, "square phone|call|earphone|number|support|telephone|voice"}, {0xf87b, false, "square phone flip|call|earphone|number|support|telephone|voice"}, {0xf0fe, false, "square plus|add|create|expand|new|positive|shape"}, {0xf682, false, "square poll horizontal|chart|graph|results|statistics|survey|trend|vote|voting"}, {0xf681, false, "square poll vertical|chart|graph|results|revenue|statistics|survey|trend|vote|voting"}, {0xf698, false, "square root variable|arithmetic|calculus|division|math"}, {0xf143, false, "square rss|blog|feed|journal|news|writing"}, {0xf1e1, false, "square share nodes|forward|save|send|social"}, {0xf360, false, "square up right|arrow|diagonal|direction|external-link-square|intercardinal|new|northeast|open|share|up-right arrow"}, {0xe578, false, "square virus|coronavirus|covid-19|disease|flu|infection|pandemic"}, {0xf2d3, false, "square xmark|close|cross|cross mark button|incorrect|mark|notice|notification|notify|problem|square|uncheck|window|wrong|x|×"}, {0xe579, false, "staff snake|asclepius|asklepian|health|serpent|wellness"}, {0xe289, false, "stairs|exit|steps|up"}, {0xf5bf, false, "stamp|art|certificate|imprint|rubber|seal"}, {0xe5af, false, "stapler|desktop|milton|office|paperclip|staple"}, {0xf005, false, "star|achievement|award|favorite|important|night|quality|rating|score|star|vip"}, {0xf699, false, "star and crescent|Muslim|islam|muslim|religion|star and crescent"}, {0xf089, false, "star half|achievement|award|rating|score|star-half-empty|star-half-full"}, {0xf5c0, false, "star half stroke|achievement|award|rating|score|star-half-empty|star-half-full"}, {0xf69a, false, "star of david|David|Jew|Jewish|jewish|judaism|religion|star|star of David"}, {0xf621, false, "star of life|doctor|emt|first aid|health|medical"}, {0xf154, false, "sterling sign|Pound Sign|currency"}, {0xf0f1, false, "stethoscope|covid-19|diagnosis|doctor|general practitioner|heart|hospital|infirmary|medicine|office|outpatient|stethoscope"}, {0xf04d, false, "stop|block|box|square|stop|stop button"}, {0xf2f2, false, "stopwatch|clock|reminder|stopwatch|time|waiting"}, {0xe06f, false, "stopwatch 20|ABCs|countdown|covid-19|happy birthday|i will survive|reminder|seconds|time|timer"}, {0xf54e, false, "store|bodega|building|buy|market|purchase|shopping|store"}, {0xe071, false, "store slash|building|buy|closed|covid-19|disabled|purchase|shopping"}, {0xf21d, false, "street view|directions|location|map|navigation|uer"}, {0xf0cc, false, "strikethrough|cancel|edit|font|format|modify|text|type"}, {0xf551, false, "stroopwafel|caramel|cookie|dessert|sweets|waffle"}, {0xf12c, false, "subscript|edit|font|format|text|type"}, {0xf0f2, false, "suitcase|baggage|luggage|move|packing|suitcase|travel|trip"}, {0xf0fa, false, "suitcase medical|first aid|firstaid|health|help|medical|supply|support"}, {0xf5c1, false, "suitcase rolling|baggage|luggage|move|suitcase|travel|trip"}, {0xf185, false, "sun|bright|brighten|contrast|day|lighter|rays|sol|solar|star|sun|sunny|weather"}, {0xe57a, false, "sun plant wilt|arid|droop|drought"}, {0xf12b, false, "superscript|edit|exponential|font|format|text|type"}, {0xf5c3, false, "swatchbook|Pantone|color|design|hue|palette"}, {0xf69b, false, "synagogue|Jew|Jewish|building|jewish|judaism|religion|star of david|synagogue|temple"}, {0xf48e, false, "syringe|covid-19|doctor|immunizations|medical|medicine|needle|shot|sick|syringe|vaccinate|vaccine"}, {0x54, false, "t|Latin Capital Letter T|Latin Small Letter T|letter"}, {0xf0ce, false, "table|category|data|excel|spreadsheet"}, {0xf00a, false, "table cells| excel|blocks|boxes|category|grid|spreadsheet|squares"}, {0xe678, false, "table cells column lock| blocks| boxes| column| excel| grid| lock| squares|category|spreadsheet"}, {0xf009, false, "table cells large| excel|blocks|boxes|category|grid|spreadsheet|squares"}, {0xe67a, false, "table cells row lock| blocks| boxes| column| grid| squares| category| column| excel| lock| lock| spreadsheet"}, {0xe691, false, "table cells row unlock| blocks| boxes| column| grid| squares| category| column| lock| lock| spreadsheet| excel| unlock"}, {0xf0db, false, "table columns|browser|category|dashboard|organize|panes|split"}, {0xf00b, false, "table list|category|cheatsheet|checklist|completed|done|finished|ol|summary|todo|ul"}, {0xf45d, false, "table tennis paddle ball|ball|bat|game|paddle|ping pong|table tennis"}, {0xf3fb, false, "tablet|device|kindle|screen"}, {0xf10a, false, "tablet button|apple|device|ipad|kindle|screen"}, {0xf3fa, false, "tablet screen button|apple|device|ipad|kindle|screen"}, {0xf490, false, "tablets|drugs|medicine|pills|prescription"}, {0xf566, false, "tachograph digital|data|distance|speed|tachometer"}, {0xf02b, false, "tag|discount|labe|label|price|shopping"}, {0xf02c, false, "tags|discount|label|price|shopping"}, {0xf4db, false, "tape|design|package|sticky"}, {0xe57b, false, "tarp|protection|tarp|tent|waterproof"}, {0xe57c, false, "tarp droplet|protection|tarp|tent|waterproof"}, {0xf1ba, false, "taxi|cab|cabbie|car|car service|lyft|machine|oncoming|oncoming taxi|taxi|transportation|travel|uber|vehicle"}, {0xf62e, false, "teeth|bite|dental|dentist|gums|mouth|smile|tooth"}, {0xf62f, false, "teeth open|dental|dentist|gums bite|mouth|smile|tooth"}, {0xe03f, false, "temperature arrow down|air conditioner|cold|heater|mercury|thermometer|winter"}, {0xe040, false, "temperature arrow up|air conditioner|cold|heater|mercury|thermometer|winter"}, {0xf2cb, false, "temperature empty|cold|mercury|status|temperature"}, {0xf2c7, false, "temperature full|fever|hot|mercury|status|temperature"}, {0xf2c9, false, "temperature half|mercury|status|temperature|thermometer|weather"}, {0xf769, false, "temperature high|cook|covid-19|mercury|summer|thermometer|warm"}, {0xf76b, false, "temperature low|cold|cool|covid-19|mercury|thermometer|winter"}, {0xf2ca, false, "temperature quarter|mercury|status|temperature"}, {0xf2c8, false, "temperature three quarters|mercury|status|temperature"}, {0xf7d7, false, "tenge sign|Tenge Sign|currency"}, {0xe57d, false, "tent|bivouac|campground|campsite|refugee|shelter|tent"}, {0xe57e, false, "tent arrow down to line| bivouac| campground| refugee| shelter| tent|campsite|permanent|refugee|shelter"}, {0xe57f, false, "tent arrow left right| bivouac| campground| refugee| shelter| tent|campsite|refugee|shelter|transition"}, {0xe580, false, "tent arrow turn left| bivouac| campground| refugee| shelter| tent|campsite|refugee|shelter|temporary"}, {0xe581, false, "tent arrows down| bivouac| campground| refugee| shelter| tent|campsite|insert|refugee|shelter|spontaneous"}, {0xe582, false, "tents| bivouac| campground| refugee| shelter| tent|bivouac|campground|campsite|refugee|shelter|tent"}, {0xf120, false, "terminal|code|coding|command|console|development|prompt|terminal"}, {0xf034, false, "text height|edit|font|format|modify|text|type"}, {0xf87d, false, "text slash|cancel|disabled|font|format|remove|style|text"}, {0xf035, false, "text width|edit|font|format|modify|text|type"}, {0xf491, false, "thermometer|covid-19|mercury|status|temperature"}, {0xf165, false, "thumbs down|-1|disagree|disapprove|dislike|down|hand|social|thumb|thumbs down|thumbs-o-down"}, {0xf164, false, "thumbs up|+1|agree|approve|favorite|hand|like|ok|okay|social|success|thumb|thumbs up|thumbs-o-up|up|yes|you got it dude"}, {0xf08d, false, "thumbtack|Black Pushpin|coordinates|location|marker|pin|pushpin|thumb-tack"}, {0xe68f, false, "thumbtack slash| coordinates| location| marker| pin| pushpin| thumb-tack| unpin|Black Pushpin"}, {0xf145, false, "ticket|admission|admission tickets|coupon|movie|pass|support|ticket|voucher"}, {0xf3ff, false, "ticket simple|admission|coupon|movie|pass|support|ticket|voucher"}, {0xe29c, false, "timeline|chronological|deadline|history|linear"}, {0xf204, false, "toggle off|button|off|on|switch"}, {0xf205, false, "toggle on|button|off|on|switch"}, {0xf7d8, false, "toilet|bathroom|flush|john|loo|pee|plumbing|poop|porcelain|potty|restroom|throne|toile|toilet|washroom|waste|wc"}, {0xf71e, false, "toilet paper|bathroom|covid-19|halloween|holiday|lavatory|paper towels|prank|privy|restroom|roll|roll of paper|toilet|toilet paper|wipe"}, {0xe072, false, "toilet paper slash|bathroom|covid-19|disabled|halloween|holiday|lavatory|leaves|prank|privy|restroom|roll|toilet|trouble|ut oh|wipe"}, {0xe583, false, "toilet portable|outhouse|toilet"}, {0xe584, false, "toilets portable|outhouse|toilet"}, {0xf552, false, "toolbox|admin|chest|configuration|container|equipment|fix|maintenance|mechanic|modify|repair|settings|tool|toolbox|tools"}, {0xf5c9, false, "tooth|bicuspid|dental|dentist|molar|mouth|teeth|tooth"}, {0xf6a1, false, "torii gate|building|religion|shinto|shinto shrine|shintoism|shrine"}, {0xf76f, false, "tornado|cloud|cyclone|dorothy|landspout|tornado|toto|twister|vortext|waterspout|weather|whirlwind"}, {0xf519, false, "tower broadcast|airwaves|antenna|communication|emergency|radio|reception|signal|waves"}, {0xe585, false, "tower cell|airwaves|antenna|communication|radio|reception|signal|waves"}, {0xe586, false, "tower observation|fire tower|view"}, {0xf722, false, "tractor|agriculture|farm|tractor|vehicle"}, {0xf25c, false, "trademark|copyright|mark|register|symbol|tm|trade mark|trademark"}, {0xf637, false, "traffic light|direction|light|road|signal|traffic|travel|vertical traffic light"}, {0xe041, false, "trailer|carry|haul|moving|travel"}, {0xf238, false, "train|bullet|commute|locomotive|railway|subway|train"}, {0xf239, false, "train subway|machine|railway|train|transportation|vehicle"}, {0xe5b4, false, "train tram|crossing|machine|mountains|seasonal|tram|transportation|trolleybus"}, {0xf225, false, "transgender|female|gender|intersex|male|transgender|transgender symbol"}, {0xf1f8, false, "trash|delete|garbage|hide|remove"}, {0xf829, false, "trash arrow up|back|control z|delete|garbage|hide|oops|remove|undo|upgrade"}, {0xf2ed, false, "trash can|delete|garbage|hide|remove|trash-o"}, {0xf82a, false, "trash can arrow up|back|control z|delete|garbage|hide|oops|remove|undo|upgrade"}, {0xf1bb, false, "tree|bark|evergreen tree|fall|flora|forest|investment|nature|plant|seasonal|tree"}, {0xe587, false, "tree city|building|city|urban"}, {0xf071, false, "triangle exclamation|alert|attention|danger|error|failed|important|notice|notification|notify|problem|required|warnin|warning"}, {0xf091, false, "trophy|achievement|award|cup|game|prize|trophy|winner"}, {0xe589, false, "trowel|build|construction|equipment|maintenance|tool"}, {0xe58a, false, "trowel bricks|build|construction|maintenance|reconstruction|tool"}, {0xf0d1, false, "truck|Black Truck|cargo|delivery|delivery truck|shipping|truck|vehicle"}, {0xe58b, false, "truck arrow right|access|fast|shipping|transport"}, {0xe58c, false, "truck droplet|blood|thirst|truck|water|water supply"}, {0xf48b, false, "truck fast|express|fedex|mail|overnight|package|quick|ups"}, {0xe58d, false, "truck field|supplies|truck"}, {0xe58e, false, "truck field un|supplies|truck|united nations"}, {0xe2b7, false, "truck front|shuttle|truck|van"}, {0xf0f9, false, "truck medical|ambulance|clinic|covid-19|emergency|emt|er|help|hospital|mobile|support|vehicle"}, {0xf63b, false, "truck monster|offroad|vehicle|wheel"}, {0xf4df, false, "truck moving|cargo|inventory|rental|vehicle"}, {0xf63c, false, "truck pickup|cargo|maintenance|pick-up|pickup|pickup truck|truck|vehicle"}, {0xe58f, false, "truck plane|airplane|plane|transportation|truck|vehicle"}, {0xf4de, false, "truck ramp box|box|cargo|delivery|inventory|moving|rental|vehicle"}, {0xf1e4, false, "tty|communication|deaf|telephone|teletypewriter|text"}, {0xe2bb, false, "turkish lira sign|Turkish Lira Sign|currency"}, {0xf3be, false, "turn down|arrow|down|level-down|right arrow curving down"}, {0xf3bf, false, "turn up|arrow|level-up|right arrow curving up"}, {0xf26c, false, "tv|computer|display|monitor|television"}, {0x55, false, "u|Latin Capital Letter U|Latin Small Letter U|letter"}, {0xf0e9, false, "umbrella|protection|rain|storm|wet"}, {0xf5ca, false, "umbrella beach|beach|beach with umbrella|protection|recreation|sand|shade|summer|sun|umbrella"}, {0xf0cd, false, "underline|edit|emphasis|format|modify|text|writing"}, {0xf29a, false, "universal access|uer|users-people"}, {0xf09c, false, "unlock|admin|lock|open|padlock|password|privacy|private|protect|unlock|unlocked"}, {0xf13e, false, "unlock keyhole|admin|lock|padlock|password|privacy|private|protect"}, {0xf338, false, "up down|Up Down Black Arrow|arrow|arrows-v|expand|portrait|resize|tall|up-down arrow|vertical"}, {0xf0b2, false, "up down left right|arrow|arrows|bigger|enlarge|expand|fullscreen|move|position|reorder|resize"}, {0xf30c, false, "up long|long-arrow-up|upgrade|upload"}, {0xf424, false, "up right and down left from center| maximize| resize| scale|arrows|bigger|enlarge|expand|fullscreen|resize|size"}, {0xf35d, false, "up right from square|external-link|new|open|share|upgrade"}, {0xf093, false, "upload|hard drive|import|publish|upgrade"}, {0xf007, false, "user|adult|bust|bust in silhouette|default|employee|gender-neutral|person|profile|silhouette|uer|unspecified gender|username|users-people"}, {0xf4fb, false, "user astronaut|avatar|clothing|cosmonaut|nasa|space|suit|uer"}, {0xf4fc, false, "user check|employee|enable|uer|users-people|validate|working"}, {0xf4fd, false, "user clock|employee|uer|users-people"}, {0xf0f0, false, "user doctor|covid-19|health|job|medical|nurse|occupation|physician|profile|surgeon|uer|worker"}, {0xf4fe, false, "user gear|employee|together|uer|users-people"}, {0xf501, false, "user graduate|uer|users-people"}, {0xf500, false, "user group|bust|busts in silhouette|crowd|employee|silhouette|together|uer|users-people"}, {0xf728, false, "user injured|employee|uer|users-people"}, {0xf406, false, "user large|employee|uer|users-people"}, {0xf4fa, false, "user large slash|disabled|disconnect|employee|uer|users-people"}, {0xf502, false, "user lock|employee|padlock|privacy|uer|users-people"}, {0xf503, false, "user minus|delete|employee|negative|remove|uer"}, {0xf504, false, "user ninja|assassin|avatar|dangerous|deadly|fighter|hidden|ninja|sneaky|stealth|uer"}, {0xf82f, false, "user nurse|covid-19|doctor|health|md|medical|midwife|physician|practitioner|surgeon|uer|worker"}, {0xf4ff, false, "user pen|employee|modify|uer|users-people"}, {0xf234, false, "user plus|add|avatar|employee|follow|positive|sign up|signup|team|uer"}, {0xf21b, false, "user secret|detective|sleuth|spy|uer|users-people"}, {0xf505, false, "user shield|employee|protect|safety|uer"}, {0xf506, false, "user slash|ban|delete|deny|disabled|disconnect|employee|remove|uer"}, {0xf507, false, "user tag|employee|uer|users-people"}, {0xf508, false, "user tie|administrator|avatar|business|clothing|employee|formal|offer|portfolio|professional|suit|uer"}, {0xf235, false, "user xmark|archive|delete|employee|remove|uer|uncheck|x"}, {0xf0c0, false, "users|employee|together|uer|users-people"}, {0xe591, false, "users between lines|covered|crowd|employee|group|people|together|uer"}, {0xf509, false, "users gear|employee|uer|users-people"}, {0xe592, false, "users line|crowd|employee|group|need|people|together|uer"}, {0xe593, false, "users rays|affected|crowd|employee|focused|group|people|uer"}, {0xe594, false, "users rectangle|crowd|employee|focus|group|people|reached|uer"}, {0xe073, false, "users slash|disabled|disconnect|employee|together|uer|users-people"}, {0xe595, false, "users viewfinder|crowd|focus|group|people|targeted|uer"}, {0xf2e7, false, "utensils|cooking|cutlery|dining|dinner|eat|food|fork|fork and knife|knife|restaurant"}, {0x56, false, "v|Latin Capital Letter V|Latin Small Letter V|letter"}, {0xf5b6, false, "van shuttle|airport|bus|machine|minibus|public-transportation|transportation|travel|vehicle"}, {0xe2c5, false, "vault|bank|important|investment|lock|money|premium|privacy|safe|salary"}, {0xf5cb, false, "vector square|anchors|lines|object|render|shape"}, {0xf221, false, "venus|female|female sign|gender|woman"}, {0xf226, false, "venus double|Doubled Female Sign|female|gender|lesbian"}, {0xf228, false, "venus mars|Interlocked Female and Male Sign|female|gender|heterosexual|male"}, {0xe085, false, "vest|biker|fashion|style"}, {0xe086, false, "vest patches|biker|fashion|style"}, {0xf492, false, "vial|ampule|chemist|chemistry|experiment|knowledge|lab|sample|science|test|test tube"}, {0xe596, false, "vial circle check|ampule|chemist|chemistry|enable|not affected|ok|okay|success|test tube|tube|vaccine|validate|working"}, {0xe597, false, "vial virus|ampule|coronavirus|covid-19|flue|infection|lab|laboratory|pandemic|test|test tube|vaccine"}, {0xf493, false, "vials|ampule|experiment|knowledge|lab|sample|science|test|test tube"}, {0xf03d, false, "video|camera|film|movie|record|video-camera"}, {0xf4e2, false, "video slash|add|create|disabled|disconnect|film|new|positive|record|video"}, {0xf6a7, false, "vihara|buddhism|buddhist|building|monastery"}, {0xe074, false, "virus|bug|coronavirus|covid-19|flu|health|infection|pandemic|sick|vaccine|viral"}, {0xe4a8, false, "virus covid|bug|covid-19|flu|health|infection|pandemic|vaccine|viral|virus"}, {0xe4a9, false, "virus covid slash|bug|covid-19|disabled|flu|health|infection|pandemic|vaccine|viral|virus"}, {0xe075, false, "virus slash|bug|coronavirus|covid-19|cure|disabled|eliminate|flu|health|infection|pandemic|sick|vaccine|viral"}, {0xe076, false, "viruses|bugs|coronavirus|covid-19|flu|health|infection|multiply|pandemic|sick|spread|vaccine|viral"}, {0xf897, false, "voicemail|answer|inbox|message|phone"}, {0xf770, false, "volcano|caldera|eruption|lava|magma|mountain|smoke|volcano"}, {0xf45f, false, "volleyball|ball|beach|game|olympics|sport|volleyball"}, {0xf028, false, "volume high|audio|higher|loud|louder|music|sound|speaker|speaker high volume"}, {0xf027, false, "volume low|audio|lower|music|quieter|soft|sound|speaker|speaker low volume"}, {0xf026, false, "volume off|audio|ban|music|mute|quiet|silent|sound"}, {0xf6a9, false, "volume xmark|audio|music|quiet|sound|speaker"}, {0xf729, false, "vr cardboard|3d|augment|google|reality|virtual"}, {0x57, false, "w|Latin Capital Letter W|Latin Small Letter W|letter"}, {0xf8ef, false, "walkie talkie|communication|copy|intercom|over|portable|radio|two way radio"}, {0xf555, false, "wallet|billfold|cash|currency|money|salary"}, {0xf0d0, false, "wand magic|autocomplete|automatic|mage|magic|spell|wand|witch|wizard"}, {0xe2ca, false, "wand magic sparkles|auto|magic|magic wand|trick|witch|wizard"}, {0xf72b, false, "wand sparkles|autocomplete|automatic|fantasy|halloween|holiday|magic|weapon|witch|wizard"}, {0xf494, false, "warehouse|building|capacity|garage|inventory|storage"}, {0xf773, false, "water|lake|liquid|ocean|sea|swim|wet"}, {0xf5c5, false, "water ladder|ladder|recreation|swim|water"}, {0xf83e, false, "wave square|frequency|pulse|signal"}, {0xe682, false, "web awesome| coding| components| crown| web|awesome"}, {0xf5cd, false, "weight hanging|anvil|heavy|measurement"}, {0xf496, false, "weight scale|health|measurement|scale|weight"}, {0xe2cd, false, "wheat awn|agriculture|autumn|fall|farming|grain"}, {0xe598, false, "wheat awn circle exclamation|affected|failed|famine|food|gluten|hunger|starve|straw"}, {0xf193, false, "wheelchair|disabled|uer|users-people"}, {0xe2ce, false, "wheelchair move|access|disabled|handicap|impairment|physical|uer|wheelchair symbol"}, {0xf7a0, false, "whiskey glass|alcohol|bar|beverage|bourbon|drink|glass|liquor|neat|rye|scotch|shot|tumbler|tumbler glass|whisky"}, {0xf1eb, false, "wifi|connection|hotspot|internet|network|signal|wireless|www"}, {0xf72e, false, "wind|air|blow|breeze|fall|seasonal|weather"}, {0xf2d0, false, "window maximize|Maximize|browser|computer|development|expand"}, {0xf2d1, false, "window minimize|Minimize|browser|collapse|computer|development"}, {0xf2d2, false, "window restore|browser|computer|development"}, {0xf72f, false, "wine bottle|alcohol|beverage|cabernet|drink|glass|grapes|merlot|sauvignon"}, {0xf4e3, false, "wine glass|alcohol|bar|beverage|cabernet|drink|glass|grapes|merlot|sauvignon|wine|wine glass"}, {0xf5ce, false, "wine glass empty|alcohol|beverage|cabernet|drink|grapes|merlot|sauvignon"}, {0xf159, false, "won sign|Won Sign|currency"}, {0xe599, false, "worm|dirt|garden|worm|wriggle"}, {0xf0ad, false, "wrench|configuration|construction|equipment|fix|mechanic|modify|plumbing|settings|spanner|tool|update|wrench"}, {0x58, false, "x|Latin Capital Letter X|Latin Small Letter X|letter|uncheck"}, {0xf497, false, "x ray|health|medical|radiological images|radiology|skeleton"}, {0xf00d, false, "xmark|Cancellation X|Multiplication Sign|Multiplication X|cancel|close|cross|cross mark|error|exit|incorrect|mark|multiplication|multiply|notice|notification|notify|problem|sign|uncheck|wrong|x|×"}, {0xe59a, false, "xmarks lines|barricade|barrier|fence|poison|roadblock"}, {0x59, false, "y|Latin Capital Letter Y|Latin Small Letter Y|letter|yay|yes"}, {0xf157, false, "yen sign|Yen Sign|currency"}, {0xf6ad, false, "yin yang|daoism|opposites|religion|tao|taoism|taoist|yang|yin|yin yang"}, {0x5a, false, "z|Latin Capital Letter Z|Latin Small Letter Z|letter"}, {0xe080, true, "42.group"}, {0xf26e, true, "500px"}, {0xf368, true, "accessible icon|accessibility|disabled|handicap|person|uer|wheelchair|wheelchair-alt"}, {0xf369, true, "accusoft"}, {0xf170, true, "app.net"}, {0xf36a, true, "adversal"}, {0xf36b, true, "affiliatetheme"}, {0xf834, true, "airbnb"}, {0xf36c, true, "algolia"}, {0xf642, true, "alipay"}, {0xf270, true, "amazon"}, {0xf42c, true, "amazon pay"}, {0xf36d, true, "amilia"}, {0xf17b, true, "android|robot"}, {0xf209, true, "angellist"}, {0xf36e, true, "angry creative"}, {0xf420, true, "angular"}, {0xf36f, true, "app store"}, {0xf370, true, "ios app store"}, {0xf371, true, "apper systems ab"}, {0xf179, true, "apple|fruit|ios|mac|operating system|os|osx"}, {0xf415, true, "apple pay"}, {0xf77a, true, "artstation"}, {0xf372, true, "asymmetrik, ltd."}, {0xf77b, true, "atlassian"}, {0xf373, true, "audible"}, {0xf41c, true, "autoprefixer"}, {0xf374, true, "avianex"}, {0xf421, true, "aviato"}, {0xf375, true, "amazon web services (aws)"}, {0xf2d5, true, "bandcamp"}, {0xf835, true, "battle.net"}, {0xf1b4, true, "behance"}, {0xe3d9, true, "bilibili"}, {0xf378, true, "bimobject"}, {0xf171, true, "bitbucket|atlassian|bitbucket-square|git"}, {0xf379, true, "bitcoin"}, {0xf37a, true, "bity"}, {0xf27e, true, "font awesome black tie|administrator"}, {0xf37b, true, "blackberry"}, {0xf37c, true, "blogger"}, {0xf37d, true, "blogger b"}, {0xe671, true, "bluesky|social network"}, {0xf293, true, "bluetooth|signal"}, {0xf294, true, "bluetooth"}, {0xf836, true, "bootstrap"}, {0xe340, true, "bots"}, {0xe63c, true, "brave"}, {0xe63d, true, "brave reverse"}, {0xf15a, true, "btc"}, {0xf837, true, "buffer"}, {0xf37f, true, "büromöbel-experte gmbh & co. kg."}, {0xf8a6, true, "buy n large"}, {0xf20d, true, "buysellads"}, {0xf785, true, "canadian maple leaf|canada|flag|flora|nature|plant"}, {0xf42d, true, "amazon pay credit card"}, {0xf1f3, true, "cc amex|amex"}, {0xf416, true, "apple pay credit card"}, {0xf24c, true, "diner's club credit card"}, {0xf1f2, true, "discover credit card"}, {0xf24b, true, "jcb credit card"}, {0xf1f1, true, "mastercard credit card"}, {0xf1f4, true, "paypal credit card"}, {0xf1f5, true, "stripe credit card"}, {0xf1f0, true, "visa credit card"}, {0xf380, true, "centercode"}, {0xf789, true, "centos|linux|operating system|os"}, {0xf268, true, "chrome|browser"}, {0xf838, true, "chromecast"}, {0xe07d, true, "cloudflare"}, {0xf383, true, "cloudscale.ch"}, {0xf384, true, "cloudsmith"}, {0xf385, true, "cloudversify"}, {0xe360, true, "cmplid"}, {0xf1cb, true, "codepen"}, {0xf284, true, "codie pie"}, {0xf78d, true, "confluence|atlassian"}, {0xf20e, true, "connect develop"}, {0xf26d, true, "contao"}, {0xf89e, true, "cotton bureau|clothing|t-shirts|tshirts"}, {0xf388, true, "cpanel"}, {0xf25e, true, "creative commons"}, {0xf4e7, true, "creative commons attribution"}, {0xf4e8, true, "creative commons noncommercial"}, {0xf4e9, true, "creative commons noncommercial (euro sign)"}, {0xf4ea, true, "creative commons noncommercial (yen sign)"}, {0xf4eb, true, "creative commons no derivative works"}, {0xf4ec, true, "creative commons public domain"}, {0xf4ed, true, "alternate creative commons public domain"}, {0xf4ee, true, "creative commons remix"}, {0xf4ef, true, "creative commons share alike"}, {0xf4f0, true, "creative commons sampling"}, {0xf4f1, true, "creative commons sampling +"}, {0xf4f2, true, "creative commons share"}, {0xf4f3, true, "creative commons cc0"}, {0xf6c9, true, "critical role|Dungeons & Dragons|d&d|dnd|fantasy|game|gaming|tabletop"}, {0xf13c, true, "css 3 logo|code"}, {0xf38b, true, "alternate css3 logo"}, {0xf38c, true, "cuttlefish"}, {0xf38d, true, "dungeons & dragons"}, {0xf6ca, true, "d&d beyond|Dungeons & Dragons|d&d|dnd|fantasy|gaming|tabletop"}, {0xe052, true, "dailymotion"}, {0xe693, true, "dart lang"}, {0xf210, true, "dashcube"}, {0xe60b, true, "debian"}, {0xe077, true, "deezer"}, {0xf1a5, true, "delicious"}, {0xf38e, true, "deploy.dog"}, {0xf38f, true, "deskpro"}, {0xf6cc, true, "dev"}, {0xf1bd, true, "deviantart"}, {0xf790, true, "dhl|Dalsey|Hillblom and Lynn|german|package|shipping"}, {0xf791, true, "diaspora"}, {0xf1a6, true, "digg logo"}, {0xf391, true, "digital ocean"}, {0xf392, true, "discord"}, {0xf393, true, "discourse"}, {0xf394, true, "dochub"}, {0xf395, true, "docker"}, {0xf396, true, "draft2digital"}, {0xf17d, true, "dribbble"}, {0xf16b, true, "dropbox"}, {0xf1a9, true, "drupal logo"}, {0xf399, true, "dyalog"}, {0xf39a, true, "earlybirds"}, {0xf4f4, true, "ebay"}, {0xf282, true, "edge browser|browser|ie"}, {0xe078, true, "edge legacy browser"}, {0xf430, true, "elementor"}, {0xf5f1, true, "ello"}, {0xf423, true, "ember"}, {0xf1d1, true, "galactic empire"}, {0xf299, true, "envira gallery|leaf"}, {0xf39d, true, "erlang"}, {0xf42e, true, "ethereum"}, {0xf2d7, true, "etsy"}, {0xf839, true, "evernote"}, {0xf23e, true, "expeditedssl"}, {0xf09a, true, "facebook|fabook|facebook-official|fb|social network"}, {0xf39e, true, "facebook f|fabook|facebook|fb"}, {0xf39f, true, "facebook messenger|fabook|fb"}, {0xf6dc, true, "fantasy flight-games|Dungeons & Dragons|d&d|dnd|fantasy|game|gaming|tabletop"}, {0xf797, true, "fedex|Federal Express|package|shipping"}, {0xf798, true, "fedora|linux|operating system|os"}, {0xf799, true, "figma|app|design|interface"}, {0xf269, true, "firefox|browser"}, {0xe007, true, "firefox browser|browser"}, {0xf2b0, true, "first order"}, {0xf50a, true, "alternate first order"}, {0xf3a1, true, "firstdraft"}, {0xf16e, true, "flickr"}, {0xf44d, true, "flipboard"}, {0xe694, true, "flutter"}, {0xf417, true, "fly"}, {0xf2b4, true, "font awesome|awesome|flag|font|icons|typeface"}, {0xf280, true, "fonticons"}, {0xf3a2, true, "fonticons fi"}, {0xf286, true, "fort awesome|castle"}, {0xf3a3, true, "alternate fort awesome|castle"}, {0xf211, true, "forumbee"}, {0xf180, true, "foursquare"}, {0xf2c5, true, "freecodecamp"}, {0xf3a4, true, "freebsd"}, {0xf50b, true, "fulcrum"}, {0xf50c, true, "galactic republic|politics|star wars"}, {0xf50d, true, "galactic senate|star wars"}, {0xf265, true, "get pocket"}, {0xf260, true, "gg currency"}, {0xf261, true, "gg currency circle"}, {0xf1d3, true, "git"}, {0xf841, true, "git alt"}, {0xf09b, true, "github|octocat"}, {0xf113, true, "alternate github|octocat"}, {0xf3a6, true, "gitkraken"}, {0xf296, true, "gitlab|Axosoft"}, {0xf426, true, "gitter"}, {0xf2a5, true, "glide"}, {0xf2a6, true, "glide g"}, {0xf3a7, true, "gofore"}, {0xe40f, true, "go"}, {0xf3a8, true, "goodreads"}, {0xf3a9, true, "goodreads g"}, {0xf1a0, true, "google logo"}, {0xf3aa, true, "google drive"}, {0xe079, true, "google pay"}, {0xf3ab, true, "google play|playstore"}, {0xf2b3, true, "google plus|google-plus-circle|google-plus-official"}, {0xf0d5, true, "google plus g|google-plus|social network"}, {0xe63b, true, "google scholar"}, {0xf1ee, true, "google wallet"}, {0xf184, true, "gratipay (gittip)|favorite|heart|like|love"}, {0xf2d6, true, "grav"}, {0xf3ac, true, "gripfire, inc."}, {0xf3ad, true, "grunt"}, {0xe07e, true, "guilded"}, {0xf3ae, true, "gulp"}, {0xf1d4, true, "hacker news"}, {0xf5f7, true, "hackerrank"}, {0xe499, true, "hashnode"}, {0xf452, true, "hips"}, {0xf3b0, true, "hireahelper"}, {0xe07f, true, "hive blockchain network"}, {0xf427, true, "hooli"}, {0xf592, true, "hornbill"}, {0xf3b1, true, "hotjar"}, {0xf27c, true, "houzz"}, {0xf13b, true, "html 5 logo"}, {0xf3b2, true, "hubspot"}, {0xe013, true, "ideal"}, {0xf2d8, true, "imdb"}, {0xf16d, true, "instagram"}, {0xe081, true, "instalod"}, {0xf7af, true, "intercom|app|customer|messenger"}, {0xf26b, true, "internet-explorer|browser|ie"}, {0xf7b0, true, "invision|app|design|interface"}, {0xf208, true, "ioxhost"}, {0xf83a, true, "itch.io"}, {0xf3b4, true, "itunes"}, {0xf3b5, true, "itunes note"}, {0xf4e4, true, "java"}, {0xf50e, true, "jedi order|star wars"}, {0xf3b6, true, "jenkis"}, {0xf7b1, true, "jira|atlassian"}, {0xf3b7, true, "joget"}, {0xf1aa, true, "joomla logo"}, {0xf3b8, true, "javascript (js)"}, {0xf1cc, true, "jsfiddle"}, {0xe67b, true, "jxl"}, {0xf5fa, true, "kaggle"}, {0xf4f5, true, "keybase"}, {0xf3ba, true, "keycdn"}, {0xf3bb, true, "kickstarter"}, {0xf3bc, true, "kickstarter k"}, {0xf42f, true, "korvue"}, {0xf3bd, true, "laravel"}, {0xf202, true, "last.fm"}, {0xf212, true, "leanpub"}, {0xf41d, true, "less"}, {0xe62d, true, "letterboxd"}, {0xf3c0, true, "line"}, {0xf08c, true, "linkedin|linkedin-square|linkin"}, {0xf0e1, true, "linkedin in|linkedin|linkin"}, {0xf2b8, true, "linode"}, {0xf17c, true, "linux|tux"}, {0xf3c3, true, "lyft"}, {0xf3c4, true, "magento"}, {0xf59e, true, "mailchimp"}, {0xf50f, true, "mandalorian"}, {0xf60f, true, "markdown"}, {0xf4f6, true, "mastodon"}, {0xf136, true, "maxcdn"}, {0xf8ca, true, "material design for bootstrap"}, {0xf3c6, true, "medapps"}, {0xf23a, true, "medium"}, {0xf3c8, true, "mrt"}, {0xf2e0, true, "meetup"}, {0xf5a3, true, "megaport"}, {0xf7b3, true, "mendeley"}, {0xe49b, true, "meta"}, {0xe01a, true, "micro.blog"}, {0xf3ca, true, "microsoft"}, {0xe62f, true, "mintbit"}, {0xf3cb, true, "mix"}, {0xf289, true, "mixcloud"}, {0xe056, true, "mixer"}, {0xf3cc, true, "mizuni"}, {0xf285, true, "modx"}, {0xf3d0, true, "monero"}, {0xf3d2, true, "napster"}, {0xf612, true, "neos"}, {0xe530, true, "nfc directional|connect|data|near field communication|nfc|scan|signal|transfer|wireless"}, {0xe531, true, "nfc symbol|connect|data|near field communication|nfc|scan|signal|transfer|wireless"}, {0xf5a8, true, "nimblr"}, {0xf419, true, "node.js"}, {0xf3d3, true, "node.js js"}, {0xf3d4, true, "npm"}, {0xf3d5, true, "ns8"}, {0xf3d6, true, "nutritionix"}, {0xe082, true, "octopus deploy"}, {0xf263, true, "odnoklassniki"}, {0xe5c6, true, "odysee"}, {0xf510, true, "old republic|politics|star wars"}, {0xf23d, true, "opencart"}, {0xf19b, true, "openid"}, {0xe62b, true, "opensuse"}, {0xf26a, true, "opera"}, {0xf23c, true, "optin monster"}, {0xf8d2, true, "orcid"}, {0xf41a, true, "open source initiative"}, {0xe4a0, true, "padlet"}, {0xf3d7, true, "page4 corporation"}, {0xf18c, true, "pagelines|eco|flora|leaf|leaves|nature|plant|tree"}, {0xf3d8, true, "palfed"}, {0xf3d9, true, "patreon"}, {0xf1ed, true, "paypal"}, {0xe083, true, "perbyte"}, {0xf3da, true, "periscope"}, {0xf3db, true, "phabricator"}, {0xf3dc, true, "phoenix framework"}, {0xf511, true, "phoenix squadron"}, {0xf457, true, "php"}, {0xf2ae, true, "pied piper logo"}, {0xf1a8, true, "alternate pied piper logo (old)"}, {0xf4e5, true, "pied piper hat (old)|clothing"}, {0xf1a7, true, "pied piper pp logo (old)"}, {0xf0d2, true, "pinterest"}, {0xf231, true, "pinterest p"}, {0xe43a, true, "pix"}, {0xe640, true, "pixiv"}, {0xf3df, true, "playstation"}, {0xf288, true, "product hunt"}, {0xf3e1, true, "pushed"}, {0xf3e2, true, "python"}, {0xf1d6, true, "qq"}, {0xf459, true, "quinscape"}, {0xf2c4, true, "quora"}, {0xf4f7, true, "r project"}, {0xf7bb, true, "raspberry pi"}, {0xf2d9, true, "ravelry"}, {0xf41b, true, "react"}, {0xf75d, true, "reacteurope"}, {0xf4d5, true, "readme"}, {0xf1d0, true, "rebel alliance"}, {0xf3e3, true, "red river"}, {0xf1a1, true, "reddit"}, {0xf281, true, "reddit alien"}, {0xf7bc, true, "redhat|linux|operating system|os"}, {0xf18b, true, "renren"}, {0xf3e6, true, "replyd"}, {0xf4f8, true, "researchgate"}, {0xf3e7, true, "resolving"}, {0xf5b2, true, "rev.io"}, {0xf3e8, true, "rocket.chat"}, {0xf3e9, true, "rockrms"}, {0xe07a, true, "rust"}, {0xf267, true, "safari|browser"}, {0xf83b, true, "salesforce"}, {0xf41e, true, "sass"}, {0xf3ea, true, "schlix"}, {0xe570, true, "screenpal"}, {0xf28a, true, "scribd"}, {0xf3eb, true, "searchengin"}, {0xf2da, true, "sellcast|eercast"}, {0xf213, true, "sellsy"}, {0xf3ec, true, "servicestack"}, {0xf214, true, "shirts in bulk"}, {0xe60c, true, "shoelace"}, {0xe057, true, "shopify"}, {0xf5b5, true, "shopware"}, {0xe663, true, "signal messenger"}, {0xf215, true, "simplybuilt"}, {0xf3ee, true, "sistrix"}, {0xf512, true, "sith"}, {0xe44a, true, "sitrox"}, {0xf7c6, true, "sketch|app|design|interface"}, {0xf216, true, "skyatlas"}, {0xf17e, true, "skype"}, {0xf198, true, "slack logo|anchor|hash|hashtag"}, {0xf1e7, true, "slideshare"}, {0xf2ab, true, "snapchat"}, {0xf1be, true, "soundcloud"}, {0xf7d3, true, "sourcetree"}, {0xe5ac, true, "space awesome|adventure|rocket|ship|shuttle"}, {0xf3f3, true, "speakap"}, {0xf83c, true, "speaker deck"}, {0xf1bc, true, "spotify"}, {0xf1b5, true, "square behance"}, {0xf397, true, "square dribbble"}, {0xf082, true, "square facebook|fabook|fb|social network"}, {0xe5ad, true, "square font awesome"}, {0xf35c, true, "square font awesome stroke| flag| font| icons| typeface|awesome"}, {0xf1d2, true, "square git"}, {0xf092, true, "square github|octocat"}, {0xe5ae, true, "square gitlab"}, {0xf0d4, true, "square google plus|social network"}, {0xf3af, true, "square hacker news"}, {0xe055, true, "square instagram"}, {0xf3b9, true, "square js"}, {0xf203, true, "square lastfm"}, {0xe62e, true, "square letterboxd"}, {0xf264, true, "square odnoklassniki"}, {0xe01e, true, "pied piper square logo (old)"}, {0xf0d3, true, "square pinterest"}, {0xf1a2, true, "square reddit"}, {0xf2ad, true, "snapchat square"}, {0xf1b7, true, "square steam"}, {0xe619, true, "square threads|social network"}, {0xf174, true, "square tumblr"}, {0xf081, true, "square twitter|social network|tweet"}, {0xe67c, true, "square upwork"}, {0xf2aa, true, "square viadeo"}, {0xf194, true, "square vimeo"}, {0xe683, true, "square web awesome| coding| crown| web| awesome| components"}, {0xe684, true, "square web awesome stroke| coding| crown| web| awesome| components"}, {0xf40c, true, "square whatsapp"}, {0xe61a, true, "square x twitter| elon| x|twitter"}, {0xf169, true, "square xing"}, {0xf431, true, "square youtube"}, {0xf5be, true, "squarespace"}, {0xf18d, true, "stack exchange"}, {0xf16c, true, "stack overflow"}, {0xf842, true, "stackpath"}, {0xf3f5, true, "staylinked|linkin"}, {0xf1b6, true, "steam"}, {0xf3f6, true, "steam symbol"}, {0xf3f7, true, "sticker mule"}, {0xf428, true, "strava"}, {0xf429, true, "stripe"}, {0xf42a, true, "stripe s"}, {0xe5c7, true, "stubber"}, {0xf3f8, true, "studio vinari"}, {0xf1a4, true, "stumbleupon logo"}, {0xf1a3, true, "stumbleupon circle"}, {0xf2dd, true, "superpowers"}, {0xf3f9, true, "supple"}, {0xf7d6, true, "suse|linux|operating system|os"}, {0xf8e1, true, "swift"}, {0xf83d, true, "symfony"}, {0xf4f9, true, "teamspeak"}, {0xf2c6, true, "telegram"}, {0xf1d5, true, "tencent weibo"}, {0xf69d, true, "the red yeti"}, {0xf5c6, true, "themeco"}, {0xf2b2, true, "themeisle"}, {0xf731, true, "think peaks"}, {0xe618, true, "threads|social network"}, {0xe07b, true, "tiktok"}, {0xf513, true, "trade federation"}, {0xf181, true, "trello|atlassian"}, {0xf173, true, "tumblr"}, {0xf1e8, true, "twitch"}, {0xf099, true, "twitter|social network|tweet"}, {0xf42b, true, "typo3"}, {0xf402, true, "uber"}, {0xf7df, true, "ubuntu|linux|operating system|os"}, {0xf403, true, "uikit"}, {0xf8e8, true, "umbraco"}, {0xe084, true, "uncharted software"}, {0xf404, true, "uniregistry"}, {0xe049, true, "unity 3d"}, {0xe07c, true, "unsplash"}, {0xf405, true, "untappd"}, {0xf7e0, true, "ups|United Parcel Service|package|shipping"}, {0xe641, true, "upwork"}, {0xf287, true, "usb"}, {0xf7e1, true, "united states postal service|american|package|shipping|usa"}, {0xf407, true, "us-sunnah foundation"}, {0xf408, true, "vaadin"}, {0xf237, true, "viacoin"}, {0xf2a9, true, "viadeo"}, {0xf409, true, "viber"}, {0xf40a, true, "vimeo"}, {0xf27d, true, "vimeo|vimeo"}, {0xf1ca, true, "vine"}, {0xf189, true, "vk"}, {0xf40b, true, "vnv"}, {0xf41f, true, "vue.js"}, {0xe087, true, "watchman monitoring"}, {0xf83f, true, "waze"}, {0xe682, true, "web awesome| coding| components| crown| web|awesome"}, {0xe65c, true, "webflow"}, {0xf5cc, true, "weebly"}, {0xf18a, true, "weibo"}, {0xf1d7, true, "weixin (wechat)"}, {0xf232, true, "what's app"}, {0xf40d, true, "whmcs"}, {0xf266, true, "wikipedia w"}, {0xf17a, true, "windows|microsoft|operating system|os"}, {0xe2d0, true, "wirsindhandwerk"}, {0xf5cf, true, "wix"}, {0xf730, true, "wizards of the coast|Dungeons & Dragons|d&d|dnd|fantasy|game|gaming|tabletop"}, {0xe088, true, "wodu"}, {0xf514, true, "wolf pack battalion"}, {0xf19a, true, "wordpress logo"}, {0xf411, true, "wordpress simple"}, {0xf297, true, "wpbeginner"}, {0xf2de, true, "wpexplorer"}, {0xf298, true, "wpforms"}, {0xf3e4, true, "wpressr|rendact"}, {0xe61b, true, "x twitter| elon| twitter| x"}, {0xf412, true, "xbox"}, {0xf168, true, "xing"}, {0xf23b, true, "y combinator"}, {0xf19e, true, "yahoo logo"}, {0xf840, true, "yammer"}, {0xf413, true, "yandex"}, {0xf414, true, "yandex international"}, {0xf7e3, true, "yarn"}, {0xf1e9, true, "yelp"}, {0xf2b1, true, "yoast"}, {0xf167, true, "youtube|film|video|youtube-play|youtube-square"}, {0xf63f, true, "zhihu"} };
135,044
C++
.h
1,895
70.246966
306
0.776602
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,416
mainwindow.h
hluk_CopyQ/src/gui/mainwindow.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef MAINWINDOW_H #define MAINWINDOW_H #include "common/clipboardmode.h" #include "common/command.h" #include "common/navigationstyle.h" #include "gui/clipboardbrowsershared.h" #include "gui/menuitems.h" #include "item/persistentdisplayitem.h" #include "platform/platformnativeinterface.h" #include <QMainWindow> #include <QPersistentModelIndex> #include <QPointer> #include <QTimer> #include <QtContainerFwd> class Action; class ActionDialog; class AppConfig; class ClipboardBrowser; class ClipboardBrowserPlaceholder; class CommandAction; class CommandDialog; class ConfigurationManager; class Notification; class QAction; class QMimeData; class SystemTrayIcon; class Tabs; class Theme; class TrayMenu; class ToolBar; class QModelIndex; struct NotificationButton; Q_DECLARE_METATYPE(QPersistentModelIndex) #if QT_VERSION >= QT_VERSION_CHECK(6,0,0) using NativeEventResult = qintptr; #else Q_DECLARE_METATYPE(QList<QPersistentModelIndex>) using NativeEventResult = long; #endif namespace Ui { class MainWindow; } enum ItemActivationCommand { ActivateNoCommand = 0x0, ActivateCloses = 0x1, ActivateFocuses = 0x2, ActivatePastes = 0x4 }; enum class ImportOptions { /// Select what to import/export in dialog. Select, /// Import/export everything without asking. All }; struct MainWindowOptions { bool activateCloses() const { return itemActivationCommands & ActivateCloses; } bool activateFocuses() const { return itemActivationCommands & ActivateFocuses; } bool activatePastes() const { return itemActivationCommands & ActivatePastes; } bool confirmExit = true; NavigationStyle navigationStyle = NavigationStyle::Default; bool trayCommands = false; bool trayCurrentTab = false; QString trayTabName; int trayItems = 5; bool nativeTrayMenu = false; bool trayImages = true; bool trayMenuOpenOnLeftClick = false; int transparency = 0; int transparencyFocused = 0; bool hideTabs = false; bool hideMainWindow = false; bool closeOnUnfocus = false; int itemActivationCommands = ActivateCloses; bool clearFirstTab = false; bool trayItemPaste = true; QString clipboardTab; }; /** * Application's main window. * * Contains search bar and tab widget. * Each tab contains one clipboard browser widget. * * It operates in two modes: * * browse mode with search bar hidden and empty (default) and * * search mode with search bar shown and not empty. * * If user starts typing text the search mode will become active and * the search bar focused. * If the text is deleted or escape pressed the browse mode will become active. */ class MainWindow final : public QMainWindow { Q_OBJECT public: explicit MainWindow( const ClipboardBrowserSharedPtr &sharedData, QWidget *parent = nullptr); ~MainWindow(); /** Return true if in browse mode (i.e. search field is hidden). */ bool browseMode() const; /** * Try to close command dialog and return true on success. * * Note that dialog won't be closed if it has unsaved changes * and user cancels the closing. */ bool maybeCloseCommandDialog(); /** * Return browser widget in given tab @a index. * Load items if not loaded yet. */ ClipboardBrowser *browser(int index); /** * Return browser widget in current tab. * Load items if not loaded yet. */ ClipboardBrowser *browser(); /** * Return browser widget in current tab or nullptr if not loaded. */ ClipboardBrowser *browserOrNull(); /** Return browser containing item or nullptr. */ ClipboardBrowser *browserForItem(const QModelIndex &index); /** * Find tab with given @a name. * @return found tab index or -1 */ int findTabIndex(const QString &name); /** * Tries to find tab with exact or similar name (ignores * key hints '&') or creates new one. * @return Existing or new tab with given @a name. */ ClipboardBrowser *tab( const QString &name //!< Name of the new tab. ); /** * Show/hide tray menu. Return true only if menu is shown. */ bool toggleMenu(); bool toggleMenu(const QString &tabName, int itemCount, QPoint position); /** Switch between browse and search mode. */ void enterBrowseMode(); void enterSearchMode(); void enterSearchMode(const QString &txt); /** Show and focus main window. */ void showWindow(); /** Hide window to tray or minimize if tray is not available. */ void hideWindow(); /** Minimize window (hide if option is set). */ void minimizeWindow(); /** Set current tab. */ bool setCurrentTab(int index); bool focusPrevious(); /** Open tab group renaming dialog. */ void openRenameTabGroupDialog(const QString &name); /** Remove all tab in group. */ void removeTabGroup(const QString &name); /** Remove tab. */ void removeTab( bool ask, //!< Ask before removing. int tabIndex //!< Tab index or current tab. ); /** Set icon for tab or tab group. */ void setTabIcon(const QString &tabName); void setTabIcon(const QString &tabName, const QString &icon); bool unloadTab(const QString &tabName); void forceUnloadTab(const QString &tabName); /** * Save all items in tab to file. * @return True only if all items were successfully saved. */ bool saveTab( const QString &fileName, int tabIndex = -1 //!< Tab index or current tab. ); /** Save all unsaved tabs. */ Q_SLOT void saveTabs(); /** * Load saved items to new tab. * @return True only if all items were successfully loaded. */ bool loadTab(const QString &fileName); /** * Import tabs, settings etc. * @return True only if all data were successfully loaded. */ bool importDataFrom(const QString &fileName, ImportOptions options); /** * Export tabs, settings etc. * @return True only if all data were successfully saved. */ bool exportAllData(const QString &fileName); /** Temporarily disable monitoring (i.e. adding new clipboard content to the first tab). */ void disableClipboardStoring(bool disable); /** Return true only if monitoring is enabled. */ bool isMonitoringEnabled() const; QStringList tabs() const; /// Used by config() command. QVariant config(const QVariantList &nameValue); QString configDescription(); QVariantMap actionData(int id) const; void setActionData(int id, const QVariantMap &data); void setCommands(const QVector<Command> &commands); void setSessionIconColor(QColor color); void setSessionIconTag(const QString &tag); void setSessionIconTagColor(QColor color); QColor sessionIconColor() const; QString sessionIconTag() const; QColor sessionIconTagColor() const; void setTrayTooltip(const QString &tooltip); bool setMenuItemEnabled(int actionId, int currentRun, int menuItemMatchCommandIndex, const QVariantMap &menuItem); QVariantMap setDisplayData(int actionId, const QVariantMap &data); QVector<Command> automaticCommands() const { return m_automaticCommands; } QVector<Command> displayCommands() const { return m_displayCommands; } QVector<Command> scriptCommands() const { return m_scriptCommands; } /** Close main window and exit the application. */ void exit(); /** Load settings. */ void loadSettings(QSettings &settings, AppConfig *appConfig); void loadTheme(const QSettings &themeSettings); /** Open help. */ void openHelp(); /** Open log dialog. */ void openLogDialog(); /** Open about dialog. */ void openAboutDialog(); /** Open dialog with clipboard content. */ void showClipboardContent(); /** Open dialog with active commands. */ void showProcessManagerDialog(); /** Open action dialog with given input data. */ ActionDialog *openActionDialog(const QVariantMap &data); /** Open action dialog with input data from selected items. */ void openActionDialog(); void showItemContent(); /** Open preferences dialog. */ void openPreferences(); /** Open commands dialog. */ void openCommands(); /** Sort selected items. */ void sortSelectedItems(); /** Reverse order of selected items. */ void reverseSelectedItems(); /** * Import tabs, settings etc. (select file in dialog). * @return True only if all data were successfully loaded. */ bool importData(); /** Create new item in current tab. */ void editNewItem(); /** Paste items to current tab. */ void pasteItems(); /** Copy selected items in current tab. */ void copyItems(); /** Activate current item. */ void activateCurrentItem(); /** Show window and given tab and give focus to the tab. */ void showBrowser(const ClipboardBrowser *browser); /** Show error popup message. */ void showError(const QString &msg); Notification *createNotification(const QString &id = QString()); /** Open command dialog and add commands. */ void addCommands(const QVector<Command> &commands); /** Execute command on given input data. */ Action *action( const QVariantMap &data, const Command &cmd, const QModelIndex &outputIndex); bool triggerMenuCommand(const Command &command, const QString &triggeredShortcut); void runInternalAction(Action *action); bool isInternalActionId(int id) const; void setClipboard(const QVariantMap &data); void setClipboard(const QVariantMap &data, ClipboardMode mode); void setClipboardAndSelection(const QVariantMap &data); void moveToClipboard(ClipboardBrowser *c, int row); const QMimeData *getClipboardData(ClipboardMode mode); /** Show/hide main window. Return true only if window is shown. */ bool toggleVisible(); /** Set icon for current tab or tab group. */ void setTabIcon(); /** Open tab creation dialog. */ void openNewTabDialog(const QString &name); void openNewTabDialog(); /** Remove tab. */ void removeTab(); /** Rename current tab to given name (if possible). */ void renameTabGroup(const QString &newName, const QString &oldName); /** Open tab renaming dialog (for given tab index or current tab). */ void openRenameTabDialog(int tabIndex); void openRenameTabDialog(); /** Rename current tab to given name (if possible). */ void renameTab(const QString &name, int tabIndex); void addAndFocusTab(const QString &name); /** Toggle monitoring (i.e. adding new clipboard content to the first tab). */ void toggleClipboardStoring(); /** * Export tabs, settings etc. (select in file dialog). * @return True only if all data were successfully saved. */ bool exportData(); /** Set next or first tab as current. */ void nextTab(); /** Set previous or last tab as current. */ void previousTab(); void setClipboardData(const QVariantMap &data); /** Set text for filtering items. */ void setFilter(const QString &text); QString filter() const; void updateShortcuts(); void setItemPreviewVisible(bool visible); bool isItemPreviewVisible() const; void setScriptOverrides(const QVector<int> &overrides, int actionId); bool isScriptOverridden(int id) const; signals: /** Request clipboard change. */ void changeClipboard(const QVariantMap &data, ClipboardMode mode); void tabGroupSelected(bool selected); void requestExit(); void commandsSaved(const QVector<Command> &commands); void configurationChanged(AppConfig *appConfig); void disableClipboardStoringRequest(bool disable); void sendActionData(int actionId, const QByteArray &bytes); protected: void keyPressEvent(QKeyEvent *event) override; void keyReleaseEvent(QKeyEvent *event) override; bool event(QEvent *event) override; /** Hide (minimize to tray) window on close. */ void closeEvent(QCloseEvent *event) override; bool focusNextPrevChild(bool next) override; bool nativeEvent( const QByteArray &eventType, void *message, NativeEventResult *result) override; private: ClipboardBrowserPlaceholder *getPlaceholderForMenu(); ClipboardBrowserPlaceholder *getPlaceholderForTrayMenu(); void filterMenuItems(const QString &searchText); void filterTrayMenuItems(const QString &searchText); void trayActivated(int reason); void onMenuActionTriggered(const QVariantMap &data, bool omitPaste); void onTrayActionTriggered(const QVariantMap &data, bool omitPaste); void findNextOrPrevious(); void tabChanged(int current, int previous); void saveTabPositions(); void onSaveTabPositionsTimer(); void doSaveTabPositions(AppConfig *appConfig); void tabsMoved(const QString &oldPrefix, const QString &newPrefix); void tabBarMenuRequested(QPoint pos, int tab); void tabTreeMenuRequested(QPoint pos, const QString &groupPath); void tabCloseRequested(int tab); void onFilterChanged(); void raiseLastWindowAfterMenuClosed(); /** Update WId for paste and last focused window if needed. */ void updateFocusWindows(); /** Update tray and window icon depending on current state. */ void updateIcon(); void updateContextMenuTimeout(); void updateTrayMenuItemsTimeout(); void initTrayMenuItems(); void updateItemPreviewAfterMs(int ms); void updateItemPreviewTimeout(); void toggleItemPreviewVisible(); void onAboutToQuit(); void onItemCommandActionTriggered(CommandAction *commandAction, const QString &triggeredShortcut); void onClipboardCommandActionTriggered(CommandAction *commandAction, const QString &triggeredShortcut); void onTabWidgetDropItems(const QString &tabName, const QMimeData *data); void showContextMenuAt(QPoint position); void showContextMenu(); void moveUp(); void moveDown(); void moveToTop(); void moveToBottom(); void onBrowserCreated(ClipboardBrowser *browser); void onBrowserLoaded(ClipboardBrowser *browser); void onBrowserDestroyed(ClipboardBrowserPlaceholder *placeholder); void onItemSelectionChanged(const ClipboardBrowser *browser); void onItemsChanged(const ClipboardBrowser *browser); void onInternalEditorStateChanged(const ClipboardBrowser *self); void onItemWidgetCreated(const PersistentDisplayItem &item); void onActionDialogAccepted(const Command &command, const QStringList &arguments, const QVariantMap &data); void onSearchShowRequest(const QString &text); void updateEnabledCommands(); void updateCommands(QVector<Command> allCommands, bool forceSave); bool syncInternalCommands(QVector<Command> *allCommands); void disableHideWindowOnUnfocus(); void enableHideWindowOnUnfocus(); void hideWindowIfNotActive(); template <typename SlotReturnType> using MainWindowActionSlot = SlotReturnType (MainWindow::*)(); enum TabNameMatching { MatchExactTabName, MatchSimilarTabName }; struct MenuMatchCommands { int currentRun = 0; int actionId = -1; QStringList matchCommands; QVector< QPointer<QAction> > actions; QMenu *menu = nullptr; }; void runDisplayCommands(); void clearHiddenDisplayData(); void reloadBrowsers(); ClipboardBrowserPlaceholder *createTab(const QString &name, TabNameMatching nameMatch, const Tabs &tabs); int findTabIndexExactMatch(const QString &name); /** Create menu bar and tray menu with items. Called once. */ void createMenu(); /** Create context menu for @a tab. It will be automatically deleted after closed. */ void popupTabBarMenu(QPoint pos, const QString &tab); void updateContextMenu(int intervalMsec); void updateTrayMenuItems(); void updateTrayMenuCommands(); void updateWindowTransparency(bool mouseOver = false); /** Return browser widget in given tab @a index. */ ClipboardBrowserPlaceholder *getPlaceholder(int index) const; ClipboardBrowserPlaceholder *getPlaceholder(const QString &tabName) const; /** Return browser widget in current tab. */ ClipboardBrowserPlaceholder *getPlaceholder() const; /** Call updateFocusWindows() after a small delay if main window or menu is not active. */ void delayedUpdateForeignFocusWindows(); /** Show/hide tab bar. **/ void setHideTabs(bool hide); /** * Return true if window should be minimized instead of closed/hidden. * * If tray icon is not available, window should be minimized so that it can be opened with * mouse. */ bool closeMinimizes() const; template <typename SlotReturnType> QAction *createAction(Actions::Id id, MainWindowActionSlot<SlotReturnType> slot, QMenu *menu, QWidget *parent = nullptr); QAction *addTrayAction(Actions::Id id); void updateTabIcon(const QString &newName, const QString &oldName); template <typename Receiver, typename ReturnType> QAction *addItemAction(Actions::Id id, Receiver *receiver, ReturnType (Receiver::* slot)()); QVector<Command> commandsForMenu(const QVariantMap &data, const QString &tabName, const QVector<Command> &allCommands); void addCommandsToItemMenu(ClipboardBrowser *c); void addCommandsToTrayMenu(const QVariantMap &clipboardData, QList<QAction*> *actions); void addMenuMatchCommand(MenuMatchCommands *menuMatchCommands, const QString &matchCommand, QAction *act); void runMenuCommandFilters(MenuMatchCommands *menuMatchCommands, QVariantMap &data); void interruptMenuCommandFilters(MenuMatchCommands *menuMatchCommands); void stopMenuCommandFilters(MenuMatchCommands *menuMatchCommands); void terminateAction(int *actionId); bool isItemMenuDefaultActionValid() const; void updateToolBar(); void setTrayEnabled(bool enable = true); void runDisplayCommand(const Command &command); bool isWindowVisible() const; void onEscape(); void updateActionShortcuts(); QAction *actionForMenuItem(Actions::Id id, QWidget *parent, Qt::ShortcutContext context); void addMenuItems(TrayMenu *menu, ClipboardBrowserPlaceholder *placeholder, int maxItemCount, const QString &searchText); void activateMenuItem(ClipboardBrowserPlaceholder *placeholder, const QVariantMap &data, bool omitPaste); bool toggleMenu(TrayMenu *menu, QPoint pos); bool toggleMenu(TrayMenu *menu); bool exportDataFrom(const QString &fileName, const QStringList &tabs, bool exportConfiguration, bool exportCommands); bool exportDataV4(QDataStream *out, const QStringList &tabs, bool exportConfiguration, bool exportCommands); bool importDataV3(QDataStream *in, ImportOptions options); bool importDataV4(QDataStream *in, ImportOptions options); const Theme &theme() const; Action *runScript(const QString &script, const QVariantMap &data = QVariantMap()); bool runEventHandlerScript(const QString &script, const QVariantMap &data); void runItemHandlerScript( const QString &script, const ClipboardBrowser *browser, int firstRow, int lastRow); void activateCurrentItemHelper(); void onItemClicked(); void onItemDoubleClicked(); ConfigurationManager *cm; Ui::MainWindow *ui; QMenu *m_menuItem; TrayMenu *m_trayMenu; SystemTrayIcon *m_tray; ToolBar *m_toolBar; MainWindowOptions m_options; bool m_clipboardStoringDisabled = false; ClipboardBrowserSharedPtr m_sharedData; QVector<Command> m_automaticCommands; QVector<Command> m_displayCommands; QVector<Command> m_menuCommands; QVector<Command> m_trayMenuCommands; QVector<Command> m_scriptCommands; PlatformWindowPtr m_windowForMenuPaste; PlatformWindowPtr m_windowForMainPaste; QTimer m_timerUpdateFocusWindows; QTimer m_timerUpdateContextMenu; QTimer m_timerUpdatePreview; QTimer m_timerSaveTabPositions; QTimer m_timerHideWindowIfNotActive; QTimer m_timerRaiseLastWindowAfterMenuClosed; bool m_trayMenuDirty = true; QVariantMap m_clipboardData; TrayMenu *m_menu; QString m_menuTabName; int m_menuMaxItemCount; QPointer<CommandDialog> m_commandDialog; bool m_wasMaximized = false; bool m_showItemPreview = false; bool m_activatingItem = false; QVector< QPointer<QAction> > m_actions; QList<PersistentDisplayItem> m_displayItemList; PersistentDisplayItem m_currentDisplayItem; int m_displayActionId = -1; MenuMatchCommands m_trayMenuMatchCommands; MenuMatchCommands m_itemMenuMatchCommands; PlatformClipboardPtr m_clipboard; bool m_isActiveWindow = false; bool m_singleClickActivate = 0; bool m_enteringSearchMode = false; QVector<int> m_overrides; int m_maxEventHandlerScripts = 10; QPointer<Action> m_actionCollectOverrides; }; #endif // MAINWINDOW_H
21,223
C++
.h
514
36.101167
125
0.731647
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,417
actionhandler.h
hluk_CopyQ/src/gui/actionhandler.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef ACTIONHANDLER_H #define ACTIONHANDLER_H #include <QObject> #include <QSet> class Action; class NotificationDaemon; class ActionTableModel; class ActionHandler final : public QObject { Q_OBJECT public: explicit ActionHandler(NotificationDaemon *notificationDaemon, QObject *parent); void setMaxRowCount(uint rows); int runningActionCount() const { return m_actions.size() - m_internalActions.size(); } void showProcessManagerDialog(QWidget *parent); void addFinishedAction(const QString &name); QVariantMap actionData(int id) const; void setActionData(int id, const QVariantMap &data); void internalAction(Action *action); bool isInternalActionId(int id) const; /** Execute action. */ void action(Action *action); void terminateAction(int id); private: /** Delete finished action and its menu item. */ void closeAction(Action *action); void showActionErrors(Action *action, const QString &message, ushort icon); NotificationDaemon *m_notificationDaemon; ActionTableModel *m_actionModel; QHash<int, Action*> m_actions; QSet<int> m_internalActions; int m_lastActionId = -1; }; #endif // ACTIONHANDLER_H
1,253
C++
.h
35
31.942857
90
0.75624
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,418
selectiondata.h
hluk_CopyQ/src/gui/selectiondata.h
// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include <QModelIndexList> #include <QVariantMap> #include <QtContainerFwd> class ClipboardBrowser; void addSelectionData( QVariantMap *result, const QList<QPersistentModelIndex> &selectedIndexes); void addSelectionData( QVariantMap *result, const QModelIndexList &selectedIndexes); /// Adds information about current tab and selection if command is triggered by user. QVariantMap selectionData( const ClipboardBrowser &c, const QModelIndex &currentIndex, const QModelIndexList &selectedIndexes); QVariantMap selectionData(const ClipboardBrowser &c);
671
C++
.h
18
32.833333
85
0.777434
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,419
configtabappearance.h
hluk_CopyQ/src/gui/configtabappearance.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef CONFIGTABAPPEARANCE_H #define CONFIGTABAPPEARANCE_H #include "gui/theme.h" #include <QWidget> #include <QTimer> namespace Ui { class ConfigTabAppearance; } class ItemDelegate; class ItemFactory; class Option; class QAbstractScrollArea; class QSettings; class ConfigTabAppearance final : public QWidget { Q_OBJECT public: explicit ConfigTabAppearance(QWidget *parent = nullptr); ~ConfigTabAppearance(); /** Load theme from settings file. */ void loadTheme(const QSettings &settings); /** Save theme to settings file. */ void saveTheme(QSettings *settings); void setEditor(const QString &editor) { m_editor = editor; } void createPreview(ItemFactory *itemFactory); protected: void showEvent(QShowEvent *event) override; private: void onFontButtonClicked(); void onColorButtonClicked(); void onPushButtonLoadThemeClicked(); void onPushButtonSaveThemeClicked(); void onPushButtonResetThemeClicked(); void onPushButtonEditThemeClicked(); void onCheckBoxShowNumberStateChanged(int); void onCheckBoxScrollbarsStateChanged(int); void onCheckBoxAntialiasStateChanged(int); void onComboBoxThemesActivated(const QString &text); void onThemeModified(const QByteArray &bytes); void updateThemes(); void addThemes(const QString &path); void updateStyle(); void fontButtonClicked(QObject *button); void colorButtonClicked(QObject *button); void updateColorButtons(); void updateFontButtons(); QIcon createThemeIcon(const QString &fileName); void decoratePreview(); void decoratePreviewNow(); Ui::ConfigTabAppearance *ui; Theme m_theme; QString m_editor; QWidget *m_preview = nullptr; ItemFactory *m_itemFactory = nullptr; QTimer m_timerPreview; }; #endif // CONFIGTABAPPEARANCE_H
1,890
C++
.h
58
28.62069
64
0.767146
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,420
filtercompleter.h
hluk_CopyQ/src/gui/filtercompleter.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef FILTERCOMPLETER_H #define FILTERCOMPLETER_H #include <QCompleter> #include <QStringList> class QLineEdit; class FilterCompleter final : public QCompleter { Q_OBJECT Q_PROPERTY(QStringList history READ history WRITE setHistory) public: static void installCompleter(QLineEdit *lineEdit); static void removeCompleter(QLineEdit *lineEdit); QStringList history() const; void setHistory(const QStringList &history); protected: bool eventFilter(QObject *obj, QEvent *event) override; private: void onTextEdited(const QString &text); void onEditingFinished(); void onComplete(); explicit FilterCompleter(QLineEdit *lineEdit); void setUnfiltered(bool unfiltered); void prependItem(const QString &item); QLineEdit *m_lineEdit; QString m_lastText; }; #endif // FILTERCOMPLETER_H
891
C++
.h
28
28.321429
65
0.776084
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,421
notificationbutton.h
hluk_CopyQ/src/gui/notificationbutton.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef NOTIFICATIONBUTTON_H #define NOTIFICATIONBUTTON_H #include <QByteArray> #include <QList> #include <QMetaType> #include <QString> struct NotificationButton { QString name; QString script; QByteArray data; }; Q_DECLARE_METATYPE(NotificationButton) using NotificationButtons = QList<NotificationButton>; #endif // NOTIFICATIONBUTTON_H
403
C++
.h
16
23.0625
54
0.811024
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,422
configtabtabs.h
hluk_CopyQ/src/gui/configtabtabs.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef CONFIGTABTABS_H #define CONFIGTABTABS_H #include <QWidget> class ItemOrderList; class QSettings; class ConfigTabTabs final : public QWidget { Q_OBJECT public: explicit ConfigTabTabs(QWidget *parent = nullptr); void saveTabs(QSettings *settings); private: ItemOrderList *m_list; }; #endif // CONFIGTABTABS_H
383
C++
.h
16
21.5
54
0.783333
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,423
clipboarddialog.h
hluk_CopyQ/src/gui/clipboarddialog.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef CLIPBOARDDIALOG_H #define CLIPBOARDDIALOG_H #include <QDialog> #include <QPersistentModelIndex> #include <QPointer> #include <QVariantMap> #include <QTimer> #include "platform/platformnativeinterface.h" class QBuffer; class QListWidgetItem; class QMovie; namespace Ui { class ClipboardDialog; } class ClipboardDialog final : public QDialog { Q_OBJECT public: /** * Create dialog with clipboard data. */ explicit ClipboardDialog(QWidget *parent = nullptr); /** * Create dialog with item data. */ explicit ClipboardDialog(const QPersistentModelIndex &index, QAbstractItemModel *model, QWidget *parent = nullptr); ~ClipboardDialog(); signals: void changeClipboard(const QVariantMap &data); private: void onListWidgetFormatsCurrentItemChanged( QListWidgetItem *current, QListWidgetItem *previous); void onActionRemoveFormatTriggered(); void onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight); void addText(); void init(); void setData(const QVariantMap &data); Ui::ClipboardDialog *ui = nullptr; QPointer<QAbstractItemModel> m_model; QPersistentModelIndex m_index; QVariantMap m_data; bool m_dataFromClipboard = false; QString m_textToShow; QTimer m_timerTextLoad; QBuffer *m_animationBuffer = nullptr; QMovie *m_animation = nullptr; PlatformClipboardPtr m_clipboard; }; #endif // CLIPBOARDDIALOG_H
1,519
C++
.h
50
26.42
119
0.756384
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,424
actionhandlerdialog.h
hluk_CopyQ/src/gui/actionhandlerdialog.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef ACTIONHANDLERDIALOG_H #define ACTIONHANDLERDIALOG_H #include <QDialog> class ActionHandler; class QAbstractItemModel; namespace Ui { class ActionHandlerDialog; } class ActionHandlerDialog final : public QDialog { public: explicit ActionHandlerDialog(ActionHandler *actionHandler, QAbstractItemModel *model, QWidget *parent = nullptr); ~ActionHandlerDialog(); private: Ui::ActionHandlerDialog *ui; }; #endif // ACTIONHANDLERDIALOG_H
504
C++
.h
18
25.944444
117
0.820459
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,425
traymenu.h
hluk_CopyQ/src/gui/traymenu.h
// SPDX-License-Identifier: GPL-3.0-or-later #ifndef TRAYMENU_H #define TRAYMENU_H #include "common/navigationstyle.h" #include <QMenu> #include <QPointer> #include <QTimer> class QAction; class QModelIndex; class TrayMenu final : public QMenu { Q_OBJECT public: explicit TrayMenu(QWidget *parent = nullptr); static void updateTextFromData(QAction *act, const QVariantMap &data); static bool updateIconFromData(QAction *act, const QVariantMap &data); /** * Add clipboard item action with number key hint. * * Triggering this action emits clipboardItemActionTriggered() signal. */ QAction *addClipboardItemAction(const QVariantMap &data, bool showImages); void clearClipboardItems(); void clearCustomActions(); /** Add custom action. */ void setCustomActions(QList<QAction*> actions); /** Clear clipboard item actions and curstom actions. */ void clearAllActions(); void setNavigationStyle(NavigationStyle style); /** Enable searching for numbers. */ void setNumberSearchEnabled(bool enabled); /** Filter clipboard items. */ void search(const QString &text); void markItemInClipboard(const QVariantMap &clipboardData); /** Row numbers start from one instead of zero? */ void setRowIndexFromOne(bool rowIndexFromOne) { m_rowIndexFromOne = rowIndexFromOne; } signals: /** Emitted if numbered action triggered. */ void clipboardItemActionTriggered(const QVariantMap &itemData, bool omitPaste); void searchRequest(const QString &text); protected: void keyPressEvent(QKeyEvent *event) override; void mousePressEvent(QMouseEvent *event) override; void showEvent(QShowEvent *event) override; void hideEvent(QHideEvent *event) override; void actionEvent(QActionEvent *event) override; void leaveEvent(QEvent *event) override; void inputMethodEvent(QInputMethodEvent *event) override; private: void onClipboardItemActionTriggered(); void delayedUpdateActiveAction(); void doUpdateActiveAction(); void setSearchMenuItem(const QString &text); QPointer<QAction> m_clipboardItemActionsSeparator; QPointer<QAction> m_customActionsSeparator; QPointer<QAction> m_searchAction; int m_clipboardItemActionCount; bool m_omitPaste; bool m_numberSearch; NavigationStyle m_navigationStyle = NavigationStyle::Default; QString m_searchText; QTimer m_timerUpdateActiveAction; bool m_rowIndexFromOne = true; QList<QAction*> m_clipboardActions; QList<QAction*> m_customActions; }; #endif // TRAYMENU_H
2,609
C++
.h
67
34.41791
90
0.759363
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,426
notificationnative.h
hluk_CopyQ/src/gui/notificationnative/notificationnative.h
// SPDX-License-Identifier: GPL-3.0-or-later #pragma once class Notification; class QColor; class QObject; Notification *createNotificationNative(const QColor &iconColor, QObject *parent);
192
C++
.h
6
30.5
81
0.830601
hluk/CopyQ
8,577
439
420
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,427
common_auth.cpp
s3fs-fuse_s3fs-fuse/src/common_auth.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <cstdio> #include <string> #include "s3fs_auth.h" #include "string_util.h" //------------------------------------------------------------------- // Utility Function //------------------------------------------------------------------- std::string s3fs_get_content_md5(int fd) { md5_t md5; if(!s3fs_md5_fd(fd, 0, -1, &md5)){ // TODO: better return value? return ""; } return s3fs_base64(md5.data(), md5.size()); } std::string s3fs_sha256_hex_fd(int fd, off_t start, off_t size) { sha256_t sha256; if(!s3fs_sha256_fd(fd, start, size, &sha256)){ // TODO: better return value? return ""; } std::string sha256hex = s3fs_hex_lower(sha256.data(), sha256.size()); return sha256hex; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
1,737
C++
.cpp
53
30
82
0.644391
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,428
s3fs_xml.cpp
s3fs-fuse_s3fs-fuse/src/s3fs_xml.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <cstdio> #include <cstdlib> #include <libxml/xpathInternals.h> #include <mutex> #include <string> #include "common.h" #include "s3fs_logger.h" #include "s3fs_xml.h" #include "s3fs_util.h" #include "s3objlist.h" #include "string_util.h" //------------------------------------------------------------------- // Symbols //------------------------------------------------------------------- enum class get_object_name_result : std::uint8_t { SUCCESS, FAILURE, FILE_OR_SUBDIR_IN_DIR }; //------------------------------------------------------------------- // Variables //------------------------------------------------------------------- // [NOTE] // mutex for static variables in GetXmlNsUrl // static std::mutex xml_parser_mutex; //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- static bool GetXmlNsUrl(xmlDocPtr doc, std::string& nsurl) { bool result = false; if(!doc){ return result; } std::string tmpNs; { static time_t tmLast = 0; // cache for 60 sec. static std::string strNs; const std::lock_guard<std::mutex> lock(xml_parser_mutex); if((tmLast + 60) < time(nullptr)){ // refresh tmLast = time(nullptr); strNs = ""; xmlNodePtr pRootNode = xmlDocGetRootElement(doc); if(pRootNode){ std::unique_ptr<xmlNsPtr, decltype(xmlFree)> nslist(xmlGetNsList(doc, pRootNode), xmlFree); if(nslist){ if(*nslist && (*nslist)[0].href){ int len = xmlStrlen((*nslist)[0].href); if(0 < len){ strNs = std::string(reinterpret_cast<const char*>((*nslist)[0].href), len); } } } } } tmpNs = strNs; } if(!tmpNs.empty()){ nsurl = tmpNs; result = true; } return result; } static unique_ptr_xmlChar get_base_exp(xmlDocPtr doc, const char* exp) { std::string xmlnsurl; std::string exp_string; if(!doc){ return {nullptr, xmlFree}; } unique_ptr_xmlXPathContext ctx(xmlXPathNewContext(doc), xmlXPathFreeContext); if(!noxmlns && GetXmlNsUrl(doc, xmlnsurl)){ xmlXPathRegisterNs(ctx.get(), reinterpret_cast<const xmlChar*>("s3"), reinterpret_cast<const xmlChar*>(xmlnsurl.c_str())); exp_string = "/s3:ListBucketResult/s3:"; } else { exp_string = "/ListBucketResult/"; } exp_string += exp; unique_ptr_xmlXPathObject marker_xp(xmlXPathEvalExpression(reinterpret_cast<const xmlChar*>(exp_string.c_str()), ctx.get()), xmlXPathFreeObject); if(nullptr == marker_xp){ return {nullptr, xmlFree}; } if(xmlXPathNodeSetIsEmpty(marker_xp->nodesetval)){ S3FS_PRN_INFO("marker_xp->nodesetval is empty."); return {nullptr, xmlFree}; } xmlNodeSetPtr nodes = marker_xp->nodesetval; unique_ptr_xmlChar result(xmlNodeListGetString(doc, nodes->nodeTab[0]->xmlChildrenNode, 1), xmlFree); return result; } static unique_ptr_xmlChar get_prefix(xmlDocPtr doc) { return get_base_exp(doc, "Prefix"); } unique_ptr_xmlChar get_next_continuation_token(xmlDocPtr doc) { return get_base_exp(doc, "NextContinuationToken"); } unique_ptr_xmlChar get_next_marker(xmlDocPtr doc) { return get_base_exp(doc, "NextMarker"); } static std::pair<get_object_name_result, std::string> get_object_name(xmlDocPtr doc, xmlNodePtr node, const char* path) { // Get full path unique_ptr_xmlChar fullpath(xmlNodeListGetString(doc, node, 1), xmlFree); if(!fullpath){ S3FS_PRN_ERR("could not get object full path name.."); return {get_object_name_result::FAILURE, ""}; } // basepath(path) is as same as fullpath. if(0 == strcmp(reinterpret_cast<char*>(fullpath.get()), path)){ return {get_object_name_result::FILE_OR_SUBDIR_IN_DIR, ""}; } // Make dir path and filename std::string strdirpath = mydirname(reinterpret_cast<const char*>(fullpath.get())); std::string strmybpath = mybasename(reinterpret_cast<const char*>(fullpath.get())); const char* dirpath = strdirpath.c_str(); const char* mybname = strmybpath.c_str(); const char* basepath= (path && '/' == path[0]) ? &path[1] : path; if('\0' == mybname[0]){ return {get_object_name_result::FAILURE, ""}; } // check subdir & file in subdir if(0 < strlen(dirpath)){ // case of "/" if(0 == strcmp(mybname, "/") && 0 == strcmp(dirpath, "/")){ return {get_object_name_result::FILE_OR_SUBDIR_IN_DIR, ""}; } // case of "." if(0 == strcmp(mybname, ".") && 0 == strcmp(dirpath, ".")){ return {get_object_name_result::FILE_OR_SUBDIR_IN_DIR, ""}; } // case of ".." if(0 == strcmp(mybname, "..") && 0 == strcmp(dirpath, ".")){ return {get_object_name_result::FILE_OR_SUBDIR_IN_DIR, ""}; } // case of "name" if(0 == strcmp(dirpath, ".")){ // OK return {get_object_name_result::SUCCESS, mybname}; }else{ if(basepath && 0 == strcmp(dirpath, basepath)){ // OK return {get_object_name_result::SUCCESS, mybname}; }else if(basepath && 0 < strlen(basepath) && '/' == basepath[strlen(basepath) - 1] && 0 == strncmp(dirpath, basepath, strlen(basepath) - 1)){ std::string withdirname; if(strlen(dirpath) > strlen(basepath)){ withdirname = &dirpath[strlen(basepath)]; } // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(!withdirname.empty() && '/' != *withdirname.rbegin()){ withdirname += "/"; } withdirname += mybname; return {get_object_name_result::SUCCESS, withdirname}; } } } // case of something wrong return {get_object_name_result::FILE_OR_SUBDIR_IN_DIR, ""}; } static unique_ptr_xmlChar get_exp_value_xml(xmlDocPtr doc, xmlXPathContextPtr ctx, const char* exp_key) { if(!doc || !ctx || !exp_key){ return {nullptr, xmlFree}; } xmlNodeSetPtr exp_nodes; // search exp_key tag unique_ptr_xmlXPathObject exp(xmlXPathEvalExpression(reinterpret_cast<const xmlChar*>(exp_key), ctx), xmlXPathFreeObject); if(nullptr == exp){ S3FS_PRN_ERR("Could not find key(%s).", exp_key); return {nullptr, xmlFree}; } if(xmlXPathNodeSetIsEmpty(exp->nodesetval)){ S3FS_PRN_ERR("Key(%s) node is empty.", exp_key); return {nullptr, xmlFree}; } // get exp_key value & set in struct exp_nodes = exp->nodesetval; unique_ptr_xmlChar exp_value(xmlNodeListGetString(doc, exp_nodes->nodeTab[0]->xmlChildrenNode, 1), xmlFree); if(nullptr == exp_value){ S3FS_PRN_ERR("Key(%s) value is empty.", exp_key); return {nullptr, xmlFree}; } return exp_value; } bool get_incomp_mpu_list(xmlDocPtr doc, incomp_mpu_list_t& list) { if(!doc){ return false; } unique_ptr_xmlXPathContext ctx(xmlXPathNewContext(doc), xmlXPathFreeContext); std::string xmlnsurl; std::string ex_upload = "//"; std::string ex_key; std::string ex_id; std::string ex_date; if(!noxmlns && GetXmlNsUrl(doc, xmlnsurl)){ xmlXPathRegisterNs(ctx.get(), reinterpret_cast<const xmlChar*>("s3"), reinterpret_cast<const 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 unique_ptr_xmlXPathObject upload_xp(xmlXPathEvalExpression(reinterpret_cast<const xmlChar*>(ex_upload.c_str()), ctx.get()), xmlXPathFreeObject); if(nullptr == upload_xp){ S3FS_PRN_ERR("xmlXPathEvalExpression returns null."); return false; } if(xmlXPathNodeSetIsEmpty(upload_xp->nodesetval)){ S3FS_PRN_INFO("upload_xp->nodesetval is empty."); 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]; INCOMP_MPU_INFO part; // search "Key" tag unique_ptr_xmlChar ex_value(get_exp_value_xml(doc, ctx.get(), ex_key.c_str())); if(nullptr == ex_value){ continue; } if('/' != *(reinterpret_cast<char*>(ex_value.get()))){ part.key = "/"; }else{ part.key = ""; } part.key += reinterpret_cast<char*>(ex_value.get()); // search "UploadId" tag if(nullptr == (ex_value = get_exp_value_xml(doc, ctx.get(), ex_id.c_str()))){ continue; } part.id = reinterpret_cast<char*>(ex_value.get()); // search "Initiated" tag if(nullptr == (ex_value = get_exp_value_xml(doc, ctx.get(), ex_date.c_str()))){ continue; } part.date = reinterpret_cast<char*>(ex_value.get()); list.push_back(part); } return true; } bool is_truncated(xmlDocPtr doc) { unique_ptr_xmlChar strTruncate(get_base_exp(doc, "IsTruncated")); if(!strTruncate){ return false; } return 0 == strcasecmp(reinterpret_cast<const char*>(strTruncate.get()), "true"); } 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, bool prefix) { xmlNodeSetPtr content_nodes; unique_ptr_xmlXPathObject contents_xp(xmlXPathEvalExpression(reinterpret_cast<const xmlChar*>(ex_contents), ctx), xmlXPathFreeObject); if(nullptr == contents_xp){ S3FS_PRN_ERR("xmlXPathEvalExpression returns null."); return -1; } if(xmlXPathNodeSetIsEmpty(contents_xp->nodesetval)){ S3FS_PRN_DBG("contents_xp->nodesetval is empty."); return 0; } content_nodes = contents_xp->nodesetval; bool is_dir; std::string stretag; int i; for(i = 0; i < content_nodes->nodeNr; i++){ ctx->node = content_nodes->nodeTab[i]; // object name unique_ptr_xmlXPathObject key(xmlXPathEvalExpression(reinterpret_cast<const xmlChar*>(ex_key), ctx), xmlXPathFreeObject); if(nullptr == key){ S3FS_PRN_WARN("key is null. but continue."); continue; } if(xmlXPathNodeSetIsEmpty(key->nodesetval)){ S3FS_PRN_WARN("node is empty. but continue."); continue; } xmlNodeSetPtr key_nodes = key->nodesetval; auto result = get_object_name(doc, key_nodes->nodeTab[0]->xmlChildrenNode, path); switch(result.first){ case get_object_name_result::FAILURE: S3FS_PRN_WARN("name is something wrong. but continue."); break; case get_object_name_result::SUCCESS: { is_dir = isCPrefix ? true : false; stretag = ""; if(!isCPrefix && ex_etag){ // Get ETag unique_ptr_xmlXPathObject ETag(xmlXPathEvalExpression(reinterpret_cast<const xmlChar*>(ex_etag), ctx), xmlXPathFreeObject); if(nullptr != ETag){ if(xmlXPathNodeSetIsEmpty(ETag->nodesetval)){ S3FS_PRN_INFO("ETag->nodesetval is empty."); }else{ xmlNodeSetPtr etag_nodes = ETag->nodesetval; unique_ptr_xmlChar petag(xmlNodeListGetString(doc, etag_nodes->nodeTab[0]->xmlChildrenNode, 1), xmlFree); if(petag){ stretag = reinterpret_cast<const char*>(petag.get()); } } } } // [NOTE] // The XML data passed to this function is CR code(\r) encoded. // The function below decodes that encoded CR code. // std::string decname = get_decoded_cr_code(result.second.c_str()); if(prefix){ head.AddCommonPrefix(decname); } if(!head.insert(decname.c_str(), (!stretag.empty() ? stretag.c_str() : nullptr), is_dir)){ S3FS_PRN_ERR("insert_object returns with error."); return -1; } break; } case get_object_name_result::FILE_OR_SUBDIR_IN_DIR: S3FS_PRN_DBG("name is file or subdir in dir. but continue."); break; } } return 0; } int append_objects_from_xml(const char* path, xmlDocPtr doc, S3ObjList& head) { std::string xmlnsurl; std::string ex_contents = "//"; std::string ex_key; std::string ex_cprefix = "//"; std::string ex_prefix; std::string ex_etag; if(!doc){ return -1; } // If there is not <Prefix>, use path instead of it. auto pprefix = get_prefix(doc); std::string prefix = (pprefix ? reinterpret_cast<char*>(pprefix.get()) : path ? path : ""); unique_ptr_xmlXPathContext ctx(xmlXPathNewContext(doc), xmlXPathFreeContext); if(!noxmlns && GetXmlNsUrl(doc, xmlnsurl)){ xmlXPathRegisterNs(ctx.get(), reinterpret_cast<const xmlChar*>("s3"), reinterpret_cast<const 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.get(), ex_contents.c_str(), ex_key.c_str(), ex_etag.c_str(), 0, head, /*prefix=*/ false) || -1 == append_objects_from_xml_ex(prefix.c_str(), doc, ctx.get(), ex_cprefix.c_str(), ex_prefix.c_str(), nullptr, 1, head, /*prefix=*/ true) ) { S3FS_PRN_ERR("append_objects_from_xml_ex returns with error."); return -1; } return 0; } //------------------------------------------------------------------- // Utility functions //------------------------------------------------------------------- bool simple_parse_xml(const char* data, size_t len, const char* key, std::string& value) { bool result = false; if(!data || !key){ return false; } value.clear(); std::unique_ptr<xmlDoc, decltype(&xmlFreeDoc)> doc(xmlReadMemory(data, static_cast<int>(len), "", nullptr, 0), xmlFreeDoc); if(nullptr == doc){ return false; } if(nullptr == doc->children){ return false; } for(xmlNodePtr cur_node = doc->children->children; nullptr != cur_node; cur_node = cur_node->next){ // For DEBUG // std::string cur_node_name(reinterpret_cast<const char *>(cur_node->name)); // printf("cur_node_name: %s\n", cur_node_name.c_str()); if(XML_ELEMENT_NODE == cur_node->type){ std::string elementName = reinterpret_cast<const char*>(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 == key) { value = reinterpret_cast<const char *>(cur_node->children->content); result = true; break; } } } } } return result; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
16,949
C++
.cpp
436
31.130734
198
0.574833
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,429
test_curl_util.cpp
s3fs-fuse_s3fs-fuse/src/test_curl_util.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2020 Andrew Gaul <andrew@gaul.org> * * 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 <string> #include <cstring> #include "curl_util.h" #include "test_util.h" //--------------------------------------------------------- // S3fsCred Stub // // [NOTE] // This test program links curl_util.cpp just to use the // curl_slist_sort_insert function. // This file has a call to S3fsCred::GetBucket(), which // results in a link error. That method is not used in // this test file, so define a stub class. Linking all // implementation of the S3fsCred class or making all // stubs is not practical, so this is the best answer. // class S3fsCred { private: static std::string bucket_name; public: static const std::string& GetBucket(); }; std::string S3fsCred::bucket_name; const std::string& S3fsCred::GetBucket() { return S3fsCred::bucket_name; } //--------------------------------------------------------- #define ASSERT_IS_SORTED(x) assert_is_sorted((x), __FILE__, __LINE__) void assert_is_sorted(const struct curl_slist* list, const char *file, int line) { for(; list != nullptr; list = list->next){ std::string key1 = list->data; key1.erase(key1.find(':')); std::string key2 = list->data; key2.erase(key2.find(':')); std::cerr << "key1: " << key1 << " key2: " << key2 << std::endl; if(strcasecmp(key1.c_str(), key2.c_str()) > 0){ std::cerr << "not sorted: " << key1 << " " << key2 << " at " << file << ":" << line << std::endl; std::exit(1); } } std::cerr << std::endl; } size_t curl_slist_length(const struct curl_slist* list) { size_t len = 0; for(; list != nullptr; list = list->next){ ++len; } return len; } void test_sort_insert() { struct curl_slist* list = nullptr; ASSERT_IS_SORTED(list); // add to head list = curl_slist_sort_insert(list, "2", "val"); ASSERT_IS_SORTED(list); // add to tail list = curl_slist_sort_insert(list, "4", "val"); ASSERT_IS_SORTED(list); // add in between list = curl_slist_sort_insert(list, "3", "val"); ASSERT_IS_SORTED(list); // add to head list = curl_slist_sort_insert(list, "1", "val"); ASSERT_IS_SORTED(list); ASSERT_STREQUALS("1: val", list->data); // replace head list = curl_slist_sort_insert(list, "1", "val2"); ASSERT_IS_SORTED(list); ASSERT_EQUALS(static_cast<size_t>(4), curl_slist_length(list)); ASSERT_STREQUALS("1: val2", list->data); curl_slist_free_all(list); } void test_slist_remove() { struct curl_slist* list = nullptr; // remove no elements ASSERT_EQUALS(static_cast<size_t>(0), curl_slist_length(list)); list = curl_slist_remove(list, "1"); ASSERT_EQUALS(static_cast<size_t>(0), curl_slist_length(list)); // remove only element list = nullptr; list = curl_slist_sort_insert(list, "1", "val"); ASSERT_EQUALS(static_cast<size_t>(1), curl_slist_length(list)); list = curl_slist_remove(list, "1"); ASSERT_EQUALS(static_cast<size_t>(0), curl_slist_length(list)); // remove head element list = nullptr; list = curl_slist_sort_insert(list, "1", "val"); list = curl_slist_sort_insert(list, "2", "val"); ASSERT_EQUALS(static_cast<size_t>(2), curl_slist_length(list)); list = curl_slist_remove(list, "1"); ASSERT_EQUALS(static_cast<size_t>(1), curl_slist_length(list)); curl_slist_free_all(list); // remove tail element list = nullptr; list = curl_slist_sort_insert(list, "1", "val"); list = curl_slist_sort_insert(list, "2", "val"); ASSERT_EQUALS(static_cast<size_t>(2), curl_slist_length(list)); list = curl_slist_remove(list, "2"); ASSERT_EQUALS(static_cast<size_t>(1), curl_slist_length(list)); curl_slist_free_all(list); // remove middle element list = nullptr; list = curl_slist_sort_insert(list, "1", "val"); list = curl_slist_sort_insert(list, "2", "val"); list = curl_slist_sort_insert(list, "3", "val"); ASSERT_EQUALS(static_cast<size_t>(3), curl_slist_length(list)); list = curl_slist_remove(list, "2"); ASSERT_EQUALS(static_cast<size_t>(2), curl_slist_length(list)); curl_slist_free_all(list); } int main(int argc, const char *argv[]) { test_sort_insert(); test_slist_remove(); return 0; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
5,247
C++
.cpp
149
31.416107
109
0.640945
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
18,430
s3fs_help.cpp
s3fs-fuse_s3fs-fuse/src/s3fs_help.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <cstdio> #include <string> #include "common.h" #include "s3fs_help.h" #include "s3fs_auth.h" //------------------------------------------------------------------- // Contents //------------------------------------------------------------------- static constexpr char help_string[] = "\n" "Mount an Amazon S3 bucket as a file system.\n" "\n" "Usage:\n" " mounting\n" " s3fs bucket[:/path] mountpoint [options]\n" " s3fs mountpoint [options (must specify bucket= option)]\n" "\n" " unmounting\n" " umount mountpoint\n" "\n" " General forms for s3fs and FUSE/mount options:\n" " -o opt[,opt...]\n" " -o opt [-o opt] ...\n" "\n" " utility mode (remove interrupted multipart uploading objects)\n" " s3fs --incomplete-mpu-list (-u) bucket\n" " s3fs --incomplete-mpu-abort[=all | =<date format>] bucket\n" "\n" "s3fs Options:\n" "\n" " Most s3fs options are given in the form where \"opt\" is:\n" "\n" " <option_name>=<option_value>\n" "\n" " bucket\n" " - if it is not specified bucket name (and path) in command line,\n" " must specify this option after -o option for bucket name.\n" "\n" " default_acl (default=\"private\")\n" " - the default canned acl to apply to all written s3 objects,\n" " e.g., private, public-read. see\n" " https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl\n" " for the full list of canned ACLs\n" "\n" " retries (default=\"5\")\n" " - number of times to retry a failed S3 transaction\n" "\n" " tmpdir (default=\"/tmp\")\n" " - local folder for temporary files.\n" "\n" " use_cache (default=\"\" which means disabled)\n" " - local folder to use for local file cache\n" "\n" " check_cache_dir_exist (default is disable)\n" " - if use_cache is set, check if the cache directory exists.\n" " If this option is not specified, it will be created at runtime\n" " when the cache directory does not exist.\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, onezone_ia, reduced_redundancy,\n" " intelligent_tiering, glacier, glacier_ir, and deep_archive.\n" "\n" " use_rrs (default is disable)\n" " - use Amazon's Reduced Redundancy Storage.\n" " this option can not be specified with use_sse.\n" " (can specify use_rrs=1 for old version)\n" " this option has been replaced by new storage_class option.\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:<custom key file path>\" or\n" " \"use_sse=<custom key file path>\" (only <custom key file path>\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 downloading, 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:<kms id>\". You can use \"k\" for short \"kmsid\".\n" " If you san specify SSE-KMS type with your <kms id> 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 <kms id>. You must be careful\n" " about that you can not use the KMS id which is not same EC2\n" " region.\n" " Additionally, if you specify SSE-KMS, your endpoints must use\n" " Secure Sockets Layer(SSL) or Transport Layer Security(TLS).\n" "\n" " load_sse_c - specify SSE-C keys\n" " Specify the custom-provided encryption keys file path for decrypting\n" " at downloading.\n" " If you use the custom-provided encryption 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, ignores the \n" " $HOME/.passwd-s3fs and /etc/passwd-s3fs files.\n" " S3 does not allow copy object api for anonymous users, then\n" " s3fs sets nocopyapi option automatically when public_bucket=1\n" " option is specified.\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 or regex] HTTP-header [HTTP-values]\n" " file suffix = file (object) suffix, if this field is empty,\n" " it means \"reg:(.*)\".(=all object).\n" " regex = regular expression to match the file (object) path.\n" " this type starts with \"reg:\" prefix.\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" " reg:^/MYDIR/(.*)[.]t2$ Content-Encoding text2\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" " profile (default=\"default\")\n" " - Choose a profile from ${HOME}/.aws/credentials to authenticate\n" " against S3. Note that this format matches the AWS CLI format and\n" " differs from the s3fs passwd format.\n" "\n" " connect_timeout (default=\"300\" seconds)\n" " - time to wait for connection before giving up\n" "\n" " readwrite_timeout (default=\"120\" seconds)\n" " - time to wait between read/write activity before giving up\n" "\n" " list_object_max_keys (default=\"1000\")\n" " - specify the maximum number of keys returned by S3 list object\n" " API. The default is 1000. you can set this value to 1000 or more.\n" "\n" " max_stat_cache_size (default=\"100,000\" entries (about 40MB))\n" " - maximum number of entries in the stat cache, and this maximum is\n" " also treated as the number of symbolic link cache.\n" "\n" " stat_cache_expire (default is 900))\n" " - specify expire time (seconds) for entries in the stat cache.\n" " This expire time indicates the time since stat cached. and this\n" " is also set to the expire time of the symbolic link cache.\n" "\n" " stat_cache_interval_expire (default is 900)\n" " - specify expire time (seconds) for entries in the stat cache(and\n" " symbolic link cache).\n" " This expire time is based on the time from the last access time\n" " of the stat cache. This option is exclusive with stat_cache_expire,\n" " and is left for compatibility with older versions.\n" "\n" " disable_noobj_cache (default is enable)\n" " - By default s3fs memorizes when an object does not exist up until\n" " the stat cache timeout. This caching can cause staleness for\n" " applications. If disabled, s3fs will not memorize objects and may\n" " cause extra HeadObject requests and reduce performance.\n" "\n" " no_check_certificate\n" " - server certificate won't be checked against the available \n" " certificate authorities.\n" "\n" " ssl_verify_hostname (default=\"2\")\n" " - When 0, do not verify the SSL certificate against the hostname.\n" "\n" " ssl_client_cert (default=\"\")\n" " - Specify an SSL client certificate.\n" " Specify this optional parameter in the following format:\n" " \"<SSL Cert>[:<Cert Type>[:<Private Key>[:<Key Type>\n" " [:<Password>]]]]\"\n" " <SSL Cert>: Client certificate.\n" " Specify the file path or NickName(for NSS, etc.).\n" " <Cert Type>: Type of certificate, default is \"PEM\"(optional).\n" " <Private Key>: Certificate's private key file(optional).\n" " <Key Type>: Type of private key, default is \"PEM\"(optional).\n" " <Password>: Passphrase of the private key(optional).\n" " It is also possible to omit this value and specify\n" " it using the environment variable\n" " \"S3FS_SSL_PRIVKEY_PASSWORD\".\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 upload 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" " The minimum value is 5 MB and the maximum value is 5 GB.\n" "\n" " multipart_copy_size (default=\"512\")\n" " - part size, in MB, for each multipart copy request, used for\n" " renames and mixupload.\n" " The minimum value is 5 MB and the maximum value is 5 GB.\n" " Must be at least 512 MB to copy the maximum 5 TB object size\n" " but lower values may improve performance.\n" "\n" " max_dirty_data (default=\"5120\")\n" " - flush dirty data to S3 after a certain number of MB written.\n" " The minimum value is 50 MB. -1 value means disable.\n" " Cannot be used with nomixupload.\n" "\n" " bucket_size (default=maximum long unsigned integer value)\n" " - The size of the bucket with which the corresponding\n" " elements of the statvfs structure will be filled. The option\n" " argument is an integer optionally followed by a\n" " multiplicative suffix (GB, GiB, TB, TiB, PB, PiB,\n" " EB, EiB) (no spaces in between). If no suffix is supplied,\n" " bytes are assumed; eg: 20000000, 30GB, 45TiB. Note that\n" " s3fs does not compute the actual volume size (too\n" " expensive): by default it will assume the maximum possible\n" " size; however, since this may confuse other software which\n" " uses s3fs, the advertised bucket size can be set with this\n" " option.\n" "\n" " ensure_diskfree (default 0)\n" " - sets MB to ensure disk free space. This option means the\n" " threshold of free space size on disk which is used for the\n" " cache file by s3fs. s3fs makes file for\n" " downloading, uploading and caching files. If the disk free\n" " space is smaller than this value, s3fs do not use disk space\n" " as possible in exchange for the performance.\n" "\n" " free_space_ratio (default=\"10\")\n" " - sets min free space ratio of the disk.\n" " The value of this option can be between 0 and 100. It will control\n" " the size of the cache according to this ratio to ensure that the\n" " idle ratio of the disk is greater than this value.\n" " For example, when the disk space is 50GB, the default value will\n" " ensure that the disk will reserve at least 50GB * 10%% = 5GB of\n" " remaining space.\n" "\n" " multipart_threshold (default=\"25\")\n" " - threshold, in MB, to use multipart upload instead of\n" " single-part. Must be at least 5 MB.\n" "\n" " singlepart_copy_limit (default=\"512\")\n" " - maximum size, in MB, of a single-part copy before trying \n" " multipart copy.\n" "\n" " host (default=\"https://s3.amazonaws.com\")\n" " - Set a non-Amazon host, e.g., https://example.com.\n" "\n" " servicepath (default=\"/\")\n" " - Set a service path when the non-Amazon host requires a prefix.\n" "\n" " url (default=\"https://s3.amazonaws.com\")\n" " - sets the url to use to access Amazon S3. If you want to use HTTP,\n" " then you can set \"url=http://s3.amazonaws.com\".\n" " If you do not use https, please specify the URL with the url\n" " option.\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 falling back to version 2)\n" " - sets signing AWS requests by using only signature version 2\n" "\n" " sigv4 (default is signature version 4 falling back to version 2)\n" " - sets signing AWS requests by using only signature version 4\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" " umask (default is \"0000\")\n" " - sets umask for files under the mountpoint. This can allow\n" " users other than the mounting user to read and write to files\n" " that they did not create.\n" "\n" " nomultipart (disable multipart uploads)\n" "\n" " streamupload (default is disable)\n" " - Enable stream upload.\n" " If this option is enabled, a sequential upload will be performed\n" " in parallel with the write from the part that has been written\n" " during a multipart upload.\n" " This is expected to give better performance than other upload\n" " functions.\n" " Note that this option is still experimental and may change in the\n" " future.\n" "\n" " max_thread_count (default is \"5\")\n" " - Specifies the number of threads waiting for stream uploads.\n" " Note that this option and Stream Upload are still experimental\n" " and subject to change in the future.\n" " This option will be merged with \"parallel_count\" in the future.\n" "\n" " enable_content_md5 (default is disable)\n" " - Allow S3 server to check data integrity of uploads via the\n" " Content-MD5 header. This can add CPU overhead to transfers.\n" "\n" " enable_unsigned_payload (default is disable)\n" " - Do not calculate Content-SHA256 for PutObject and UploadPart\n" " payloads. This can reduce CPU overhead to transfers.\n" "\n" " ecs (default is disable)\n" " - This option instructs s3fs to query the ECS container credential\n" " metadata address instead of the instance metadata address.\n" "\n" " iam_role (default is no IAM role)\n" " - This option requires the IAM role name or \"auto\". If you specify\n" " \"auto\", s3fs will automatically use the IAM role names that are set\n" " to an instance. If you specify this option without any argument, it\n" " is the same as that you have specified the \"auto\".\n" "\n" " imdsv1only (default is to use IMDSv2 with fallback to v1)\n" " - AWS instance metadata service, used with IAM role authentication,\n" " supports the use of an API token. If you're using an IAM role\n" " in an environment that does not support IMDSv2, setting this flag\n" " will skip retrieval and usage of the API token when retrieving\n" " IAM credentials.\n" "\n" " ibm_iam_auth (default is not using IBM IAM authentication)\n" " - This option instructs s3fs to use IBM IAM authentication.\n" " In this mode, the AWSAccessKey and AWSSecretKey will be used as\n" " IBM's Service-Instance-ID and APIKey, respectively.\n" "\n" " ibm_iam_endpoint (default is https://iam.cloud.ibm.com)\n" " - sets the URL to use for IBM IAM authentication.\n" "\n" " credlib (default=\"\" which means disabled)\n" " - Specifies the shared library that handles the credentials\n" " containing the authentication token.\n" " If this option is specified, the specified credential and token\n" " processing provided by the shared library ant will be performed\n" " instead of the built-in credential processing.\n" " This option cannot be specified with passwd_file, profile,\n" " use_session_token, ecs, ibm_iam_auth, ibm_iam_endpoint, imdsv1only\n" " and iam_role option.\n" "\n" " credlib_opts (default=\"\" which means disabled)\n" " - Specifies the options to pass when the shared library specified\n" " in credlib is loaded and then initialized.\n" " For the string specified in this option, specify the string defined\n" " by the shared library.\n" "\n" " use_xattr (default is not handling the extended attribute)\n" " Enable to handle the extended attribute (xattrs).\n" " If you set this option, you can use the extended attribute.\n" " For example, encfs and ecryptfs need to support the extended attribute.\n" " Notice: if s3fs handles the extended attribute, s3fs can not work to\n" " copy command with preserve=mode.\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" " nomixupload (disable copy in multipart uploads)\n" " Disable to use PUT (copy api) when multipart uploading large size objects.\n" " By default, when doing multipart upload, the range of unchanged data\n" " will use PUT (copy api) whenever possible.\n" " When nocopyapi or norenameapi is specified, use of PUT (copy api) is\n" " invalidated even if this option is not specified.\n" "\n" " nocopyapi (for other incomplete compatibility object storage)\n" " Enable compatibility with S3-like APIs which do not support\n" " 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" " Enable compatibility with S3-like APIs which do not support\n" " 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" " Enable 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" " listobjectsv2 (use ListObjectsV2)\n" " Issue ListObjectsV2 instead of ListObjects, useful on object\n" " stores without ListObjects support.\n" "\n" " noua (suppress User-Agent header)\n" " Usually s3fs outputs of the User-Agent in \"s3fs/<version> (commit\n" " hash <hash>; <using ssl library name>)\" format.\n" " If this option is specified, s3fs suppresses the output of the\n" " User-Agent.\n" "\n" " cipher_suites\n" " Customize the list of TLS cipher suites.\n" " Expects a colon separated list of cipher suite names.\n" " A list of available cipher suites, depending on your TLS engine,\n" " can be found on the CURL library documentation:\n" " https://curl.haxx.se/docs/ssl-ciphers.html\n" "\n" " instance_name - The instance name of the current s3fs mountpoint.\n" " This name will be added to logging messages and user agent headers sent by s3fs.\n" "\n" " complement_stat (complement lack of file/directory mode)\n" " s3fs complements lack of information about file/directory mode\n" " if a file or a directory object does not have x-amz-meta-mode\n" " header. As default, s3fs does not complements stat information\n" " for a object, then the object will not be able to be allowed to\n" " list/modify.\n" "\n" " compat_dir (enable support of alternative directory names)\n" " s3fs supports two different naming schemas \"dir/\" and\n" " \"dir\" to map directory names to S3 objects and\n" " vice versa by default. As a third variant, directories can be\n" " determined indirectly if there is a file object with a path (e.g.\n" " \"/dir/file\") but without the parent directory.\n" " This option enables a fourth variant, \"dir_$folder$\", created by\n" " older applications.\n" " \n" " S3fs uses only the first schema \"dir/\" to create S3 objects for\n" " directories." " \n" " The support for these different naming schemas causes an increased\n" " communication effort.\n" "\n" " use_wtf8 - support arbitrary file system encoding.\n" " S3 requires all object names to be valid UTF-8. But some\n" " clients, notably Windows NFS clients, use their own encoding.\n" " This option re-encodes invalid UTF-8 object names into valid\n" " UTF-8 by mapping offending codes into a 'private' codepage of the\n" " Unicode set.\n" " Useful on clients not using UTF-8 as their file system encoding.\n" "\n" " use_session_token - indicate that session token should be provided.\n" " If credentials are provided by environment variables this switch\n" " forces presence check of AWSSESSIONTOKEN variable.\n" " Otherwise an error is returned.\n" "\n" " requester_pays (default is disable)\n" " This option instructs s3fs to enable requests involving\n" " Requester Pays buckets.\n" " It includes the 'x-amz-request-payer=requester' entry in the\n" " request header.\n" "\n" " mime (default is \"/etc/mime.types\")\n" " Specify the path of the mime.types file.\n" " If this option is not specified, the existence of \"/etc/mime.types\"\n" " is checked, and that file is loaded as mime information.\n" " If this file does not exist on macOS, then \"/etc/apache2/mime.types\"\n" " is checked as well.\n" "\n" " proxy (default=\"\")\n" " This option specifies a proxy to S3 server.\n" " Specify the proxy with '[<scheme://]hostname(fqdn)[:<port>]' formatted.\n" " '<schema>://' can be omitted, and 'http://' is used when omitted.\n" " Also, ':<port>' can also be omitted. If omitted, port 443 is used for\n" " HTTPS schema, and port 1080 is used otherwise.\n" " This option is the same as the curl command's '--proxy(-x)' option and\n" " libcurl's 'CURLOPT_PROXY' flag.\n" " This option is equivalent to and takes precedence over the environment\n" " variables 'http_proxy', 'all_proxy', etc.\n" "\n" " proxy_cred_file (default=\"\")\n" " This option specifies the file that describes the username and\n" " passphrase for authentication of the proxy when the HTTP schema\n" " proxy is specified by the 'proxy' option.\n" " Username and passphrase are valid only for HTTP schema. If the HTTP\n" " proxy does not require authentication, this option is not required.\n" " Separate the username and passphrase with a ':' character and\n" " specify each as a URL-encoded string.\n" "\n" " ipresolve (default=\"whatever\")\n" " Select what type of IP addresses to use when establishing a\n" " connection.\n" " Default('whatever') can use addresses of all IP versions(IPv4 and\n" " IPv6) that your system allows. If you specify 'IPv4', only IPv4\n" " addresses are used. And when 'IPv6'is specified, only IPv6 addresses\n" " will be used.\n" "\n" " logfile - specify the log output file.\n" " s3fs outputs the log file to syslog. Alternatively, if s3fs is\n" " started with the \"-f\" option specified, the log will be output\n" " to the stdout/stderr.\n" " You can use this option to specify the log file that s3fs outputs.\n" " If you specify a log file with this option, it will reopen the log\n" " file when s3fs receives a SIGHUP signal. You can use the SIGHUP\n" " signal for log rotation.\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 bump up.\n" "\n" " curldbg - put curl debug message\n" " Put the debug message from libcurl when this option is specified.\n" " Specify \"normal\" or \"body\" for the parameter.\n" " If the parameter is omitted, it is the same as \"normal\".\n" " If \"body\" is specified, some API communication body data will be\n" " output in addition to the debug message output as \"normal\".\n" "\n" " no_time_stamp_msg - no time stamp in debug message\n" " The time stamp is output to the debug message by default.\n" " If this option is specified, the time stamp will not be output\n" " in the debug message.\n" " It is the same even if the environment variable \"S3FS_MSGTIMESTAMP\"\n" " is set to \"no\".\n" "\n" " set_check_cache_sigusr1 (default is stdout)\n" " If the cache is enabled, you can check the integrity of the\n" " cache file and the cache file's stats info file.\n" " This option is specified and when sending the SIGUSR1 signal\n" " to the s3fs process checks the cache status at that time.\n" " This option can take a file path as parameter to output the\n" " check result to that file. The file path parameter can be omitted.\n" " If omitted, the result will be output to stdout or syslog.\n" "\n" " update_parent_dir_stat (default is disable)\n" " The parent directory's mtime and ctime are updated when a file or\n" " directory is created or deleted (when the parent directory's inode is\n" " updated).\n" " By default, parent directory statistics are not updated.\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" "Utility mode Options:\n" "\n" " -u, --incomplete-mpu-list\n" " Lists multipart incomplete objects uploaded to the specified\n" " bucket.\n" " --incomplete-mpu-abort (=all or =<date format>)\n" " Delete the multipart incomplete object uploaded to the specified\n" " bucket.\n" " If \"all\" is specified for this option, all multipart incomplete\n" " objects will be deleted. If you specify no argument as an option,\n" " objects older than 24 hours (24H) will be deleted (This is the\n" " default value). You can specify an optional date format. It can\n" " be specified as year, month, day, hour, minute, second, and it is\n" " expressed as \"Y\", \"M\", \"D\", \"h\", \"m\", \"s\" respectively.\n" " For example, \"1Y6M10D12h30m30s\".\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 single-threaded option\n" " disable multi-threaded operation\n" "\n" "\n" "s3fs home page: <https://github.com/s3fs-fuse/s3fs-fuse>\n" ; //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- void show_usage() { printf("Usage: %s BUCKET:[PATH] MOUNTPOINT [OPTION]...\n", program_name.c_str()); } void show_help() { show_usage(); printf(help_string); } void show_version() { printf( "Amazon Simple Storage Service File System V%s%s with %s\n" "Copyright (C) 2010 Randy Rizun <rrizun@gmail.com>\n" "License GPL2: GNU GPL version 2 <https://gnu.org/licenses/gpl.html>\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()); } const char* short_version() { static constexpr char short_ver[] = "s3fs version " VERSION "" COMMIT_HASH_VAL; return short_ver; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
35,222
C++
.cpp
668
47.992515
96
0.608829
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,431
fdcache_pseudofd.cpp
s3fs-fuse_s3fs-fuse/src/fdcache_pseudofd.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <algorithm> #include <cstdlib> #include <mutex> #include <vector> #include "fdcache_pseudofd.h" //------------------------------------------------ // Symbols //------------------------------------------------ // [NOTE] // The minimum pseudo fd value starts 2. // This is to avoid mistakes for 0(stdout) and 1(stderr), which are usually used. // static constexpr int MIN_PSEUDOFD_NUMBER = 2; //------------------------------------------------ // PseudoFdManager class methods //------------------------------------------------ PseudoFdManager& PseudoFdManager::GetManager() { static PseudoFdManager singleton; return singleton; } int PseudoFdManager::Get() { return (PseudoFdManager::GetManager()).CreatePseudoFd(); } bool PseudoFdManager::Release(int fd) { return (PseudoFdManager::GetManager()).ReleasePseudoFd(fd); } //------------------------------------------------ // PseudoFdManager methods //------------------------------------------------ int PseudoFdManager::GetUnusedMinPseudoFd() const { int min_fd = MIN_PSEUDOFD_NUMBER; // Look for the first discontinuous value. for(auto iter = pseudofd_list.cbegin(); iter != pseudofd_list.cend(); ++iter){ if(min_fd == (*iter)){ ++min_fd; }else if(min_fd < (*iter)){ break; } } return min_fd; } int PseudoFdManager::CreatePseudoFd() { const std::lock_guard<std::mutex> lock(pseudofd_list_lock); int new_fd = PseudoFdManager::GetUnusedMinPseudoFd(); pseudofd_list.push_back(new_fd); std::sort(pseudofd_list.begin(), pseudofd_list.end()); return new_fd; } bool PseudoFdManager::ReleasePseudoFd(int fd) { const std::lock_guard<std::mutex> lock(pseudofd_list_lock); for(auto iter = pseudofd_list.begin(); iter != pseudofd_list.end(); ++iter){ if(fd == (*iter)){ pseudofd_list.erase(iter); return true; } } return false; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,927
C++
.cpp
91
29.054945
82
0.632884
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,432
test_page_list.cpp
s3fs-fuse_s3fs-fuse/src/test_page_list.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2021 Andrew Gaul <andrew@gaul.org> * * 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 "fdcache_page.h" #include "fdcache_stat.h" #include "test_util.h" bool CacheFileStat::Open() { return false; } // NOLINT(readability-convert-member-functions-to-static) void test_compress() { PageList list; ASSERT_EQUALS(off_t(0), list.Size()); list.Init(42, /*is_loaded=*/ false, /*is_modified=*/ false); ASSERT_EQUALS(off_t(42), list.Size()); ASSERT_FALSE(list.IsPageLoaded(0, 1)); list.SetPageLoadedStatus(0, 1, /*pstatus=*/ PageList::page_status::LOADED); ASSERT_TRUE(list.IsPageLoaded(0, 1)); ASSERT_FALSE(list.IsPageLoaded(0, 2)); off_t start = 0; off_t size = 0; ASSERT_TRUE(list.FindUnloadedPage(0, start, size)); ASSERT_EQUALS(off_t(1), start); ASSERT_EQUALS(off_t(41), size); // test adding subsequent page then compressing list.SetPageLoadedStatus(1, 3, /*pstatus=*/ PageList::page_status::LOADED); list.Compress(); ASSERT_TRUE(list.IsPageLoaded(0, 3)); ASSERT_TRUE(list.FindUnloadedPage(0, start, size)); ASSERT_EQUALS(off_t(4), start); ASSERT_EQUALS(off_t(38), size); // test adding non-contiguous page then compressing list.SetPageLoadedStatus(5, 1, /*pstatus=*/ PageList::page_status::LOADED); list.Compress(); ASSERT_TRUE(list.FindUnloadedPage(0, start, size)); ASSERT_EQUALS(off_t(4), start); ASSERT_EQUALS(off_t(1), size); list.Dump(); printf("\n"); // test adding page between two pages then compressing list.SetPageLoadedStatus(4, 1, /*pstatus=*/ PageList::page_status::LOADED); list.Compress(); list.Dump(); ASSERT_TRUE(list.FindUnloadedPage(0, start, size)); ASSERT_EQUALS(off_t(6), start); ASSERT_EQUALS(off_t(36), size); } int main(int argc, const char *argv[]) { test_compress(); return 0; }
2,550
C++
.cpp
66
36.045455
103
0.724808
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
18,433
mpu_util.cpp
s3fs-fuse_s3fs-fuse/src/mpu_util.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <cstdio> #include <cstdlib> #include <string> #include "s3fs.h" #include "s3fs_logger.h" #include "mpu_util.h" #include "curl.h" #include "s3fs_xml.h" #include "s3fs_auth.h" #include "string_util.h" #include "s3fs_threadreqs.h" //------------------------------------------------------------------- // Global variables //------------------------------------------------------------------- utility_incomp_type utility_mode = utility_incomp_type::NO_UTILITY_MODE; //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- static void print_incomp_mpu_list(const incomp_mpu_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(auto iter = list.cbegin(); iter != list.cend(); ++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_incomp_mpu_list(const incomp_mpu_list_t& list, time_t abort_time) { if(list.empty()){ return true; } time_t now_time = time(nullptr); // do removing. bool result = true; for(auto iter = list.cbegin(); iter != list.cend(); ++iter){ const char* tpath = (*iter).key.c_str(); std::string upload_id = (*iter).id; if(0 != abort_time){ // abort_time is 0, it means all. time_t date = 0; if(!get_unixtime_from_iso8601((*iter).date.c_str(), date)){ S3FS_PRN_DBG("date format is not ISO 8601 for %s multipart uploading object, skip this.", tpath); continue; } if(now_time <= (date + abort_time)){ continue; } } if(0 != abort_multipart_upload_request(std::string(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); } } return result; } int s3fs_utility_processing(time_t abort_time) { if(utility_incomp_type::NO_UTILITY_MODE == utility_mode){ return EXIT_FAILURE; } printf("\n*** s3fs run as utility mode.\n\n"); S3fsCurl s3fscurl; std::string body; int result = EXIT_SUCCESS; if(0 != s3fscurl.MultipartListRequest(body)){ S3FS_PRN_EXIT("Could not get list multipart upload.\nThere is no incomplete multipart uploaded object in bucket.\n"); result = EXIT_FAILURE; }else{ // parse result(incomplete multipart upload information) S3FS_PRN_DBG("response body = {\n%s\n}", body.c_str()); std::unique_ptr<xmlDoc, decltype(&xmlFreeDoc)> doc(xmlReadMemory(body.c_str(), static_cast<int>(body.size()), "", nullptr, 0), xmlFreeDoc); if(nullptr == doc){ S3FS_PRN_DBG("xmlReadMemory exited with error."); result = EXIT_FAILURE; }else{ // make incomplete uploads list incomp_mpu_list_t list; if(!get_incomp_mpu_list(doc.get(), list)){ S3FS_PRN_DBG("get_incomp_mpu_list exited with error."); result = EXIT_FAILURE; }else{ if(utility_incomp_type::INCOMP_TYPE_LIST == utility_mode){ // print list print_incomp_mpu_list(list); }else if(utility_incomp_type::INCOMP_TYPE_ABORT == utility_mode){ // remove if(!abort_incomp_mpu_list(list, abort_time)){ S3FS_PRN_DBG("an error occurred during removal process."); result = EXIT_FAILURE; } } } } } // ssl s3fs_destroy_global_ssl(); return result; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
5,281
C++
.cpp
137
31.49635
147
0.553366
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,435
fdcache_untreated.cpp
s3fs-fuse_s3fs-fuse/src/fdcache_untreated.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <cstdlib> #include <mutex> #include "s3fs_logger.h" #include "fdcache_untreated.h" //------------------------------------------------ // UntreatedParts methods //------------------------------------------------ bool UntreatedParts::empty() { const std::lock_guard<std::mutex> lock(untreated_list_lock); return untreated_list.empty(); } bool UntreatedParts::AddPart(off_t start, off_t size) { if(start < 0 || size <= 0){ S3FS_PRN_ERR("Parameter are wrong(start=%lld, size=%lld).", static_cast<long long int>(start), static_cast<long long int>(size)); return false; } const std::lock_guard<std::mutex> lock(untreated_list_lock); ++last_tag; // Check the overlap with the existing part and add the part. for(auto iter = untreated_list.begin(); iter != untreated_list.end(); ++iter){ if(iter->stretch(start, size, last_tag)){ // the part was stretched, thus check if it overlaps with next parts auto niter = iter; for(++niter; niter != untreated_list.cend(); ){ if(!iter->stretch(niter->start, niter->size, last_tag)){ // This next part does not overlap with the current part break; } // Since the parts overlap and the current part is stretched, delete this next part. niter = untreated_list.erase(niter); } // success to stretch and compress existed parts return true; }else if((start + size) < iter->start){ // The part to add should be inserted before the current part. untreated_list.insert(iter, untreatedpart(start, size, last_tag)); // success to stretch and compress existed parts return true; } } // There are no overlapping parts in the untreated_list, then add the part at end of list untreated_list.emplace_back(start, size, last_tag); return true; } bool UntreatedParts::RowGetPart(off_t& start, off_t& size, off_t max_size, off_t min_size, bool lastpart) const { if(max_size <= 0 || min_size < 0 || max_size < min_size){ S3FS_PRN_ERR("Parameter are wrong(max_size=%lld, min_size=%lld).", static_cast<long long int>(max_size), static_cast<long long int>(min_size)); return false; } const std::lock_guard<std::mutex> lock(untreated_list_lock); // Check the overlap with the existing part and add the part. for(auto iter = untreated_list.cbegin(); iter != untreated_list.cend(); ++iter){ if(!lastpart || iter->untreated_tag == last_tag){ if(min_size <= iter->size){ if(iter->size <= max_size){ // whole part( min <= part size <= max ) start = iter->start; size = iter->size; }else{ // Partially take out part( max < part size ) start = iter->start; size = max_size; } return true; }else{ if(lastpart){ return false; } } } } return false; } // [NOTE] // If size is specified as 0, all areas(parts) after start will be deleted. // bool UntreatedParts::ClearParts(off_t start, off_t size) { if(start < 0 || size < 0){ S3FS_PRN_ERR("Parameter are wrong(start=%lld, size=%lld).", static_cast<long long int>(start), static_cast<long long int>(size)); return false; } const std::lock_guard<std::mutex> lock(untreated_list_lock); if(untreated_list.empty()){ return true; } // Check the overlap with the existing part. for(auto iter = untreated_list.begin(); iter != untreated_list.end(); ){ if(0 != size && (start + size) <= iter->start){ // clear area is in front of iter area, no more to do. break; }else if(start <= iter->start){ if(0 != size && (start + size) <= (iter->start + iter->size)){ // clear area overlaps with iter area(on the start side) iter->size = (iter->start + iter->size) - (start + size); iter->start = start + size; if(0 == iter->size){ iter = untreated_list.erase(iter); } }else{ // clear area overlaps with all of iter area iter = untreated_list.erase(iter); } }else if(start < (iter->start + iter->size)){ // clear area overlaps with iter area(on the end side) if(0 == size || (iter->start + iter->size) <= (start + size)){ // start to iter->end is clear iter->size = start - iter->start; }else{ // parse current part iter->size = start - iter->start; // add new part off_t next_start = start + size; off_t next_size = (iter->start + iter->size) - (start + size); long next_tag = iter->untreated_tag; ++iter; iter = untreated_list.insert(iter, untreatedpart(next_start, next_size, next_tag)); ++iter; } }else{ // clear area is in behind of iter area ++iter; } } return true; } // // Update the last updated Untreated part // bool UntreatedParts::GetLastUpdatePart(off_t& start, off_t& size) const { const std::lock_guard<std::mutex> lock(untreated_list_lock); for(auto iter = untreated_list.cbegin(); iter != untreated_list.cend(); ++iter){ if(iter->untreated_tag == last_tag){ start = iter->start; size = iter->size; return true; } } return false; } // // Replaces the last updated Untreated part. // // [NOTE] // If size <= 0, delete that part // bool UntreatedParts::ReplaceLastUpdatePart(off_t start, off_t size) { const std::lock_guard<std::mutex> lock(untreated_list_lock); for(auto iter = untreated_list.begin(); iter != untreated_list.end(); ++iter){ if(iter->untreated_tag == last_tag){ if(0 < size){ iter->start = start; iter->size = size; }else{ untreated_list.erase(iter); } return true; } } return false; } // // Remove the last updated Untreated part. // bool UntreatedParts::RemoveLastUpdatePart() { const std::lock_guard<std::mutex> lock(untreated_list_lock); for(auto iter = untreated_list.begin(); iter != untreated_list.end(); ++iter){ if(iter->untreated_tag == last_tag){ untreated_list.erase(iter); return true; } } return false; } // // Duplicate the internally untreated_list. // bool UntreatedParts::Duplicate(untreated_list_t& list) { const std::lock_guard<std::mutex> lock(untreated_list_lock); list = untreated_list; return true; } void UntreatedParts::Dump() { const std::lock_guard<std::mutex> lock(untreated_list_lock); S3FS_PRN_DBG("untreated list = ["); for(auto iter = untreated_list.cbegin(); iter != untreated_list.cend(); ++iter){ S3FS_PRN_DBG(" {%014lld - %014lld : tag=%ld}", static_cast<long long int>(iter->start), static_cast<long long int>(iter->size), iter->untreated_tag); } S3FS_PRN_DBG("]"); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
8,463
C++
.cpp
225
29.866667
160
0.582664
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,437
s3fs_threadreqs.cpp
s3fs-fuse_s3fs-fuse/src/s3fs_threadreqs.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 "common.h" #include "s3fs.h" #include "s3fs_threadreqs.h" #include "threadpoolman.h" #include "curl_util.h" #include "s3fs_logger.h" #include "s3fs_util.h" #include "cache.h" #include "string_util.h" //------------------------------------------------------------------- // Thread Worker functions for MultiThread Request //------------------------------------------------------------------- // // Thread Worker function for head request // void* head_req_threadworker(void* arg) { auto* pthparam = static_cast<head_req_thparam*>(arg); if(!pthparam || !pthparam->pmeta){ return reinterpret_cast<void*>(-EIO); } S3FS_PRN_INFO3("Head Request [path=%s][pmeta=%p]", pthparam->path.c_str(), pthparam->pmeta); S3fsCurl s3fscurl; pthparam->result = s3fscurl.HeadRequest(pthparam->path.c_str(), *(pthparam->pmeta)); return reinterpret_cast<void*>(pthparam->result); } // // Thread Worker function for multi head request // void* multi_head_req_threadworker(void* arg) { std::unique_ptr<multi_head_req_thparam> pthparam(static_cast<multi_head_req_thparam*>(arg)); if(!pthparam || !pthparam->psyncfiller || !pthparam->pthparam_lock || !pthparam->pretrycount || !pthparam->pnotfound_list || !pthparam->presult){ return reinterpret_cast<void*>(-EIO); } // Check retry max count and print debug message { const std::lock_guard<std::mutex> lock(*(pthparam->pthparam_lock)); S3FS_PRN_INFO3("Multi Head Request [filler=%p][thparam_lock=%p][retrycount=%d][notfound_list=%p][wtf8=%s][path=%s]", pthparam->psyncfiller, pthparam->pthparam_lock, *(pthparam->pretrycount), pthparam->pnotfound_list, pthparam->use_wtf8 ? "true" : "false", pthparam->path.c_str()); if(S3fsCurl::GetRetries() < *(pthparam->pretrycount)){ S3FS_PRN_ERR("Head request(%s) reached the maximum number of retry count(%d).", pthparam->path.c_str(), *(pthparam->pretrycount)); return reinterpret_cast<void*>(-EIO); } } // loop for head request S3fsCurl s3fscurl; int result = 0; headers_t meta; // this value is not used while(true){ // Request result = s3fscurl.HeadRequest(pthparam->path.c_str(), meta); // Check result bool isResetOffset= true; CURLcode curlCode = s3fscurl.GetCurlCode(); long responseCode = S3fsCurl::S3FSCURL_RESPONSECODE_NOTSET; s3fscurl.GetResponseCode(responseCode, false); if(CURLE_OK == curlCode){ if(responseCode < 400){ // add into stat cache if(StatCache::getStatCacheData()->AddStat(pthparam->path, *(s3fscurl.GetResponseHeaders()))){ // Get stats from stats cache(for converting from meta), and fill std::string bpath = mybasename(pthparam->path); if(pthparam->use_wtf8){ bpath = s3fs_wtf8_decode(bpath); } struct stat st; if(StatCache::getStatCacheData()->GetStat(pthparam->path, &st)){ pthparam->psyncfiller->Fill(bpath, &st, 0); }else{ S3FS_PRN_INFO2("Could not find %s file in stat cache.", pthparam->path.c_str()); pthparam->psyncfiller->Fill(bpath, nullptr, 0); } result = 0; }else{ S3FS_PRN_ERR("failed adding stat cache [path=%s]", pthparam->path.c_str()); if(0 == result){ result = -EIO; } } break; }else if(responseCode == 400){ // as possibly in multipart S3FS_PRN_WARN("Head Request(%s) got 400 response code.", pthparam->path.c_str()); }else if(responseCode == 404){ // set path to not found list S3FS_PRN_INFO("Head Request(%s) got NotFound(404), it maybe only the path exists and the object does not exist.", pthparam->path.c_str()); { const std::lock_guard<std::mutex> lock(*(pthparam->pthparam_lock)); pthparam->pnotfound_list->push_back(pthparam->path); } break; }else if(responseCode == 500){ // 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("Head Request(%s) got 500 response code.", pthparam->path.c_str()); // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse }else if(responseCode == S3fsCurl::S3FSCURL_RESPONSECODE_NOTSET){ // This is a case where the processing result has not yet been updated (should be very rare). S3FS_PRN_WARN("Head Request(%s) could not get any response code.", pthparam->path.c_str()); }else{ // including S3fsCurl::S3FSCURL_RESPONSECODE_FATAL_ERROR // Retry in other case. S3FS_PRN_WARN("Head Request(%s) got fatal response code.", pthparam->path.c_str()); } }else if(CURLE_OPERATION_TIMEDOUT == curlCode){ S3FS_PRN_ERR("Head Request(%s) is timeouted.", pthparam->path.c_str()); isResetOffset= false; }else if(CURLE_PARTIAL_FILE == curlCode){ S3FS_PRN_WARN("Head Request(%s) is recieved data does not match the given size.", pthparam->path.c_str()); isResetOffset= false; }else{ S3FS_PRN_WARN("Head Request(%s) got the result code(%d: %s)", pthparam->path.c_str(), curlCode, curl_easy_strerror(curlCode)); } // Check retry max count { const std::lock_guard<std::mutex> lock(*(pthparam->pthparam_lock)); ++(*(pthparam->pretrycount)); if(S3fsCurl::GetRetries() < *(pthparam->pretrycount)){ S3FS_PRN_ERR("Head request(%s) reached the maximum number of retry count(%d).", pthparam->path.c_str(), *(pthparam->pretrycount)); if(0 == result){ result = -EIO; } break; } } // Setup for retry if(isResetOffset){ S3fsCurl::ResetOffset(&s3fscurl); } } // Set result code { const std::lock_guard<std::mutex> lock(*(pthparam->pthparam_lock)); if(0 == *(pthparam->presult) && 0 != result){ // keep first error *(pthparam->presult) = result; } } // [NOTE] // The return value of a Multi Head request thread will always be 0(nullptr). // This is because the expected value of a Head request will always be a // response other than 200, such as 400/404/etc. // In those error cases, this function simply outputs a message. And those // errors(the first one) will be set to pthparam->presult and can be referenced // by the caller. // return nullptr; } // // Thread Worker function for delete request // void* delete_req_threadworker(void* arg) { auto* pthparam = static_cast<delete_req_thparam*>(arg); if(!pthparam){ return reinterpret_cast<void*>(-EIO); } S3FS_PRN_INFO3("Delete Request [path=%s]", pthparam->path.c_str()); S3fsCurl s3fscurl; pthparam->result = s3fscurl.DeleteRequest(pthparam->path.c_str()); return reinterpret_cast<void*>(pthparam->result); } // // Thread Worker function for put head request // void* put_head_req_threadworker(void* arg) { auto* pthparam = static_cast<put_head_req_thparam*>(arg); if(!pthparam){ return reinterpret_cast<void*>(-EIO); } S3FS_PRN_INFO3("Put Head Request [path=%s][meta count=%lu][is copy=%s]", pthparam->path.c_str(), pthparam->meta.size(), (pthparam->isCopy ? "true" : "false")); S3fsCurl s3fscurl(true); pthparam->result = s3fscurl.PutHeadRequest(pthparam->path.c_str(), pthparam->meta, pthparam->isCopy); return reinterpret_cast<void*>(pthparam->result); } // // Thread Worker function for put request // void* put_req_threadworker(void* arg) { auto* pthparam = static_cast<put_req_thparam*>(arg); if(!pthparam){ return reinterpret_cast<void*>(-EIO); } S3FS_PRN_INFO3("Put Request [path=%s][meta count=%lu][fd=%d][use_ahbe=%s]", pthparam->path.c_str(), pthparam->meta.size(), pthparam->fd, (pthparam->ahbe ? "true" : "false")); S3fsCurl s3fscurl(pthparam->ahbe); pthparam->result = s3fscurl.PutRequest(pthparam->path.c_str(), pthparam->meta, pthparam->fd); return reinterpret_cast<void*>(pthparam->result); } // // Thread Worker function for list bucket request // void* list_bucket_req_threadworker(void* arg) { auto* pthparam = static_cast<list_bucket_req_thparam*>(arg); if(!pthparam || !(pthparam->presponseBody)){ return reinterpret_cast<void*>(-EIO); } S3FS_PRN_INFO3("List Bucket Request [path=%s][query=%s]", pthparam->path.c_str(), pthparam->query.c_str()); S3fsCurl s3fscurl; if(0 == (pthparam->result = s3fscurl.ListBucketRequest(pthparam->path.c_str(), pthparam->query.c_str()))){ *(pthparam->presponseBody) = s3fscurl.GetBodyData(); } return reinterpret_cast<void*>(pthparam->result); } // // Thread Worker function for check service request // void* check_service_req_threadworker(void* arg) { auto* pthparam = static_cast<check_service_req_thparam*>(arg); if(!pthparam || !(pthparam->presponseCode) || !(pthparam->presponseBody)){ return reinterpret_cast<void*>(-EIO); } S3FS_PRN_INFO3("Check Service Request [path=%s][support compat dir=%s][force No SSE=%s]", pthparam->path.c_str(), (pthparam->support_compat_dir ? "true" : "false"), (pthparam->forceNoSSE ? "true" : "false")); S3fsCurl s3fscurl; if(0 == (pthparam->result = s3fscurl.CheckBucket(pthparam->path.c_str(), pthparam->support_compat_dir, pthparam->forceNoSSE))){ *(pthparam->presponseCode) = s3fscurl.GetLastResponseCode(); *(pthparam->presponseBody) = s3fscurl.GetBodyData(); } return reinterpret_cast<void*>(pthparam->result); } // // Worker function for pre multipart upload request // void* pre_multipart_upload_req_threadworker(void* arg) { auto* pthparam = static_cast<pre_multipart_upload_req_thparam*>(arg); if(!pthparam){ return reinterpret_cast<void*>(-EIO); } S3FS_PRN_INFO3("Pre Multipart Upload Request [path=%s][meta count=%lu]", pthparam->path.c_str(), pthparam->meta.size()); S3fsCurl s3fscurl(true); pthparam->result = s3fscurl.PreMultipartUploadRequest(pthparam->path.c_str(), pthparam->meta, pthparam->upload_id); return reinterpret_cast<void*>(pthparam->result); } // // Worker function for complete multipart upload request // void* complete_multipart_upload_threadworker(void* arg) { auto* pthparam = static_cast<complete_multipart_upload_req_thparam*>(arg); if(!pthparam){ return reinterpret_cast<void*>(-EIO); } S3FS_PRN_INFO3("Complete Multipart Upload Request [path=%s][upload id=%s][etaglist=%lu]", pthparam->path.c_str(), pthparam->upload_id.c_str(), pthparam->etaglist.size()); S3fsCurl s3fscurl(true); pthparam->result = s3fscurl.MultipartUploadComplete(pthparam->path.c_str(), pthparam->upload_id, pthparam->etaglist); return reinterpret_cast<void*>(pthparam->result); } // // Worker function for abort multipart upload request // void* abort_multipart_upload_req_threadworker(void* arg) { auto* pthparam = static_cast<abort_multipart_upload_req_thparam*>(arg); if(!pthparam){ return reinterpret_cast<void*>(-EIO); } S3FS_PRN_INFO3("Abort Multipart Upload Request [path=%s][upload id=%s]", pthparam->path.c_str(), pthparam->upload_id.c_str()); S3fsCurl s3fscurl(true); pthparam->result = s3fscurl.AbortMultipartUpload(pthparam->path.c_str(), pthparam->upload_id); return reinterpret_cast<void*>(pthparam->result); } // // Thread Worker function for get object request // void* get_object_req_threadworker(void* arg) { auto* pthparam = static_cast<get_object_req_thparam*>(arg); if(!pthparam){ return reinterpret_cast<void*>(-EIO); } S3FS_PRN_INFO3("Get Object Request [path=%s][fd=%d][start=%lld][size=%lld]", pthparam->path.c_str(), pthparam->fd, static_cast<long long>(pthparam->start), static_cast<long long>(pthparam->size)); sse_type_t ssetype = sse_type_t::SSE_DISABLE; std::string ssevalue; if(!get_object_sse_type(pthparam->path.c_str(), ssetype, ssevalue)){ S3FS_PRN_WARN("Failed to get SSE type for file(%s).", pthparam->path.c_str()); } S3fsCurl s3fscurl; pthparam->result = s3fscurl.GetObjectRequest(pthparam->path.c_str(), pthparam->fd, pthparam->start, pthparam->size, ssetype, ssevalue); return reinterpret_cast<void*>(pthparam->result); } //------------------------------------------------------------------- // Utility functions //------------------------------------------------------------------- // // Calls S3fsCurl::HeadRequest via head_req_threadworker // int head_request(const std::string& strpath, headers_t& header) { // parameter for thread worker head_req_thparam thargs; thargs.path = strpath; thargs.pmeta = &header; thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = head_req_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Await Head Request Thread Worker [path=%s]", strpath.c_str()); return -EIO; } if(0 != thargs.result){ S3FS_PRN_DBG("Await Head Request by error(%d) [path=%s]", thargs.result, strpath.c_str()); return thargs.result; } return 0; } // // Calls S3fsCurl::DeleteRequest via delete_req_threadworker // int delete_request(const std::string& strpath) { // parameter for thread worker delete_req_thparam thargs; thargs.path = strpath; thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = delete_req_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Await Delete Request Thread Worker [path=%s]", strpath.c_str()); return -EIO; } if(0 != thargs.result){ S3FS_PRN_DBG("Await Delete Request by error(%d) [path=%s]", thargs.result, strpath.c_str()); return thargs.result; } return 0; } // // Calls S3fsCurl::PutHeadRequest via put_head_req_threadworker // int put_head_request(const std::string& strpath, const headers_t& meta, bool is_copy) { // parameter for thread worker put_head_req_thparam thargs; thargs.path = strpath; thargs.meta = meta; // copy thargs.isCopy = is_copy; thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = put_head_req_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Await Put Head Request Thread Worker [path=%s][meta count=%lu][is copy=%s]", strpath.c_str(), meta.size(), (is_copy ? "true" : "false")); return -EIO; } if(0 != thargs.result){ S3FS_PRN_ERR("Await Put Head Request by error(%d) [path=%s][meta count=%lu][is copy=%s]", thargs.result, strpath.c_str(), meta.size(), (is_copy ? "true" : "false")); return thargs.result; } return 0; } // // Calls S3fsCurl::PutRequest via put_req_threadworker // int put_request(const std::string& strpath, const headers_t& meta, int fd, bool ahbe) { // parameter for thread worker put_req_thparam thargs; thargs.path = strpath; thargs.meta = meta; // copy thargs.fd = fd; // fd=-1 means for creating zero byte object. thargs.ahbe = ahbe; thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = put_req_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Await Put Request Thread Worker [path=%s][meta count=%lu][fd=%d][use_ahbe=%s]", strpath.c_str(), meta.size(), fd, (ahbe ? "true" : "false")); return -EIO; } if(0 != thargs.result){ S3FS_PRN_ERR("Await Put Request by error(%d) [path=%s][meta count=%lu][fd=%d][use_ahbe=%s]", thargs.result, strpath.c_str(), meta.size(), fd, (ahbe ? "true" : "false")); return thargs.result; } return 0; } // // Calls S3fsCurl::ListBucketRequest via list_bucket_req_threadworker // int list_bucket_request(const std::string& strpath, const std::string& query, std::string& responseBody) { // parameter for thread worker list_bucket_req_thparam thargs; thargs.path = strpath; thargs.query = query; thargs.presponseBody = &responseBody; thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = list_bucket_req_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Await List Bucket Request Thread Worker [path=%s][query=%s]", strpath.c_str(), query.c_str()); return -EIO; } if(0 != thargs.result){ S3FS_PRN_ERR("Await List Bucket Request by error(%d) [path=%s][query=%s]", thargs.result, strpath.c_str(), query.c_str()); return thargs.result; } return 0; } // // Calls S3fsCurl::CheckBucket via check_service_req_threadworker // int check_service_request(const std::string& strpath, bool forceNoSSE, bool support_compat_dir, long& responseCode, std::string& responseBody) { // parameter for thread worker check_service_req_thparam thargs; thargs.path = strpath; thargs.forceNoSSE = forceNoSSE; thargs.support_compat_dir = support_compat_dir; thargs.presponseCode = &responseCode; thargs.presponseBody = &responseBody; thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = check_service_req_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Await Check Service Request Thread Worker [path=%s][support compat dir=%s][force No SSE=%s]", strpath.c_str(), (support_compat_dir ? "true" : "false"), (forceNoSSE ? "true" : "false")); return -EIO; } if(0 != thargs.result){ S3FS_PRN_ERR("Await Check Service Request by error(%d) [path=%s][support compat dir=%s][force No SSE=%s]", thargs.result, strpath.c_str(), (support_compat_dir ? "true" : "false"), (forceNoSSE ? "true" : "false")); return thargs.result; } return 0; } // // Calls S3fsCurl::PreMultipartUploadRequest via pre_multipart_upload_req_threadworker // // [NOTE] // If the request is successful, sets upload_id. // int pre_multipart_upload_request(const std::string& path, const headers_t& meta, std::string& upload_id) { // parameter for thread worker pre_multipart_upload_req_thparam thargs; thargs.path = path; thargs.meta = meta; // copy thargs.upload_id.clear(); // clear thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = pre_multipart_upload_req_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Pre Multipart Upload Request Thread Worker"); return -EIO; } if(0 != thargs.result){ S3FS_PRN_ERR("Pre Multipart Upload Request(path=%s) returns with error(%d)", path.c_str(), thargs.result); return thargs.result; } // set upload_id upload_id = thargs.upload_id; return 0; } // // Calls S3fsCurl::MultipartUploadComplete via complete_multipart_upload_threadworker // int complete_multipart_upload_request(const std::string& path, const std::string& upload_id, const etaglist_t& parts) { // parameter for thread worker complete_multipart_upload_req_thparam thargs; thargs.path = path; thargs.upload_id = upload_id; thargs.etaglist = parts; // copy thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = complete_multipart_upload_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Complete Multipart Upload Request Thread Worker"); return -EIO; } if(0 != thargs.result){ S3FS_PRN_ERR("Complete Multipart Upload Request(path=%s) returns with error(%d)", path.c_str(), thargs.result); return thargs.result; } return 0; } // // Calls S3fsCurl::AbortMultipartUpload via abort_multipart_upload_req_threadworker // int abort_multipart_upload_request(const std::string& path, const std::string& upload_id) { // parameter for thread worker abort_multipart_upload_req_thparam thargs; thargs.path = path; thargs.upload_id = upload_id; thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = abort_multipart_upload_req_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Abort Multipart Upload Request Thread Worker"); return -EIO; } if(0 != thargs.result){ S3FS_PRN_ERR("Abort Multipart Upload Request(path=%s) returns with error(%d)", path.c_str(), thargs.result); return thargs.result; } return 0; } // // Calls S3fsCurl::GetObjectRequest via get_object_req_threadworker // int get_object_request(const std::string& path, int fd, off_t start, off_t size) { // parameter for thread worker get_object_req_thparam thargs; thargs.path = path; thargs.fd = fd; thargs.start = start; thargs.size = size; thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = get_object_req_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Await Get Object Request Thread Worker [path=%s][fd=%d][start=%lld][size=%lld]", path.c_str(), fd, static_cast<long long int>(start), static_cast<long long int>(size)); return -EIO; } if(0 != thargs.result){ S3FS_PRN_ERR("Await Get Object Request by error(%d) [path=%s][fd=%d][start=%lld][size=%lld]", thargs.result, path.c_str(), fd, static_cast<long long int>(start), static_cast<long long int>(size)); return thargs.result; } return 0; } //------------------------------------------------------------------- // Direct Call Utility Functions //------------------------------------------------------------------- // These functions (mainly IAM token-related) are not called from // a thread. // // [NOTE] // The request for IAM token calls are called from S3fsCurl::RequestPerform // method if the IAM token needs to be updated during each request // processing. (NOTE: Each request is already executed in a thread.) // If the number of threads has reached the limit when these functions // are called, they will block until a thread that can execute this // process is found. // This may result in all processing being blocked. // Therefore, the following functions(IAM token requests) will not be // processed by a thread worker, but will process the request directly. // // If it is a different request called from within a thread worker, // please process it like this. // // // Directly calls S3fsCurl::GetIAMv2ApiToken // int get_iamv2api_token_request(const std::string& strurl, int tokenttl, const std::string& strttlhdr, std::string& token) { S3FS_PRN_INFO3("Get IAMv2 API Toekn Request directly [url=%s][token ttl=%d][ttl header=%s]", strurl.c_str(), tokenttl, strttlhdr.c_str()); S3fsCurl s3fscurl; return s3fscurl.GetIAMv2ApiToken(strurl.c_str(), tokenttl, strttlhdr.c_str(), token); } // // Directly calls S3fsCurl::GetIAMRoleFromMetaData // int get_iamrole_request(const std::string& strurl, const std::string& striamtoken, std::string& token) { S3FS_PRN_INFO3("Get IAM Role Request directly [url=%s][iam token=%s]", strurl.c_str(), striamtoken.c_str()); S3fsCurl s3fscurl; int result = 0; if(!s3fscurl.GetIAMRoleFromMetaData(strurl.c_str(), (striamtoken.empty() ? nullptr : striamtoken.c_str()), token)){ S3FS_PRN_ERR("Something error occurred during getting IAM Role from MetaData."); result = -EIO; } return result; } // // Directly calls S3fsCurl::GetIAMCredentials // int get_iamcred_request(const std::string& strurl, const std::string& striamtoken, const std::string& stribmsecret, std::string& cred) { S3FS_PRN_INFO3("Get IAM Credentials Request directly [url=%s][iam token=%s][ibm secrect access key=%s]", strurl.c_str(), striamtoken.c_str(), stribmsecret.c_str()); S3fsCurl s3fscurl; int result = 0; if(!s3fscurl.GetIAMCredentials(strurl.c_str(), (striamtoken.empty() ? nullptr : striamtoken.c_str()), (stribmsecret.empty() ? nullptr : stribmsecret.c_str()), cred)){ S3FS_PRN_ERR("Something error occurred during getting IAM Credentials."); result = -EIO; } return result; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
27,662
C++
.cpp
647
37.102009
288
0.647253
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,438
sighandlers.cpp
s3fs-fuse_s3fs-fuse/src/sighandlers.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <cstdio> #include <csignal> #include <thread> #include <utility> #include "psemaphore.h" #include "s3fs_logger.h" #include "sighandlers.h" #include "fdcache.h" //------------------------------------------------------------------- // Class S3fsSignals //------------------------------------------------------------------- std::unique_ptr<S3fsSignals> S3fsSignals::pSingleton; bool S3fsSignals::enableUsr1 = false; //------------------------------------------------------------------- // Class methods //------------------------------------------------------------------- bool S3fsSignals::Initialize() { if(!S3fsSignals::pSingleton){ S3fsSignals::pSingleton.reset(new S3fsSignals); } return true; } bool S3fsSignals::Destroy() { S3fsSignals::pSingleton.reset(); return true; } void S3fsSignals::HandlerUSR1(int sig) { if(SIGUSR1 != sig){ S3FS_PRN_ERR("The handler for SIGUSR1 received signal(%d)", sig); return; } S3fsSignals* pSigobj = S3fsSignals::get(); if(!pSigobj){ S3FS_PRN_ERR("S3fsSignals object is not initialized."); return; } if(!pSigobj->WakeupUsr1Thread()){ S3FS_PRN_ERR("Failed to wakeup the thread for SIGUSR1."); return; } } bool S3fsSignals::SetUsr1Handler(const char* path) { if(!FdManager::HaveLseekHole()){ S3FS_PRN_ERR("Could not set SIGUSR1 for checking cache, because this system does not support SEEK_DATA/SEEK_HOLE in lseek function."); return false; } // set output file if(!FdManager::SetCacheCheckOutput(path)){ S3FS_PRN_ERR("Could not set output file(%s) for checking cache.", path ? path : "null(stdout)"); return false; } S3fsSignals::enableUsr1 = true; return true; } void S3fsSignals::CheckCacheWorker(Semaphore* pSem) { if(!pSem){ return; } if(!S3fsSignals::enableUsr1){ return; } // wait and loop while(S3fsSignals::enableUsr1){ // wait pSem->acquire(); // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(!S3fsSignals::enableUsr1){ break; // asap } // check all cache if(!FdManager::get()->CheckAllCache()){ S3FS_PRN_ERR("Processing failed due to some problem."); } // do not allow request queuing while(pSem->try_acquire()); } } void S3fsSignals::HandlerUSR2(int sig) { if(SIGUSR2 == sig){ S3fsLog::BumpupLogLevel(); }else{ S3FS_PRN_ERR("The handler for SIGUSR2 received signal(%d)", sig); } } bool S3fsSignals::InitUsr2Handler() { struct sigaction sa{}; sa.sa_handler = S3fsSignals::HandlerUSR2; sa.sa_flags = SA_RESTART; if(0 != sigaction(SIGUSR2, &sa, nullptr)){ return false; } return true; } void S3fsSignals::HandlerHUP(int sig) { if(SIGHUP == sig){ S3fsLog::ReopenLogfile(); }else{ S3FS_PRN_ERR("The handler for SIGHUP received signal(%d)", sig); } } bool S3fsSignals::InitHupHandler() { struct sigaction sa{}; sa.sa_handler = S3fsSignals::HandlerHUP; sa.sa_flags = SA_RESTART; if(0 != sigaction(SIGHUP, &sa, nullptr)){ return false; } return true; } //------------------------------------------------------------------- // Methods //------------------------------------------------------------------- S3fsSignals::S3fsSignals() { if(S3fsSignals::enableUsr1){ if(!InitUsr1Handler()){ S3FS_PRN_ERR("failed creating thread for SIGUSR1 handler, but continue..."); } } if(!S3fsSignals::InitUsr2Handler()){ S3FS_PRN_ERR("failed to initialize SIGUSR2 handler for bumping log level, but continue..."); } if(!S3fsSignals::InitHupHandler()){ S3FS_PRN_ERR("failed to initialize SIGHUP handler for reopen log file, but continue..."); } } S3fsSignals::~S3fsSignals() { if(S3fsSignals::enableUsr1){ if(!DestroyUsr1Handler()){ S3FS_PRN_ERR("failed stopping thread for SIGUSR1 handler, but continue..."); } } } bool S3fsSignals::InitUsr1Handler() { if(pThreadUsr1 || pSemUsr1){ S3FS_PRN_ERR("Already run thread for SIGUSR1"); return false; } // create thread std::unique_ptr<Semaphore> pSemUsr1_tmp(new Semaphore(0)); pThreadUsr1.reset(new std::thread(S3fsSignals::CheckCacheWorker, pSemUsr1_tmp.get())); pSemUsr1 = std::move(pSemUsr1_tmp); // set handler struct sigaction sa{}; sa.sa_handler = S3fsSignals::HandlerUSR1; sa.sa_flags = SA_RESTART; if(0 != sigaction(SIGUSR1, &sa, nullptr)){ S3FS_PRN_ERR("Could not set signal handler for SIGUSR1"); DestroyUsr1Handler(); return false; } return true; } bool S3fsSignals::DestroyUsr1Handler() { if(!pThreadUsr1 || !pSemUsr1){ return false; } // for thread exit S3fsSignals::enableUsr1 = false; // wakeup thread pSemUsr1->release(); // wait for thread exiting pThreadUsr1->join(); pSemUsr1.reset(); pThreadUsr1.reset(); return true; } bool S3fsSignals::WakeupUsr1Thread() { if(!pThreadUsr1 || !pSemUsr1){ S3FS_PRN_ERR("The thread for SIGUSR1 is not setup."); return false; } pSemUsr1->release(); return true; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
6,376
C++
.cpp
216
24.949074
142
0.620369
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,439
s3fs_util.cpp
s3fs-fuse_s3fs-fuse/src/s3fs_util.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <cstdio> #include <cstdlib> #include <unistd.h> #include <cerrno> #include <grp.h> #include <memory> #include <mutex> #include <pwd.h> #include <libgen.h> #include <dirent.h> #include <sys/stat.h> #include <sys/utsname.h> #include <string> #include <sstream> #include "s3fs_logger.h" #include "s3fs_util.h" #include "string_util.h" #include "s3fs_help.h" //------------------------------------------------------------------- // Global variables //------------------------------------------------------------------- std::string mount_prefix; static size_t max_password_size; static size_t max_group_name_length; //------------------------------------------------------------------- // Utilities //------------------------------------------------------------------- std::string get_realpath(const char *path) { std::string realpath = mount_prefix; realpath += path; return realpath; } void init_sysconf_vars() { // SUSv4tc1 says the following about _SC_GETGR_R_SIZE_MAX and // _SC_GETPW_R_SIZE_MAX: // Note that sysconf(_SC_GETGR_R_SIZE_MAX) may return -1 if // there is no hard limit on the size of the buffer needed to // store all the groups returned. errno = 0; long res = sysconf(_SC_GETPW_R_SIZE_MAX); if(0 > res){ if (errno != 0){ S3FS_PRN_ERR("could not get max password length."); abort(); } res = 1024; // default initial length } max_password_size = res; errno = 0; res = sysconf(_SC_GETGR_R_SIZE_MAX); if(0 > res) { if (errno != 0) { S3FS_PRN_ERR("could not get max group name length."); abort(); } res = 1024; // default initial length } max_group_name_length = res; } //------------------------------------------------------------------- // Utility for UID/GID //------------------------------------------------------------------- // get user name from uid std::string get_username(uid_t uid) { size_t maxlen = max_password_size; int result; struct passwd pwinfo; struct passwd* ppwinfo = nullptr; // make buffer std::unique_ptr<char[]> pbuf(new char[maxlen]); // get pw information while(ERANGE == (result = getpwuid_r(uid, &pwinfo, pbuf.get(), maxlen, &ppwinfo))){ maxlen *= 2; pbuf.reset(new char[maxlen]); } if(0 != result){ S3FS_PRN_ERR("could not get pw information(%d).", result); return ""; } // check pw if(nullptr == ppwinfo){ return ""; } std::string name = SAFESTRPTR(ppwinfo->pw_name); return name; } int is_uid_include_group(uid_t uid, gid_t gid) { size_t maxlen = max_group_name_length; int result; struct group ginfo; struct group* pginfo = nullptr; // make buffer std::unique_ptr<char[]> pbuf(new char[maxlen]); // get group information while(ERANGE == (result = getgrgid_r(gid, &ginfo, pbuf.get(), maxlen, &pginfo))){ maxlen *= 2; pbuf.reset(new char[maxlen]); } if(0 != result){ S3FS_PRN_ERR("could not get group information(%d).", result); return -result; } // check group if(nullptr == pginfo){ // there is not gid in group. return -EINVAL; } std::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. return 1; } } return 0; } //------------------------------------------------------------------- // Utility for file and directory //------------------------------------------------------------------- // [NOTE] // basename/dirname returns a static variable pointer as the return value. // Normally this shouldn't be a problem, but in macos10 we found a case // where dirname didn't receive its return value correctly due to thread // conflicts. // To avoid this, exclusive control is performed by mutex. // static std::mutex basename_lock; std::string mydirname(const std::string& path) { const std::lock_guard<std::mutex> lock(basename_lock); return mydirname(path.c_str()); } // safe variant of dirname // dirname clobbers path so let it operate on a tmp copy std::string mydirname(const char* path) { if(!path || '\0' == path[0]){ return ""; } char *buf = strdup(path); std::string result = dirname(buf); free(buf); return result; } std::string mybasename(const std::string& path) { const std::lock_guard<std::mutex> data_lock(basename_lock); return mybasename(path.c_str()); } // safe variant of basename // basename clobbers path so let it operate on a tmp copy std::string mybasename(const char* path) { if(!path || '\0' == path[0]){ return ""; } char *buf = strdup(path); std::string result = basename(buf); free(buf); return result; } // mkdir --parents int mkdirp(const std::string& path, mode_t mode) { std::string base; std::string component; std::istringstream 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) && errno != EEXIST){ return errno; } } } return 0; } // get existed directory path std::string get_exist_directory_path(const std::string& path) { std::string existed("/"); // "/" is existed. std::string base; std::string component; std::istringstream ss(path); while (getline(ss, component, '/')) { if(base != "/"){ base += "/"; } base += component; struct stat st; if(0 == stat(base.c_str(), &st) && S_ISDIR(st.st_mode)){ existed = base; }else{ break; } } return existed; } 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 exist return true; } if(EACCES == errno){ // could not access directory return false; } // something error occurred 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_include_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(nullptr == (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; } std::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 for system information //------------------------------------------------------------------- bool compare_sysname(const char* target) { // [NOTE] // The buffer size of sysname member in struct utsname is // OS dependent, but 512 bytes is sufficient for now. // static const char* psysname = nullptr; static char sysname[512]; if(!psysname){ struct utsname sysinfo; if(0 != uname(&sysinfo)){ S3FS_PRN_ERR("could not initialize system name to internal buffer(errno:%d), thus use \"Linux\".", errno); strcpy(sysname, "Linux"); }else{ S3FS_PRN_INFO("system name is %s", sysinfo.sysname); sysname[sizeof(sysname) - 1] = '\0'; strncpy(sysname, sysinfo.sysname, sizeof(sysname) - 1); } psysname = &sysname[0]; } if(!target || 0 != strcmp(psysname, target)){ return false; } return true; } //------------------------------------------------------------------- // Utility for print message at launching //------------------------------------------------------------------- void print_launch_message(int argc, char** argv) { std::string message = short_version(); if(argv){ message += " :"; for(int cnt = 0; cnt < argc; ++cnt){ if(argv[cnt]){ message += " "; if(0 == cnt){ message += basename(argv[cnt]); }else{ message += argv[cnt]; } } } } S3FS_PRN_LAUNCH_INFO("%s", message.c_str()); } // // result: -1 ts1 < ts2 // 0 ts1 == ts2 // 1 ts1 > ts2 // int compare_timespec(const struct timespec& ts1, const struct timespec& ts2) { if(ts1.tv_sec < ts2.tv_sec){ return -1; }else if(ts1.tv_sec > ts2.tv_sec){ return 1; }else{ if(ts1.tv_nsec < ts2.tv_nsec){ return -1; }else if(ts1.tv_nsec > ts2.tv_nsec){ return 1; } } return 0; } // // result: -1 st < ts // 0 st == ts // 1 st > ts // int compare_timespec(const struct stat& st, stat_time_type type, const struct timespec& ts) { struct timespec st_ts; set_stat_to_timespec(st, type, st_ts); return compare_timespec(st_ts, ts); } void set_timespec_to_stat(struct stat& st, stat_time_type type, const struct timespec& ts) { if(stat_time_type::ATIME == type){ #if defined(__APPLE__) st.st_atime = ts.tv_sec; st.st_atimespec.tv_nsec = ts.tv_nsec; #else st.st_atim.tv_sec = ts.tv_sec; st.st_atim.tv_nsec = ts.tv_nsec; #endif }else if(stat_time_type::MTIME == type){ #if defined(__APPLE__) st.st_mtime = ts.tv_sec; st.st_mtimespec.tv_nsec = ts.tv_nsec; #else st.st_mtim.tv_sec = ts.tv_sec; st.st_mtim.tv_nsec = ts.tv_nsec; #endif }else if(stat_time_type::CTIME == type){ #if defined(__APPLE__) st.st_ctime = ts.tv_sec; st.st_ctimespec.tv_nsec = ts.tv_nsec; #else st.st_ctim.tv_sec = ts.tv_sec; st.st_ctim.tv_nsec = ts.tv_nsec; #endif }else{ S3FS_PRN_ERR("unknown type(%d), so skip to set value.", static_cast<int>(type)); } } struct timespec* set_stat_to_timespec(const struct stat& st, stat_time_type type, struct timespec& ts) { if(stat_time_type::ATIME == type){ #if defined(__APPLE__) ts.tv_sec = st.st_atime; ts.tv_nsec = st.st_atimespec.tv_nsec; #else ts = st.st_atim; #endif }else if(stat_time_type::MTIME == type){ #if defined(__APPLE__) ts.tv_sec = st.st_mtime; ts.tv_nsec = st.st_mtimespec.tv_nsec; #else ts = st.st_mtim; #endif }else if(stat_time_type::CTIME == type){ #if defined(__APPLE__) ts.tv_sec = st.st_ctime; ts.tv_nsec = st.st_ctimespec.tv_nsec; #else ts = st.st_ctim; #endif }else{ S3FS_PRN_ERR("unknown type(%d), so use 0 as timespec.", static_cast<int>(type)); ts.tv_sec = 0; ts.tv_nsec = 0; } return &ts; } std::string str_stat_time(const struct stat& st, stat_time_type type) { struct timespec ts; return str(*set_stat_to_timespec(st, type, ts)); } struct timespec* s3fs_realtime(struct timespec& ts) { if(-1 == clock_gettime(static_cast<clockid_t>(CLOCK_REALTIME), &ts)){ S3FS_PRN_WARN("failed to clock_gettime by errno(%d)", errno); ts.tv_sec = time(nullptr); ts.tv_nsec = 0; } return &ts; } std::string s3fs_str_realtime() { struct timespec ts; return str(*s3fs_realtime(ts)); } int s3fs_fclose(FILE* fp) { if(fp == nullptr){ return 0; } return fclose(fp); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
14,681
C++
.cpp
487
24.057495
118
0.535502
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,440
addhead.cpp
s3fs-fuse_s3fs-fuse/src/addhead.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <cstdio> #include <cstdlib> #include <cstring> #include <sstream> #include <fstream> #include <string> #include <strings.h> #include <utility> #include <vector> #include "s3fs.h" #include "addhead.h" #include "curl_util.h" #include "s3fs_logger.h" //------------------------------------------------------------------- // Symbols //------------------------------------------------------------------- static constexpr char ADD_HEAD_REGEX[] = "reg:"; //------------------------------------------------------------------- // Class AdditionalHeader //------------------------------------------------------------------- AdditionalHeader AdditionalHeader::singleton; //------------------------------------------------------------------- // Class AdditionalHeader method //------------------------------------------------------------------- AdditionalHeader::AdditionalHeader() { if(this == AdditionalHeader::get()){ is_enable = false; }else{ abort(); } } AdditionalHeader::~AdditionalHeader() { if(this == AdditionalHeader::get()){ Unload(); }else{ abort(); } } bool AdditionalHeader::Load(const char* file) { if(!file){ S3FS_PRN_WARN("file is nullptr."); return false; } Unload(); std::ifstream AH(file); if(!AH.good()){ S3FS_PRN_WARN("Could not open file(%s).", file); return false; } // read file std::string line; while(getline(AH, line)){ if(line.empty()){ continue; } if('#' == line[0]){ continue; } // load a line std::istringstream ss(line); std::string key; // suffix(key) std::string head; // additional HTTP header std::string value; // header value if(0 == isblank(line[0])){ ss >> key; } if(ss){ ss >> head; if(ss && static_cast<size_t>(ss.tellg()) < line.size()){ value = line.substr(static_cast<int>(ss.tellg()) + 1); } } // check it if(head.empty()){ if(key.empty()){ continue; } S3FS_PRN_ERR("file format error: %s key(suffix) is no HTTP header value.", key.c_str()); Unload(); return false; } if(0 == strncasecmp(key.c_str(), ADD_HEAD_REGEX, strlen(ADD_HEAD_REGEX))){ // regex if(key.size() <= strlen(ADD_HEAD_REGEX)){ S3FS_PRN_ERR("file format error: %s key(suffix) does not have key std::string.", key.c_str()); continue; } key.erase(0, strlen(ADD_HEAD_REGEX)); // compile RegexPtr preg(new regex_t, regfree); int result; if(0 != (result = regcomp(preg.get(), key.c_str(), REG_EXTENDED | REG_NOSUB))){ // we do not need matching info char errbuf[256]; regerror(result, preg.get(), errbuf, sizeof(errbuf)); S3FS_PRN_ERR("failed to compile regex from %s key by %s.", key.c_str(), errbuf); continue; } addheadlist.emplace_back(std::move(preg), key, head, value); }else{ // not regex, directly comparing addheadlist.emplace_back(RegexPtr(nullptr, regfree), key, head, value); } // set flag is_enable = true; } return true; } void AdditionalHeader::Unload() { is_enable = false; addheadlist.clear(); } bool AdditionalHeader::AddHeader(headers_t& meta, const char* path) const { if(!is_enable){ return true; } if(!path){ S3FS_PRN_WARN("path is nullptr."); return false; } size_t pathlength = strlen(path); // loop // // [NOTE] // Because to allow duplicate key, and then scanning the entire table. // for(auto iter = addheadlist.cbegin(); iter != addheadlist.cend(); ++iter){ const add_header *paddhead = &*iter; if(paddhead->pregex){ // regex regmatch_t match; // not use if(0 == regexec(paddhead->pregex.get(), path, 1, &match, 0)){ // match -> adding header meta[paddhead->headkey] = paddhead->headvalue; } }else{ // directly comparing if(paddhead->basestring.length() < pathlength){ if(paddhead->basestring.empty() || paddhead->basestring == &path[pathlength - paddhead->basestring.length()]){ // match -> adding header meta[paddhead->headkey] = paddhead->headvalue; } } } } 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(auto iter = meta.cbegin(); iter != meta.cend(); ++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() const { if(!S3fsLog::IsS3fsLogDbg()){ return true; } std::ostringstream ssdbg; int cnt = 1; ssdbg << "Additional Header list[" << addheadlist.size() << "] = {" << std::endl; for(auto iter = addheadlist.cbegin(); iter != addheadlist.cend(); ++iter, ++cnt){ const add_header *paddhead = &*iter; ssdbg << " [" << cnt << "] = {" << std::endl; if(paddhead->pregex){ ssdbg << " type\t\t--->\tregex" << std::endl; }else{ ssdbg << " type\t\t--->\tsuffix matching" << std::endl; } ssdbg << " base std::string\t--->\t" << paddhead->basestring << std::endl; ssdbg << " add header\t--->\t" << paddhead->headkey << ": " << paddhead->headvalue << std::endl; ssdbg << " }" << std::endl; } ssdbg << "}" << std::endl; // print all S3FS_PRN_DBG("%s", ssdbg.str().c_str()); return true; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
7,189
C++
.cpp
217
26.345622
126
0.532786
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,441
s3fs_global.cpp
s3fs-fuse_s3fs-fuse/src/s3fs_global.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <string> #include "common.h" //------------------------------------------------------------------- // Global variables //------------------------------------------------------------------- bool foreground = false; bool nomultipart = false; bool pathrequeststyle = false; bool complement_stat = false; bool noxmlns = false; std::string program_name; std::string service_path = "/"; std::string s3host = "https://s3.amazonaws.com"; std::string endpoint = "us-east-1"; std::string cipher_suites; std::string instance_name; /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
1,627
C++
.cpp
43
36.325581
82
0.63038
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
18,443
fdcache_entity.cpp
s3fs-fuse_s3fs-fuse/src/fdcache_entity.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <cerrno> #include <cstdio> #include <cstdlib> #include <climits> #include <cstring> #include <memory> #include <mutex> #include <string> #include <sys/stat.h> #include <unistd.h> #include <utility> #include "common.h" #include "s3fs.h" #include "fdcache_entity.h" #include "fdcache_fdinfo.h" #include "fdcache_stat.h" #include "fdcache_untreated.h" #include "fdcache.h" #include "string_util.h" #include "s3fs_logger.h" #include "s3fs_util.h" #include "curl.h" #include "curl_util.h" #include "s3fs_cred.h" #include "threadpoolman.h" #include "s3fs_threadreqs.h" //------------------------------------------------ // Symbols //------------------------------------------------ static constexpr int MAX_MULTIPART_CNT = 10 * 1000; // S3 multipart max count //------------------------------------------------ // Structure of parameters to pass to thread //------------------------------------------------ // // Multipart Upload Request parameter structure for Thread Pool. // // ([TODO] This is a temporary structure is moved when S3fsMultiCurl is deprecated.) // struct multipart_upload_req_thparam { std::string path; std::string upload_id; int fd = -1; off_t start = 0; off_t size = 0; etagpair* petagpair = nullptr; int result = 0; }; //------------------------------------------------ // FdEntity class variables //------------------------------------------------ bool FdEntity::mixmultipart = true; bool FdEntity::streamupload = false; //------------------------------------------------ // FdEntity class methods //------------------------------------------------ bool FdEntity::SetNoMixMultipart() { bool old = mixmultipart; mixmultipart = false; return old; } bool FdEntity::SetStreamUpload(bool isstream) { bool old = streamupload; streamupload = isstream; return old; } int FdEntity::FillFile(int fd, unsigned char byte, off_t size, off_t start) { unsigned char bytes[1024 * 32]; // 32kb memset(bytes, byte, std::min(static_cast<off_t>(sizeof(bytes)), size)); for(off_t total = 0, onewrote = 0; total < size; total += onewrote){ if(-1 == (onewrote = pwrite(fd, bytes, std::min(static_cast<off_t>(sizeof(bytes)), size - total), start + total))){ S3FS_PRN_ERR("pwrite failed. errno(%d)", errno); return -errno; } } return 0; } // [NOTE] // If fd is wrong or something error is occurred, return 0. // The ino_t is allowed zero, but inode 0 is not realistic. // So this method returns 0 on error assuming the correct // inode is never 0. // The caller must have exclusive control. // ino_t FdEntity::GetInode(int fd) { if(-1 == fd){ S3FS_PRN_ERR("file descriptor is wrong."); return 0; } struct stat st; if(0 != fstat(fd, &st)){ S3FS_PRN_ERR("could not get stat for physical file descriptor(%d) by errno(%d).", fd, errno); return 0; } return st.st_ino; } // // Worker function for multipart upload request // // ([TODO] This is a temporary structure is moved when S3fsMultiCurl is deprecated.) // void* FdEntity::MultipartUploadThreadWorker(void* arg) { auto* pthparam = static_cast<multipart_upload_req_thparam*>(arg); if(!pthparam){ return reinterpret_cast<void*>(-EIO); } S3FS_PRN_INFO3("Multipart Upload Request [path=%s][upload id=%s][fd=%d][start=%lld][size=%lld][etagpair=%p]", pthparam->path.c_str(), pthparam->upload_id.c_str(), pthparam->fd, static_cast<long long>(pthparam->start), static_cast<long long>(pthparam->size), pthparam->petagpair); S3fsCurl s3fscurl(true); pthparam->result = s3fscurl.MultipartUploadRequest(pthparam->upload_id, pthparam->path.c_str(), pthparam->fd, pthparam->start, pthparam->size, pthparam->petagpair); return reinterpret_cast<void*>(pthparam->result); } //------------------------------------------------ // FdEntity methods //------------------------------------------------ FdEntity::FdEntity(const char* tpath, const char* cpath) : path(SAFESTRPTR(tpath)), physical_fd(-1), inode(0), size_orgmeta(0), cachepath(SAFESTRPTR(cpath)), pending_status(pending_status_t::NO_UPDATE_PENDING) { holding_mtime.tv_sec = -1; holding_mtime.tv_nsec = 0; } FdEntity::~FdEntity() { Clear(); } void FdEntity::Clear() { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> data_lock(fdent_data_lock); pseudo_fd_map.clear(); if(-1 != physical_fd){ if(!cachepath.empty()){ // [NOTE] // Compare the inode of the existing cache file with the inode of // the cache file output by this object, and if they are the same, // serialize the pagelist. // ino_t cur_inode = GetInode(); if(0 != cur_inode && cur_inode == inode){ CacheFileStat cfstat(path.c_str()); if(!pagelist.Serialize(cfstat, inode)){ S3FS_PRN_WARN("failed to save cache stat file(%s).", path.c_str()); } } } pfile.reset(); physical_fd = -1; inode = 0; if(!mirrorpath.empty()){ if(-1 == unlink(mirrorpath.c_str())){ S3FS_PRN_WARN("failed to remove mirror cache file(%s) by errno(%d).", mirrorpath.c_str(), errno); } mirrorpath.clear(); } } pagelist.Init(0, false, false); path = ""; cachepath = ""; } // [NOTE] // This method returns the inode of the file in cachepath. // The return value is the same as the class method GetInode(). // The caller must have exclusive control. // ino_t FdEntity::GetInode() const { if(cachepath.empty()){ S3FS_PRN_INFO("cache file path is empty, then return inode as 0."); return 0; } struct stat st; if(0 != stat(cachepath.c_str(), &st)){ S3FS_PRN_INFO("could not get stat for file(%s) by errno(%d).", cachepath.c_str(), errno); return 0; } return st.st_ino; } void FdEntity::Close(int fd) { const std::lock_guard<std::mutex> lock(fdent_lock); S3FS_PRN_DBG("[path=%s][pseudo_fd=%d][physical_fd=%d]", path.c_str(), fd, physical_fd); // search pseudo fd and close it. auto iter = pseudo_fd_map.find(fd); if(pseudo_fd_map.cend() != iter){ pseudo_fd_map.erase(iter); }else{ S3FS_PRN_WARN("Not found pseudo_fd(%d) in entity object(%s)", fd, path.c_str()); } // check pseudo fd count if(-1 != physical_fd && 0 == GetOpenCountHasLock()){ const std::lock_guard<std::mutex> data_lock(fdent_data_lock); if(!cachepath.empty()){ // [NOTE] // Compare the inode of the existing cache file with the inode of // the cache file output by this object, and if they are the same, // serialize the pagelist. // ino_t cur_inode = GetInode(); if(0 != cur_inode && cur_inode == inode){ CacheFileStat cfstat(path.c_str()); if(!pagelist.Serialize(cfstat, inode)){ S3FS_PRN_WARN("failed to save cache stat file(%s).", path.c_str()); } } } pfile.reset(); physical_fd = -1; inode = 0; if(!mirrorpath.empty()){ if(-1 == unlink(mirrorpath.c_str())){ S3FS_PRN_WARN("failed to remove mirror cache file(%s) by errno(%d).", mirrorpath.c_str(), errno); } mirrorpath.clear(); } } } int FdEntity::DupWithLock(int fd) { S3FS_PRN_DBG("[path=%s][pseudo_fd=%d][physical_fd=%d][pseudo fd count=%zu]", path.c_str(), fd, physical_fd, pseudo_fd_map.size()); if(-1 == physical_fd){ return -1; } auto iter = pseudo_fd_map.find(fd); if(pseudo_fd_map.cend() == iter){ S3FS_PRN_ERR("Not found pseudo_fd(%d) in entity object(%s) for physical_fd(%d)", fd, path.c_str(), physical_fd); return -1; } const PseudoFdInfo* org_pseudoinfo = iter->second.get(); std::unique_ptr<PseudoFdInfo> ppseudoinfo(new PseudoFdInfo(physical_fd, (org_pseudoinfo ? org_pseudoinfo->GetFlags() : 0))); int pseudo_fd = ppseudoinfo->GetPseudoFd(); pseudo_fd_map[pseudo_fd] = std::move(ppseudoinfo); return pseudo_fd; } int FdEntity::OpenPseudoFd(int flags) { const std::lock_guard<std::mutex> lock(fdent_lock); S3FS_PRN_DBG("[path=%s][physical_fd=%d][pseudo fd count=%zu]", path.c_str(), physical_fd, pseudo_fd_map.size()); if(-1 == physical_fd){ return -1; } std::unique_ptr<PseudoFdInfo> ppseudoinfo(new PseudoFdInfo(physical_fd, flags)); int pseudo_fd = ppseudoinfo->GetPseudoFd(); pseudo_fd_map[pseudo_fd] = std::move(ppseudoinfo); return pseudo_fd; } int FdEntity::GetOpenCountHasLock() const { return static_cast<int>(pseudo_fd_map.size()); } // // Open mirror file which is linked cache file. // int FdEntity::OpenMirrorFile() { if(cachepath.empty()){ S3FS_PRN_ERR("cache path is empty, why come here"); return -EIO; } // make temporary directory std::string bupdir; if(!FdManager::MakeCachePath(nullptr, bupdir, true, true)){ S3FS_PRN_ERR("could not make bup cache directory path or create it."); return -EIO; } // create seed generating mirror file name auto seed = static_cast<unsigned int>(time(nullptr)); int urandom_fd; if(-1 != (urandom_fd = open("/dev/urandom", O_RDONLY))){ unsigned int rand_data; if(sizeof(rand_data) == read(urandom_fd, &rand_data, sizeof(rand_data))){ seed ^= rand_data; } close(urandom_fd); } // try to link mirror file while(true){ // make random(temp) file path // (do not care for threading, because allowed any value returned.) // char szfile[NAME_MAX + 1]; snprintf(szfile, sizeof(szfile), "%x.tmp", rand_r(&seed)); szfile[NAME_MAX] = '\0'; // for safety mirrorpath = bupdir + "/" + szfile; // link mirror file to cache file if(0 == link(cachepath.c_str(), mirrorpath.c_str())){ break; } if(EEXIST != errno){ S3FS_PRN_ERR("could not link mirror file(%s) to cache file(%s) by errno(%d).", mirrorpath.c_str(), cachepath.c_str(), errno); return -errno; } ++seed; } // open mirror file int mirrorfd; if(-1 == (mirrorfd = open(mirrorpath.c_str(), O_RDWR))){ S3FS_PRN_ERR("could not open mirror file(%s) by errno(%d).", mirrorpath.c_str(), errno); return -errno; } return mirrorfd; } bool FdEntity::FindPseudoFdWithLock(int fd) const { if(-1 == fd){ return false; } if(pseudo_fd_map.cend() == pseudo_fd_map.find(fd)){ return false; } return true; } PseudoFdInfo* FdEntity::CheckPseudoFdFlags(int fd, bool writable) { if(-1 == fd){ return nullptr; } auto iter = pseudo_fd_map.find(fd); if(pseudo_fd_map.cend() == iter || nullptr == iter->second){ return nullptr; } if(writable){ if(!iter->second->Writable()){ return nullptr; } }else{ if(!iter->second->Readable()){ return nullptr; } } return iter->second.get(); } bool FdEntity::IsUploading() { for(auto iter = pseudo_fd_map.cbegin(); iter != pseudo_fd_map.cend(); ++iter){ const PseudoFdInfo* ppseudoinfo = iter->second.get(); if(ppseudoinfo && ppseudoinfo->IsUploading()){ return true; } } return false; } // [NOTE] // If the open is successful, returns pseudo fd. // If it fails, it returns an error code with a negative value. // // ts_mctime argument is a variable for mtime/ctime. // If you want to disable this variable, specify UTIME_OMIT for // tv_nsec in timespec member(in this case tv_sec member is ignored). // This is similar to utimens operation. // You can use "S3FS_OMIT_TS" global variable for UTIME_OMIT. // int FdEntity::Open(const headers_t* pmeta, off_t size, const struct timespec& ts_mctime, int flags) { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> data_lock(fdent_data_lock); S3FS_PRN_DBG("[path=%s][physical_fd=%d][size=%lld][ts_mctime=%s][flags=0x%x]", path.c_str(), physical_fd, static_cast<long long>(size), str(ts_mctime).c_str(), flags); // [NOTE] // When the file size is incremental by truncating, it must be keeped // as an untreated area, and this area is set to these variables. // off_t truncated_start = 0; off_t truncated_size = 0; if(-1 != physical_fd){ // // already open file // // check only file size(do not need to save cfs and time. if(0 <= size && pagelist.Size() != size){ // truncate temporary file size if(-1 == ftruncate(physical_fd, size) || -1 == fsync(physical_fd)){ S3FS_PRN_ERR("failed to truncate temporary file(physical_fd=%d) by errno(%d).", physical_fd, errno); return -errno; } // resize page list if(!pagelist.Resize(size, false, true)){ // Areas with increased size are modified S3FS_PRN_ERR("failed to truncate temporary file information(physical_fd=%d).", physical_fd); return -EIO; } } // set untreated area if(0 <= size && size_orgmeta < size){ // set untreated area truncated_start = size_orgmeta; truncated_size = size - size_orgmeta; } // set original headers and set size. off_t new_size = (0 <= size ? size : size_orgmeta); if(pmeta){ orgmeta = *pmeta; size_orgmeta = get_size(orgmeta); } size_orgmeta = std::min(new_size, size_orgmeta); }else{ // // file is not opened yet // bool need_save_csf = false; // need to save(reset) cache stat file bool is_truncate = false; // need to truncate std::unique_ptr<CacheFileStat> pcfstat; if(!cachepath.empty()){ // using cache struct stat st; if(stat(cachepath.c_str(), &st) == 0){ if(0 > compare_timespec(st, stat_time_type::MTIME, ts_mctime)){ S3FS_PRN_DBG("cache file stale, removing: %s", cachepath.c_str()); if(unlink(cachepath.c_str()) != 0){ return (0 == errno ? -EIO : -errno); } } } // open cache and cache stat file, load page info. pcfstat.reset(new CacheFileStat(path.c_str())); // try to open cache file if( -1 != (physical_fd = open(cachepath.c_str(), O_RDWR)) && 0 != (inode = FdEntity::GetInode(physical_fd)) && pagelist.Deserialize(*pcfstat, inode)) { // succeed to open cache file and to load stats data st = {}; if(-1 == fstat(physical_fd, &st)){ S3FS_PRN_ERR("fstat is failed. errno(%d)", errno); physical_fd = -1; inode = 0; return (0 == errno ? -EIO : -errno); } // check size, st_size, loading stat file if(-1 == size){ if(st.st_size != pagelist.Size()){ pagelist.Resize(st.st_size, false, true); // Areas with increased size are modified need_save_csf = true; // need to update page info } size = st.st_size; }else{ // First if the current cache file size and pagelist do not match, fix pagelist. if(st.st_size != pagelist.Size()){ pagelist.Resize(st.st_size, false, true); // Areas with increased size are modified need_save_csf = true; // need to update page info } if(size != pagelist.Size()){ pagelist.Resize(size, false, true); // Areas with increased size are modified need_save_csf = true; // need to update page info } if(size != st.st_size){ is_truncate = true; } } }else{ if(-1 != physical_fd){ close(physical_fd); } inode = 0; // could not open cache file or could not load stats data, so initialize it. if(-1 == (physical_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); // remove cache stat file if it is existed int result; if(0 != (result = CacheFileStat::DeleteCacheFileStat(path.c_str()))){ if(-ENOENT != result){ S3FS_PRN_WARN("failed to delete current cache stat file(%s) by errno(%d), but continue...", path.c_str(), result); } } return result; } need_save_csf = true; // need to update page info inode = FdEntity::GetInode(physical_fd); if(-1 == size){ size = 0; pagelist.Init(0, false, false); }else{ // [NOTE] // The modify flag must not be set when opening a file, // if the ts_mctime parameter(mtime) is specified(tv_nsec != UTIME_OMIT) // and the cache file does not exist. // If mtime is specified for the file and the cache file // mtime is older than it, the cache file is removed and // the processing comes here. // pagelist.Resize(size, false, (UTIME_OMIT == ts_mctime.tv_nsec ? true : false)); is_truncate = true; } } // open mirror file int mirrorfd; if(0 >= (mirrorfd = OpenMirrorFile())){ S3FS_PRN_ERR("failed to open mirror file linked cache file(%s).", cachepath.c_str()); return (0 == mirrorfd ? -EIO : mirrorfd); } // switch fd close(physical_fd); physical_fd = mirrorfd; // make file pointer(for being same tmpfile) if(nullptr == (pfile = {fdopen(physical_fd, "wb"), &s3fs_fclose})){ int saved_errno = errno; S3FS_PRN_ERR("failed to get fileno(%s). errno(%d)", cachepath.c_str(), errno); close(physical_fd); errno = saved_errno; physical_fd = -1; inode = 0; return (0 == errno ? -EIO : -errno); } }else{ // not using cache inode = 0; // open temporary file auto tmpfile = FdManager::MakeTempFile(); if(nullptr == tmpfile || -1 ==(physical_fd = fileno(tmpfile.get()))){ S3FS_PRN_ERR("failed to open temporary file by errno(%d)", errno); return (0 == errno ? -EIO : -errno); } pfile = std::move(tmpfile); if(-1 == size){ size = 0; pagelist.Init(0, false, false); }else{ // [NOTE] // The modify flag must not be set when opening a file, // if the ts_mctime parameter(mtime) is specified(tv_nsec != UTIME_OMIT) // and the cache file does not exist. // If mtime is specified for the file and the cache file // mtime is older than it, the cache file is removed and // the processing comes here. // pagelist.Resize(size, false, (UTIME_OMIT == ts_mctime.tv_nsec ? true : false)); is_truncate = true; } } // truncate cache(tmp) file if(is_truncate){ if(0 != ftruncate(physical_fd, size) || 0 != fsync(physical_fd)){ S3FS_PRN_ERR("ftruncate(%s) or fsync returned err(%d)", cachepath.c_str(), errno); pfile.reset(); physical_fd = -1; inode = 0; return (0 == errno ? -EIO : -errno); } } // reset cache stat file if(need_save_csf && pcfstat.get()){ if(!pagelist.Serialize(*pcfstat, inode)){ S3FS_PRN_WARN("failed to save cache stat file(%s), but continue...", path.c_str()); } } // set original headers and size in it. if(pmeta){ orgmeta = *pmeta; size_orgmeta = get_size(orgmeta); }else{ orgmeta.clear(); size_orgmeta = 0; } // set untreated area if(0 <= size && size_orgmeta < size){ truncated_start = size_orgmeta; truncated_size = size - size_orgmeta; } // set mtime and ctime(set "x-amz-meta-mtime" and "x-amz-meta-ctime" in orgmeta) if(UTIME_OMIT != ts_mctime.tv_nsec){ if(0 != SetMCtimeHasLock(ts_mctime, ts_mctime)){ S3FS_PRN_ERR("failed to set mtime/ctime. errno(%d)", errno); pfile.reset(); physical_fd = -1; inode = 0; return (0 == errno ? -EIO : -errno); } } } // create new pseudo fd, and set it to map std::unique_ptr<PseudoFdInfo> ppseudoinfo(new PseudoFdInfo(physical_fd, flags)); int pseudo_fd = ppseudoinfo->GetPseudoFd(); pseudo_fd_map[pseudo_fd] = std::move(ppseudoinfo); // if there is untreated area, set it to pseudo object. if(0 < truncated_size){ if(!AddUntreated(truncated_start, truncated_size)){ pseudo_fd_map.erase(pseudo_fd); pfile.reset(); } } return pseudo_fd; } // [NOTE] // This method is called for only nocopyapi functions. // So we do not check disk space for this option mode, if there is no enough // disk space this method will be failed. // bool FdEntity::LoadAll(int fd, off_t* size, bool force_load) { const std::lock_guard<std::mutex> lock(fdent_lock); S3FS_PRN_INFO3("[path=%s][pseudo_fd=%d][physical_fd=%d]", path.c_str(), fd, physical_fd); if(-1 == physical_fd || !FindPseudoFdWithLock(fd)){ S3FS_PRN_ERR("pseudo_fd(%d) and physical_fd(%d) for path(%s) is not opened yet", fd, physical_fd, path.c_str()); return false; } const std::lock_guard<std::mutex> data_lock(fdent_data_lock); if(force_load){ SetAllStatusUnloaded(); } // // TODO: possibly do background for delay loading // int result; if(0 != (result = Load(/*start=*/ 0, /*size=*/ 0))){ S3FS_PRN_ERR("could not download, result(%d)", result); return false; } if(size){ *size = pagelist.Size(); } return true; } // // Rename file path. // // This method sets the FdManager::fent map registration key to fentmapkey. // // [NOTE] // This method changes the file path of FdEntity. // Old file is deleted after linking to the new file path, and this works // without problem because the file descriptor is not affected even if the // cache file is open. // The mirror file descriptor is also the same. The mirror file path does // not need to be changed and will remain as it is. // bool FdEntity::RenamePath(const std::string& newpath, std::string& fentmapkey) { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> data_lock(fdent_data_lock); if(!cachepath.empty()){ // has cache path // make new cache path std::string newcachepath; if(!FdManager::MakeCachePath(newpath.c_str(), newcachepath, true)){ S3FS_PRN_ERR("failed to make cache path for object(%s).", newpath.c_str()); return false; } // rename cache file if(-1 == rename(cachepath.c_str(), newcachepath.c_str())){ S3FS_PRN_ERR("failed to rename old cache path(%s) to new cache path(%s) by errno(%d).", cachepath.c_str(), newcachepath.c_str(), errno); return false; } // link and unlink cache file stat if(!CacheFileStat::RenameCacheFileStat(path.c_str(), newpath.c_str())){ S3FS_PRN_ERR("failed to rename cache file stat(%s to %s).", path.c_str(), newpath.c_str()); return false; } fentmapkey = newpath; cachepath = newcachepath; }else{ // does not have cache path fentmapkey.clear(); FdManager::MakeRandomTempPath(newpath.c_str(), fentmapkey); } // set new path path = newpath; return true; } bool FdEntity::IsModified() const { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> data_lock(fdent_data_lock); return pagelist.IsModified(); } bool FdEntity::GetStatsHasLock(struct stat& st) const { if(-1 == physical_fd){ return false; } st = {}; if(-1 == fstat(physical_fd, &st)){ S3FS_PRN_ERR("fstat failed. errno(%d)", errno); return false; } return true; } int FdEntity::SetCtimeHasLock(struct timespec time) { S3FS_PRN_INFO3("[path=%s][physical_fd=%d][time=%s]", path.c_str(), physical_fd, str(time).c_str()); if(-1 == time.tv_sec){ return 0; } orgmeta["x-amz-meta-ctime"] = str(time); return 0; } int FdEntity::SetAtimeHasLock(struct timespec time) { S3FS_PRN_INFO3("[path=%s][physical_fd=%d][time=%s]", path.c_str(), physical_fd, str(time).c_str()); if(-1 == time.tv_sec){ return 0; } orgmeta["x-amz-meta-atime"] = str(time); return 0; } // [NOTE] // This method updates mtime as well as ctime. // int FdEntity::SetMCtimeHasLock(struct timespec mtime, struct timespec ctime) { S3FS_PRN_INFO3("[path=%s][physical_fd=%d][mtime=%s][ctime=%s]", path.c_str(), physical_fd, str(mtime).c_str(), str(ctime).c_str()); if(mtime.tv_sec < 0 || ctime.tv_sec < 0){ return 0; } if(-1 != physical_fd){ struct timespec ts[2]; ts[0].tv_sec = mtime.tv_sec; ts[0].tv_nsec = mtime.tv_nsec; ts[1].tv_sec = ctime.tv_sec; ts[1].tv_nsec = ctime.tv_nsec; if(-1 == futimens(physical_fd, ts)){ S3FS_PRN_ERR("futimens failed. errno(%d)", errno); return -errno; } }else if(!cachepath.empty()){ // not opened file yet. struct timespec ts[2]; ts[0].tv_sec = ctime.tv_sec; ts[0].tv_nsec = ctime.tv_nsec; ts[1].tv_sec = mtime.tv_sec; ts[1].tv_nsec = mtime.tv_nsec; if(-1 == utimensat(AT_FDCWD, cachepath.c_str(), ts, 0)){ S3FS_PRN_ERR("utimensat failed. errno(%d)", errno); return -errno; } } orgmeta["x-amz-meta-mtime"] = str(mtime); orgmeta["x-amz-meta-ctime"] = str(ctime); return 0; } bool FdEntity::UpdateCtime() { const std::lock_guard<std::mutex> lock(fdent_lock); struct stat st; if(!GetStatsHasLock(st)){ return false; } orgmeta["x-amz-meta-ctime"] = str_stat_time(st, stat_time_type::CTIME); return true; } bool FdEntity::UpdateAtime() { const std::lock_guard<std::mutex> lock(fdent_lock); struct stat st; if(!GetStatsHasLock(st)){ return false; } orgmeta["x-amz-meta-atime"] = str_stat_time(st, stat_time_type::ATIME); return true; } bool FdEntity::UpdateMtime(bool clear_holding_mtime) { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> data_lock(fdent_data_lock); if(0 <= holding_mtime.tv_sec){ // [NOTE] // This conditional statement is very special. // If you copy a file with "cp -p" etc., utimens or chown will be // called after opening the file, after that call to write, flush. // If normally utimens are not called(cases like "cp" only), mtime // should be updated at the file flush. // Here, check the holding_mtime value to prevent mtime from being // overwritten. // if(clear_holding_mtime){ if(!ClearHoldingMtime()){ return false; } // [NOTE] // If come here after fdatasync has been processed, the file // content update has already taken place. However, the metadata // update is necessary and needs to be flagged in order to // perform it with flush, // pending_status = pending_status_t::UPDATE_META_PENDING; } }else{ struct stat st; if(!GetStatsHasLock(st)){ return false; } orgmeta["x-amz-meta-mtime"] = str_stat_time(st, stat_time_type::MTIME); } return true; } bool FdEntity::SetHoldingMtime(struct timespec mtime) { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> data_lock(fdent_data_lock); S3FS_PRN_INFO3("[path=%s][physical_fd=%d][mtime=%s]", path.c_str(), physical_fd, str(mtime).c_str()); if(mtime.tv_sec < 0){ return false; } holding_mtime = mtime; return true; } bool FdEntity::ClearHoldingMtime() { if(holding_mtime.tv_sec < 0){ return false; } struct stat st; if(!GetStatsHasLock(st)){ return false; } if(-1 != physical_fd){ struct timespec ts[2]; struct timespec ts_ctime; ts[0].tv_sec = holding_mtime.tv_sec; ts[0].tv_nsec = holding_mtime.tv_nsec; set_stat_to_timespec(st, stat_time_type::CTIME, ts_ctime); ts[1].tv_sec = ts_ctime.tv_sec; ts[1].tv_nsec = ts_ctime.tv_nsec; if(-1 == futimens(physical_fd, ts)){ S3FS_PRN_ERR("futimens failed. errno(%d)", errno); return false; } }else if(!cachepath.empty()){ // not opened file yet. struct timespec ts[2]; struct timespec ts_ctime; set_stat_to_timespec(st, stat_time_type::CTIME, ts_ctime); ts[0].tv_sec = ts_ctime.tv_sec; ts[0].tv_nsec = ts_ctime.tv_nsec; ts[1].tv_sec = holding_mtime.tv_sec; ts[1].tv_nsec = holding_mtime.tv_nsec; if(-1 == utimensat(AT_FDCWD, cachepath.c_str(), ts, 0)){ S3FS_PRN_ERR("utimensat failed. errno(%d)", errno); return false; } } holding_mtime.tv_sec = -1; holding_mtime.tv_nsec = 0; return true; } bool FdEntity::GetSize(off_t& size) const { const std::lock_guard<std::mutex> lock(fdent_lock); if(-1 == physical_fd){ return false; } const std::lock_guard<std::mutex> data_lock(fdent_data_lock); size = pagelist.Size(); return true; } bool FdEntity::GetXattr(std::string& xattr) const { const std::lock_guard<std::mutex> lock(fdent_lock); auto iter = orgmeta.find("x-amz-meta-xattr"); if(iter == orgmeta.cend()){ return false; } xattr = iter->second; return true; } bool FdEntity::SetXattr(const std::string& xattr) { const std::lock_guard<std::mutex> lock(fdent_lock); orgmeta["x-amz-meta-xattr"] = xattr; return true; } bool FdEntity::SetModeHasLock(mode_t mode) { orgmeta["x-amz-meta-mode"] = std::to_string(mode); return true; } bool FdEntity::SetUIdHasLock(uid_t uid) { orgmeta["x-amz-meta-uid"] = std::to_string(uid); return true; } bool FdEntity::SetGIdHasLock(gid_t gid) { orgmeta["x-amz-meta-gid"] = std::to_string(gid); return true; } bool FdEntity::SetContentType(const char* path) { if(!path){ return false; } const std::lock_guard<std::mutex> lock(fdent_lock); orgmeta["Content-Type"] = S3fsCurl::LookupMimeType(path); return true; } bool FdEntity::SetAllStatus(bool is_loaded) { S3FS_PRN_INFO3("[path=%s][physical_fd=%d][%s]", path.c_str(), physical_fd, is_loaded ? "loaded" : "unloaded"); if(-1 == physical_fd){ return false; } // get file size struct stat st{}; if(-1 == fstat(physical_fd, &st)){ S3FS_PRN_ERR("fstat is failed. errno(%d)", errno); return false; } // Reinit pagelist.Init(st.st_size, is_loaded, false); return true; } int FdEntity::Load(off_t start, off_t size, bool is_modified_flag) { S3FS_PRN_DBG("[path=%s][physical_fd=%d][offset=%lld][size=%lld]", path.c_str(), physical_fd, static_cast<long long int>(start), static_cast<long long int>(size)); if(-1 == physical_fd){ return -EBADF; } int result = 0; // check loaded area & load fdpage_list_t unloaded_list; if(0 < pagelist.GetUnloadedPages(unloaded_list, start, size)){ for(auto iter = unloaded_list.cbegin(); iter != unloaded_list.cend(); ++iter){ if(0 != size && start + size <= iter->offset){ // reached end break; } // check loading size off_t need_load_size = 0; if(iter->offset < size_orgmeta){ // original file size(on S3) is smaller than request. need_load_size = (iter->next() <= size_orgmeta ? iter->bytes : (size_orgmeta - iter->offset)); } // download if(S3fsCurl::GetMultipartSize() <= need_load_size && !nomultipart){ // parallel request result = S3fsCurl::ParallelGetObjectRequest(path.c_str(), physical_fd, iter->offset, need_load_size); }else{ // single request if(0 < need_load_size){ result = get_object_request(path, physical_fd, iter->offset, need_load_size); }else{ result = 0; } } if(0 != result){ break; } // Set loaded flag pagelist.SetPageLoadedStatus(iter->offset, iter->bytes, (is_modified_flag ? PageList::page_status::LOAD_MODIFIED : PageList::page_status::LOADED)); } PageList::FreeList(unloaded_list); } return result; } // [NOTE] // At no disk space for caching object. // This method is downloading by dividing an object of the specified range // and uploading by multipart after finishing downloading it. // // [NOTICE] // Need to lock before calling this method. // int FdEntity::NoCacheLoadAndPost(PseudoFdInfo* pseudo_obj, off_t start, off_t size) { int result = 0; S3FS_PRN_INFO3("[path=%s][physical_fd=%d][offset=%lld][size=%lld]", path.c_str(), physical_fd, static_cast<long long int>(start), static_cast<long long int>(size)); if(!pseudo_obj){ S3FS_PRN_ERR("Pseudo object is nullptr."); return -EIO; } if(-1 == physical_fd){ return -EBADF; } // [NOTE] // This method calling means that the cache file is never used no more. // if(!cachepath.empty()){ // remove cache files(and cache stat file) FdManager::DeleteCacheFile(path.c_str()); // cache file path does not use no more. cachepath.clear(); mirrorpath.clear(); } // Change entity key in manager mapping FdManager::get()->ChangeEntityToTempPath(get_shared_ptr(), path.c_str()); // open temporary file int tmpfd; auto ptmpfp = FdManager::MakeTempFile(); if(nullptr == ptmpfp || -1 == (tmpfd = fileno(ptmpfp.get()))){ S3FS_PRN_ERR("failed to open temporary file by errno(%d)", errno); return (0 == errno ? -EIO : -errno); } // loop uploading by multipart for(auto iter = pagelist.pages.begin(); iter != pagelist.pages.end(); ++iter){ if(iter->end() < start){ continue; } if(0 != size && start + size <= iter->offset){ break; } // download each multipart size(default 10MB) in unit for(off_t oneread = 0, totalread = (iter->offset < start ? start : 0); totalread < iter->bytes; totalread += oneread){ int upload_fd = physical_fd; off_t offset = iter->offset + totalread; oneread = std::min(iter->bytes - totalread, S3fsCurl::GetMultipartSize()); // check rest size is over minimum part size // // [NOTE] // If the final part size is smaller than 5MB, it is not allowed by S3 API. // For this case, if the previous part of the final part is not over 5GB, // we incorporate the final part to the previous part. If the previous part // is over 5GB, we want to even out the last part and the previous part. // if((iter->bytes - totalread - oneread) < MIN_MULTIPART_SIZE){ if(FIVE_GB < iter->bytes - totalread){ oneread = (iter->bytes - totalread) / 2; }else{ oneread = iter->bytes - totalread; } } if(!iter->loaded){ // // loading or initializing // upload_fd = tmpfd; // load offset & size size_t need_load_size = 0; if(size_orgmeta <= offset){ // all area is over of original size need_load_size = 0; }else{ if(size_orgmeta < (offset + oneread)){ // original file size(on S3) is smaller than request. need_load_size = size_orgmeta - offset; }else{ need_load_size = oneread; } } size_t over_size = oneread - need_load_size; // [NOTE] // truncate file to zero and set length to part offset + size // after this, file length is (offset + size), but file does not use any disk space. // if(-1 == ftruncate(tmpfd, 0) || -1 == ftruncate(tmpfd, (offset + oneread))){ S3FS_PRN_ERR("failed to truncate temporary file(physical_fd=%d).", tmpfd); result = -EIO; break; } // single area get request if(0 < need_load_size){ if(0 != (result = get_object_request(path, tmpfd, offset, oneread))){ S3FS_PRN_ERR("failed to get object(start=%lld, size=%lld) for file(physical_fd=%d).", static_cast<long long int>(offset), static_cast<long long int>(oneread), tmpfd); break; } } // initialize fd without loading if(0 < over_size){ if(0 != (result = FdEntity::FillFile(tmpfd, 0, over_size, offset + need_load_size))){ S3FS_PRN_ERR("failed to fill rest bytes for physical_fd(%d). errno(%d)", tmpfd, result); break; } } }else{ // already loaded area } // single area upload by multipart upload if(0 != (result = NoCacheMultipartUploadRequest(pseudo_obj, upload_fd, offset, oneread))){ S3FS_PRN_ERR("failed to multipart upload(start=%lld, size=%lld) for file(physical_fd=%d).", static_cast<long long int>(offset), static_cast<long long int>(oneread), upload_fd); break; } } if(0 != result){ break; } // set loaded flag if(!iter->loaded){ if(iter->offset < start){ fdpage page(iter->offset, start - iter->offset, iter->loaded, false); iter->bytes -= (start - iter->offset); iter->offset = start; iter = pagelist.pages.insert(iter, page); } if(0 != size && start + size < iter->next()){ fdpage page(iter->offset, start + size - iter->offset, true, false); iter->bytes -= (start + size - iter->offset); iter->offset = start + size; iter = pagelist.pages.insert(iter, page); }else{ iter->loaded = true; iter->modified = false; } } } if(0 == result){ // compress pagelist pagelist.Compress(); // fd data do empty if(-1 == ftruncate(physical_fd, 0)){ S3FS_PRN_ERR("failed to truncate file(physical_fd=%d), but continue...", physical_fd); } } return result; } // // Common method that calls S3fsCurl::PreMultipartUploadRequest via pre_multipart_upload_request // // [NOTE] // If the request is successful, initialize upload_id. // int FdEntity::PreMultipartUploadRequest(PseudoFdInfo* pseudo_obj) { if(!pseudo_obj){ S3FS_PRN_ERR("Internal error, pseudo fd object pointer is null."); return -EIO; } // get upload_id std::string upload_id; int result; if(0 != (result = pre_multipart_upload_request(path, orgmeta, upload_id))){ return result; } // reset upload_id if(!pseudo_obj->InitialUploadInfo(upload_id)){ S3FS_PRN_ERR("failed to initialize upload id(%s)", upload_id.c_str()); return -EIO; } // Clear the dirty flag, because the meta data is updated. pending_status = pending_status_t::NO_UPDATE_PENDING; return 0; } // [NOTE] // At no disk space for caching object. // This method is starting multipart uploading. // int FdEntity::NoCachePreMultipartUploadRequest(PseudoFdInfo* pseudo_obj) { if(!pseudo_obj){ S3FS_PRN_ERR("Internal error, pseudo fd object pointer is null."); return -EIO; } // initialize multipart upload values pseudo_obj->ClearUploadInfo(true); int result; if(0 != (result = PreMultipartUploadRequest(pseudo_obj))){ return result; } return 0; } // [NOTE] // At no disk space for caching object. // This method is uploading one part of multipart. // // ([TODO] This is a temporary modification till S3fsMultiCurl is deprecated.) // int FdEntity::NoCacheMultipartUploadRequest(PseudoFdInfo* pseudo_obj, int tgfd, off_t start, off_t size) { if(-1 == tgfd || !pseudo_obj || !pseudo_obj->IsUploading()){ S3FS_PRN_ERR("Need to initialize for multipart upload."); return -EIO; } // parameter for thread worker multipart_upload_req_thparam thargs; thargs.path = path; thargs.upload_id.clear(); thargs.fd = tgfd; thargs.start = start; thargs.size = size; thargs.petagpair = nullptr; thargs.result = 0; // get upload id if(!pseudo_obj->GetUploadId(thargs.upload_id)){ return -EIO; } // append new part and get it's etag string pointer if(!pseudo_obj->AppendUploadPart(start, size, false, &(thargs.petagpair))){ return -EIO; } // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = FdEntity::MultipartUploadThreadWorker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Get Object Request Thread Worker"); return -EIO; } if(0 != thargs.result){ S3FS_PRN_ERR("Multipart Upload Request(path=%s, upload_id=%s, fd=%d, start=%lld, size=%lld) returns with error(%d)", path.c_str(), thargs.upload_id.c_str(), tgfd, static_cast<long long int>(start), static_cast<long long int>(size), thargs.result); return thargs.result; } return 0; } // [NOTE] // At no disk space for caching object. // This method is finishing multipart uploading. // int FdEntity::NoCacheMultipartUploadComplete(PseudoFdInfo* pseudo_obj) { // get upload id and etag list std::string upload_id; etaglist_t parts; if(!pseudo_obj->GetUploadId(upload_id) || !pseudo_obj->GetEtaglist(parts)){ return -EIO; } int result; if(0 != (result = complete_multipart_upload_request(path, upload_id, parts))){ S3FS_PRN_ERR("failed to complete multipart upload by errno(%d)", result); untreated_list.ClearAll(); pseudo_obj->ClearUploadInfo(); // clear multipart upload info int result2; if(0 != (result2 = abort_multipart_upload_request(path, upload_id))){ S3FS_PRN_ERR("failed to abort multipart upload by errno(%d)", result2); } return result; } // clear multipart upload info untreated_list.ClearAll(); pseudo_obj->ClearUploadInfo(); return 0; } off_t FdEntity::BytesModified() { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> data_lock(fdent_data_lock); return pagelist.BytesModified(); } // [NOTE] // There are conditions that allow you to perform multipart uploads. // // According to the AWS spec: // - 1 to 10,000 parts are allowed // - minimum size of parts is 5MB (except for the last part) // // For example, if you set the minimum part size to 5MB, you can upload // a maximum (5 * 10,000)MB file. // The part size can be changed in MB units, then the maximum file size // that can be handled can be further increased. // Files smaller than the minimum part size will not be multipart uploaded, // but will be uploaded as single part(normally). // int FdEntity::RowFlushHasLock(int fd, const char* tpath, bool force_sync) { S3FS_PRN_INFO3("[tpath=%s][path=%s][pseudo_fd=%d][physical_fd=%d]", SAFESTRPTR(tpath), path.c_str(), fd, physical_fd); if(-1 == physical_fd){ return -EBADF; } // check pseudo fd and its flag const auto miter = pseudo_fd_map.find(fd); if(pseudo_fd_map.cend() == miter || nullptr == miter->second){ return -EBADF; } if(!miter->second->Writable() && !(miter->second->GetFlags() & O_CREAT)){ // If the entity is opened read-only, it will end normally without updating. return 0; } PseudoFdInfo* pseudo_obj = miter->second.get(); int result; if(!force_sync && !pagelist.IsModified() && !IsDirtyMetadata()){ // nothing to update. return 0; } if(S3fsLog::IsS3fsLogDbg()){ pagelist.Dump(); } if(nomultipart){ // No multipart upload if(!force_sync && !pagelist.IsModified()){ // for only push pending headers result = UploadPendingHasLock(-1); }else{ result = RowFlushNoMultipart(pseudo_obj, tpath); } }else if(FdEntity::streamupload){ // Stream multipart upload result = RowFlushStreamMultipart(pseudo_obj, tpath); }else if(FdEntity::mixmultipart){ // Mix multipart upload result = RowFlushMixMultipart(pseudo_obj, tpath); }else{ // Normal multipart upload result = RowFlushMultipart(pseudo_obj, tpath); } // [NOTE] // if something went wrong, so if you are using a cache file, // the cache file may not be correct. So delete cache files. // if(0 != result && !cachepath.empty()){ FdManager::DeleteCacheFile(tpath); } return result; } // // ([TODO] This is a temporary modification till S3fsMultiCurl is deprecated.) // int FdEntity::RowFlushNoMultipart(const PseudoFdInfo* pseudo_obj, const char* tpath) { S3FS_PRN_INFO3("[tpath=%s][path=%s][pseudo_fd=%d][physical_fd=%d]", SAFESTRPTR(tpath), path.c_str(), (pseudo_obj ? pseudo_obj->GetPseudoFd() : -1), physical_fd); if(-1 == physical_fd || !pseudo_obj){ return -EBADF; } if(pseudo_obj->IsUploading()){ S3FS_PRN_ERR("Why uploading now, even though s3fs is No Multipart uploading mode."); return -EBADF; } // If there is no loading all of the area, loading all area. off_t restsize = pagelist.GetTotalUnloadedPageSize(); if(0 < restsize){ // check disk space if(!ReserveDiskSpace(restsize)){ // no enough disk space S3FS_PRN_WARN("Not enough local storage to flush: [path=%s][pseudo_fd=%d][physical_fd=%d]", (tpath ? tpath : path.c_str()), pseudo_obj->GetPseudoFd(), physical_fd); return -ENOSPC; // No space left on device } } FdManager::FreeReservedDiskSpace(restsize); // Always load all uninitialized area int result; if(0 != (result = Load(/*start=*/ 0, /*size=*/ 0))){ S3FS_PRN_ERR("failed to upload all area(errno=%d)", result); return result; } // check size if(pagelist.Size() > MAX_MULTIPART_CNT * S3fsCurl::GetMultipartSize()){ S3FS_PRN_ERR("Part count exceeds %d. Increase multipart size and try again.", MAX_MULTIPART_CNT); return -EFBIG; } // backup upload file size struct stat st{}; if(-1 == fstat(physical_fd, &st)){ S3FS_PRN_ERR("fstat is failed by errno(%d), but continue...", errno); } // parameter for thread worker put_req_thparam thargs; thargs.path = tpath ? tpath : path; thargs.meta = orgmeta; // copy thargs.fd = physical_fd; thargs.ahbe = true; thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = put_req_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Put Request for Thread Worker"); return -EIO; } if(0 != thargs.result){ // continue... S3FS_PRN_DBG("Put Request(%s) returns with errno(%d)", thargs.path.c_str(), thargs.result); } // reset uploaded file size size_orgmeta = st.st_size; untreated_list.ClearAll(); if(0 == thargs.result){ pagelist.ClearAllModified(); } return thargs.result; } // // ([TODO] This is a temporary modification till S3fsMultiCurl is deprecated.) // int FdEntity::RowFlushMultipart(PseudoFdInfo* pseudo_obj, const char* tpath) { S3FS_PRN_INFO3("[tpath=%s][path=%s][pseudo_fd=%d][physical_fd=%d]", SAFESTRPTR(tpath), path.c_str(), (pseudo_obj ? pseudo_obj->GetPseudoFd() : -1), physical_fd); if(-1 == physical_fd || !pseudo_obj){ return -EBADF; } int result = 0; if(!pseudo_obj->IsUploading()){ // Start uploading // If there is no loading all of the area, loading all area. off_t restsize = pagelist.GetTotalUnloadedPageSize(); // Check rest size and free disk space if(0 < restsize && !ReserveDiskSpace(restsize)){ // no enough disk space if(0 != (result = NoCachePreMultipartUploadRequest(pseudo_obj))){ S3FS_PRN_ERR("failed to switch multipart uploading with no cache(errno=%d)", result); return result; } // upload all by multipart uploading if(0 != (result = NoCacheLoadAndPost(pseudo_obj))){ S3FS_PRN_ERR("failed to upload all area by multipart uploading(errno=%d)", result); return result; } }else{ // enough disk space or no rest size std::string tmppath = path; headers_t tmporgmeta = orgmeta; FdManager::FreeReservedDiskSpace(restsize); // Load all uninitialized area(no mix multipart uploading) if(0 != (result = Load(/*start=*/ 0, /*size=*/ 0))){ S3FS_PRN_ERR("failed to upload all area(errno=%d)", result); return result; } // backup upload file size struct stat st{}; if(-1 == fstat(physical_fd, &st)){ S3FS_PRN_ERR("fstat is failed by errno(%d), but continue...", errno); } if(pagelist.Size() > MAX_MULTIPART_CNT * S3fsCurl::GetMultipartSize()){ S3FS_PRN_ERR("Part count exceeds %d. Increase multipart size and try again.", MAX_MULTIPART_CNT); return -EFBIG; }else if(pagelist.Size() >= S3fsCurl::GetMultipartSize()){ // multipart uploading result = S3fsCurl::ParallelMultipartUploadRequest(tpath ? tpath : tmppath.c_str(), tmporgmeta, physical_fd); }else{ // normal uploading (too small part size) // parameter for thread worker put_req_thparam thargs; thargs.path = tpath ? tpath : tmppath; thargs.meta = tmporgmeta; // copy thargs.fd = physical_fd; thargs.ahbe = true; thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = put_req_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Put Request for Thread Worker"); return -EIO; } if(0 != thargs.result){ // continue... S3FS_PRN_DBG("Put Request(%s) returns with errno(%d)", (tpath ? tpath : tmppath.c_str()), thargs.result); } result = thargs.result; } // reset uploaded file size size_orgmeta = st.st_size; } untreated_list.ClearAll(); }else{ // Already start uploading // upload rest data off_t untreated_start = 0; off_t untreated_size = 0; if(untreated_list.GetLastUpdatedPart(untreated_start, untreated_size, S3fsCurl::GetMultipartSize(), 0) && 0 < untreated_size){ if(0 != (result = NoCacheMultipartUploadRequest(pseudo_obj, physical_fd, untreated_start, untreated_size))){ S3FS_PRN_ERR("failed to multipart upload(start=%lld, size=%lld) for file(physical_fd=%d).", static_cast<long long int>(untreated_start), static_cast<long long int>(untreated_size), physical_fd); return result; } untreated_list.ClearParts(untreated_start, untreated_size); } // complete multipart uploading. if(0 != (result = NoCacheMultipartUploadComplete(pseudo_obj))){ S3FS_PRN_ERR("failed to complete(finish) multipart upload for file(physical_fd=%d).", physical_fd); return result; } // truncate file to zero if(-1 == ftruncate(physical_fd, 0)){ // So the file has already been removed, skip error. S3FS_PRN_ERR("failed to truncate file(physical_fd=%d) to zero, but continue...", physical_fd); } // put pending headers or create new file if(0 != (result = UploadPendingHasLock(-1))){ return result; } } if(0 == result){ pagelist.ClearAllModified(); pending_status = pending_status_t::NO_UPDATE_PENDING; } return result; } // // ([TODO] This is a temporary modification till S3fsMultiCurl is deprecated.) // int FdEntity::RowFlushMixMultipart(PseudoFdInfo* pseudo_obj, const char* tpath) { S3FS_PRN_INFO3("[tpath=%s][path=%s][pseudo_fd=%d][physical_fd=%d]", SAFESTRPTR(tpath), path.c_str(), (pseudo_obj ? pseudo_obj->GetPseudoFd() : -1), physical_fd); if(-1 == physical_fd || !pseudo_obj){ return -EBADF; } int result = 0; if(!pseudo_obj->IsUploading()){ // Start uploading // If there is no loading all of the area, loading all area. off_t restsize = pagelist.GetTotalUnloadedPageSize(/* start */ 0, /* size = all */ 0, MIN_MULTIPART_SIZE); // Check rest size and free disk space if(0 < restsize && !ReserveDiskSpace(restsize)){ // no enough disk space if(0 != (result = NoCachePreMultipartUploadRequest(pseudo_obj))){ S3FS_PRN_ERR("failed to switch multipart uploading with no cache(errno=%d)", result); return result; } // upload all by multipart uploading if(0 != (result = NoCacheLoadAndPost(pseudo_obj))){ S3FS_PRN_ERR("failed to upload all area by multipart uploading(errno=%d)", result); return result; } }else{ // enough disk space or no rest size std::string tmppath = path; headers_t tmporgmeta = orgmeta; FdManager::FreeReservedDiskSpace(restsize); // backup upload file size struct stat st{}; if(-1 == fstat(physical_fd, &st)){ S3FS_PRN_ERR("fstat is failed by errno(%d), but continue...", errno); } if(pagelist.Size() > MAX_MULTIPART_CNT * S3fsCurl::GetMultipartSize()){ S3FS_PRN_ERR("Part count exceeds %d. Increase multipart size and try again.", MAX_MULTIPART_CNT); return -EFBIG; }else if(pagelist.Size() >= S3fsCurl::GetMultipartSize()){ // mix multipart uploading // This is to ensure that each part is 5MB or more. // If the part is less than 5MB, download it. fdpage_list_t dlpages; fdpage_list_t mixuppages; if(!pagelist.GetPageListsForMultipartUpload(dlpages, mixuppages, S3fsCurl::GetMultipartSize())){ S3FS_PRN_ERR("something error occurred during getting download pagelist."); return -1; } // [TODO] should use parallel downloading // for(auto iter = dlpages.cbegin(); iter != dlpages.cend(); ++iter){ if(0 != (result = Load(iter->offset, iter->bytes, /*is_modified_flag=*/ true))){ // set loaded and modified flag S3FS_PRN_ERR("failed to get parts(start=%lld, size=%lld) before uploading.", static_cast<long long int>(iter->offset), static_cast<long long int>(iter->bytes)); return result; } } // multipart uploading with copy api result = S3fsCurl::ParallelMixMultipartUploadRequest(tpath ? tpath : tmppath.c_str(), tmporgmeta, physical_fd, mixuppages); }else{ // normal uploading (too small part size) // If there are unloaded pages, they are loaded at here. if(0 != (result = Load(/*start=*/ 0, /*size=*/ 0))){ S3FS_PRN_ERR("failed to load parts before uploading object(%d)", result); return result; } // parameter for thread worker put_req_thparam thargs; thargs.path = tpath ? tpath : tmppath; thargs.meta = tmporgmeta; // copy thargs.fd = physical_fd; thargs.ahbe = true; thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = put_req_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Put Request for Thread Worker"); return -EIO; } if(0 != thargs.result){ // continue... S3FS_PRN_DBG("Put Request(%s) returns with errno(%d)", (tpath ? tpath : tmppath.c_str()), thargs.result); } result = thargs.result; } // reset uploaded file size size_orgmeta = st.st_size; } untreated_list.ClearAll(); }else{ // Already start uploading // upload rest data off_t untreated_start = 0; off_t untreated_size = 0; if(untreated_list.GetLastUpdatedPart(untreated_start, untreated_size, S3fsCurl::GetMultipartSize(), 0) && 0 < untreated_size){ if(0 != (result = NoCacheMultipartUploadRequest(pseudo_obj, physical_fd, untreated_start, untreated_size))){ S3FS_PRN_ERR("failed to multipart upload(start=%lld, size=%lld) for file(physical_fd=%d).", static_cast<long long int>(untreated_start), static_cast<long long int>(untreated_size), physical_fd); return result; } untreated_list.ClearParts(untreated_start, untreated_size); } // complete multipart uploading. if(0 != (result = NoCacheMultipartUploadComplete(pseudo_obj))){ S3FS_PRN_ERR("failed to complete(finish) multipart upload for file(physical_fd=%d).", physical_fd); return result; } // truncate file to zero if(-1 == ftruncate(physical_fd, 0)){ // So the file has already been removed, skip error. S3FS_PRN_ERR("failed to truncate file(physical_fd=%d) to zero, but continue...", physical_fd); } // put pending headers or create new file if(0 != (result = UploadPendingHasLock(-1))){ return result; } } if(0 == result){ pagelist.ClearAllModified(); pending_status = pending_status_t::NO_UPDATE_PENDING; } return result; } // // ([TODO] This is a temporary modification till S3fsMultiCurl is deprecated.) // int FdEntity::RowFlushStreamMultipart(PseudoFdInfo* pseudo_obj, const char* tpath) { S3FS_PRN_INFO3("[tpath=%s][path=%s][pseudo_fd=%d][physical_fd=%d][mix_upload=%s]", SAFESTRPTR(tpath), path.c_str(), (pseudo_obj ? pseudo_obj->GetPseudoFd() : -1), physical_fd, (FdEntity::mixmultipart ? "true" : "false")); if(-1 == physical_fd || !pseudo_obj){ return -EBADF; } int result = 0; if(pagelist.Size() <= S3fsCurl::GetMultipartSize()){ // // Use normal upload instead of multipart upload(too small part size) // // backup upload file size struct stat st{}; if(-1 == fstat(physical_fd, &st)){ S3FS_PRN_ERR("fstat is failed by errno(%d), but continue...", errno); } // If there are unloaded pages, they are loaded at here. if(0 != (result = Load(/*start=*/ 0, /*size=*/ 0))){ S3FS_PRN_ERR("failed to load parts before uploading object(%d)", result); return result; } // parameter for thread worker put_req_thparam thargs; thargs.path = path; thargs.meta = orgmeta; // copy thargs.fd = physical_fd; thargs.ahbe = true; thargs.result = 0; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = &thargs; ppoolparam.psem = nullptr; // case await ppoolparam.pfunc = put_req_threadworker; // send request by thread if(!ThreadPoolMan::AwaitInstruct(ppoolparam)){ S3FS_PRN_ERR("failed to setup Put Request for Thread Worker"); return -EIO; } if(0 != thargs.result){ // continue... S3FS_PRN_DBG("Put Request(%s) returns with errno(%d)", path.c_str(), thargs.result); } result = thargs.result; // reset uploaded file size size_orgmeta = st.st_size; untreated_list.ClearAll(); if(0 == result){ pagelist.ClearAllModified(); } }else{ // // Make upload/download/copy/cancel lists from file // mp_part_list_t to_upload_list; mp_part_list_t to_copy_list; mp_part_list_t to_download_list; filepart_list_t cancel_uploaded_list; bool wait_upload_complete = false; if(!pseudo_obj->ExtractUploadPartsFromAllArea(untreated_list, to_upload_list, to_copy_list, to_download_list, cancel_uploaded_list, wait_upload_complete, S3fsCurl::GetMultipartSize(), pagelist.Size(), FdEntity::mixmultipart)){ S3FS_PRN_ERR("Failed to extract various upload parts list from all area: errno(EIO)"); return -EIO; } // // Check total size for downloading and Download // off_t total_download_size = total_mp_part_list(to_download_list); if(0 < total_download_size){ // // Check if there is enough free disk space for the total download size // if(!ReserveDiskSpace(total_download_size)){ // no enough disk space // // [NOTE] // Because there is no left space size to download, we can't solve this anymore // in this case which is uploading in sequence. // S3FS_PRN_WARN("Not enough local storage(%lld byte) to cache write request for whole of the file: [path=%s][physical_fd=%d]", static_cast<long long int>(total_download_size), path.c_str(), physical_fd); return -ENOSPC; // No space left on device } // enough disk space // // Download all parts // // [TODO] // Execute in parallel downloading with multiple thread. // for(auto download_iter = to_download_list.cbegin(); download_iter != to_download_list.cend(); ++download_iter){ if(0 != (result = Load(download_iter->start, download_iter->size))){ break; } } FdManager::FreeReservedDiskSpace(total_download_size); if(0 != result){ S3FS_PRN_ERR("failed to load uninitialized area before writing(errno=%d)", result); return result; } } // // Has multipart uploading already started? // if(!pseudo_obj->IsUploading()){ // // Multipart uploading hasn't started yet, so start it. // if(0 != (result = PreMultipartUploadRequest(pseudo_obj))){ return result; } } // // Output debug level information // // When canceling(overwriting) a part that has already been uploaded, output it. // if(S3fsLog::IsS3fsLogDbg()){ for(auto cancel_iter = cancel_uploaded_list.cbegin(); cancel_iter != cancel_uploaded_list.cend(); ++cancel_iter){ S3FS_PRN_DBG("Cancel uploaded: start(%lld), size(%lld), part number(%d)", static_cast<long long int>(cancel_iter->startpos), static_cast<long long int>(cancel_iter->size), (cancel_iter->petag ? cancel_iter->petag->part_num : -1)); } } // [NOTE] // If there is a part where has already been uploading, that part // is re-updated after finishing uploading, so the part of the last // uploaded must be canceled. // (These are cancel_uploaded_list, cancellation processing means // re-uploading the same area.) // // In rare cases, the completion of the previous upload and the // re-upload may be reversed, causing the ETag to be reversed, // in which case the upload will fail. // To prevent this, if the upload of the same area as the re-upload // is incomplete, we must wait for it to complete here. // if(wait_upload_complete){ if(0 != (result = pseudo_obj->WaitAllThreadsExit())){ S3FS_PRN_ERR("Some cancel area uploads that were waiting to complete failed with %d.", result); return result; } } // // Upload multipart and copy parts and wait exiting them // if(!pseudo_obj->ParallelMultipartUploadAll(path.c_str(), to_upload_list, to_copy_list, result)){ S3FS_PRN_ERR("Failed to upload multipart parts."); untreated_list.ClearAll(); pseudo_obj->ClearUploadInfo(); // clear multipart upload info return -EIO; } if(0 != result){ S3FS_PRN_ERR("An error(%d) occurred in some threads that were uploading parallel multiparts, but continue to clean up..", result); untreated_list.ClearAll(); pseudo_obj->ClearUploadInfo(); // clear multipart upload info return result; } // // Complete uploading // std::string upload_id; etaglist_t parts; if(!pseudo_obj->GetUploadId(upload_id) || !pseudo_obj->GetEtaglist(parts)){ S3FS_PRN_ERR("There is no upload id or etag list."); untreated_list.ClearAll(); pseudo_obj->ClearUploadInfo(); // clear multipart upload info return -EIO; }else{ if(0 != (result = complete_multipart_upload_request(path, upload_id, parts))){ S3FS_PRN_ERR("failed to complete multipart upload by errno(%d)", result); untreated_list.ClearAll(); pseudo_obj->ClearUploadInfo(); // clear multipart upload info int result2; if(0 != (result2 = abort_multipart_upload_request(path, upload_id))){ S3FS_PRN_ERR("failed to abort multipart upload by errno(%d)", result2); } return result; } } untreated_list.ClearAll(); pseudo_obj->ClearUploadInfo(); // clear multipart upload info // put pending headers or create new file if(0 != (result = UploadPendingHasLock(-1))){ return result; } } untreated_list.ClearAll(); if(0 == result){ pagelist.ClearAllModified(); } return result; } // [NOTICE] // Need to lock before calling this method. bool FdEntity::ReserveDiskSpace(off_t size) { if(FdManager::ReserveDiskSpace(size)){ return true; } if(!pagelist.IsModified()){ // try to clear all cache for this fd. pagelist.Init(pagelist.Size(), false, false); if(-1 == ftruncate(physical_fd, 0) || -1 == ftruncate(physical_fd, pagelist.Size())){ S3FS_PRN_ERR("failed to truncate temporary file(physical_fd=%d).", physical_fd); return false; } if(FdManager::ReserveDiskSpace(size)){ return true; } } FdManager::get()->CleanupCacheDir(); return FdManager::ReserveDiskSpace(size); } ssize_t FdEntity::Read(int fd, char* bytes, off_t start, size_t size, bool force_load) { const std::lock_guard<std::mutex> lock(fdent_lock); S3FS_PRN_DBG("[path=%s][pseudo_fd=%d][physical_fd=%d][offset=%lld][size=%zu]", path.c_str(), fd, physical_fd, static_cast<long long int>(start), size); if(-1 == physical_fd || nullptr == CheckPseudoFdFlags(fd, false)){ S3FS_PRN_DBG("pseudo_fd(%d) to physical_fd(%d) for path(%s) is not opened or not readable", fd, physical_fd, path.c_str()); return -EBADF; } const std::lock_guard<std::mutex> data_lock(fdent_data_lock); if(force_load){ pagelist.SetPageLoadedStatus(start, size, PageList::page_status::NOT_LOAD_MODIFIED); } ssize_t rsize; // check disk space if(0 < pagelist.GetTotalUnloadedPageSize(start, size)){ // load size(for prefetch) size_t load_size = size; if(start + static_cast<ssize_t>(size) < pagelist.Size()){ ssize_t prefetch_max_size = std::max(static_cast<off_t>(size), S3fsCurl::GetMultipartSize() * S3fsCurl::GetMaxParallelCount()); if(start + prefetch_max_size < pagelist.Size()){ load_size = prefetch_max_size; }else{ load_size = pagelist.Size() - start; } } if(!ReserveDiskSpace(load_size)){ S3FS_PRN_WARN("could not reserve disk space for pre-fetch download"); load_size = size; if(!ReserveDiskSpace(load_size)){ S3FS_PRN_ERR("could not reserve disk space for pre-fetch download"); return -ENOSPC; } } // Loading int result = 0; if(0 < size){ result = Load(start, load_size); } FdManager::FreeReservedDiskSpace(load_size); if(0 != result){ S3FS_PRN_ERR("could not download. start(%lld), size(%zu), errno(%d)", static_cast<long long int>(start), size, result); return result; } } // Reading if(-1 == (rsize = pread(physical_fd, bytes, size, start))){ S3FS_PRN_ERR("pread failed. errno(%d)", errno); return -errno; } return rsize; } ssize_t FdEntity::Write(int fd, const char* bytes, off_t start, size_t size) { const std::lock_guard<std::mutex> lock(fdent_lock); S3FS_PRN_DBG("[path=%s][pseudo_fd=%d][physical_fd=%d][offset=%lld][size=%zu]", path.c_str(), fd, physical_fd, static_cast<long long int>(start), size); PseudoFdInfo* pseudo_obj = nullptr; if(-1 == physical_fd || nullptr == (pseudo_obj = CheckPseudoFdFlags(fd, false))){ S3FS_PRN_ERR("pseudo_fd(%d) to physical_fd(%d) for path(%s) is not opened or not writable", fd, physical_fd, path.c_str()); return -EBADF; } // check if not enough disk space left BEFORE locking fd if(FdManager::IsCacheDir() && !FdManager::IsSafeDiskSpace(nullptr, size)){ FdManager::get()->CleanupCacheDir(); } const std::lock_guard<std::mutex> data_lock(fdent_data_lock); // check file size if(pagelist.Size() < start){ // grow file size if(-1 == ftruncate(physical_fd, start)){ S3FS_PRN_ERR("failed to truncate temporary file(physical_fd=%d).", physical_fd); return -errno; } // set untreated area if(!AddUntreated(pagelist.Size(), (start - pagelist.Size()))){ S3FS_PRN_ERR("failed to set untreated area by incremental."); return -EIO; } // add new area pagelist.SetPageLoadedStatus(pagelist.Size(), start - pagelist.Size(), PageList::page_status::MODIFIED); } ssize_t wsize; if(nomultipart){ // No multipart upload wsize = WriteNoMultipart(pseudo_obj, bytes, start, size); }else if(FdEntity::streamupload){ // Stream upload wsize = WriteStreamUpload(pseudo_obj, bytes, start, size); }else if(FdEntity::mixmultipart){ // Mix multipart upload wsize = WriteMixMultipart(pseudo_obj, bytes, start, size); }else{ // Normal multipart upload wsize = WriteMultipart(pseudo_obj, bytes, start, size); } return wsize; } ssize_t FdEntity::WriteNoMultipart(const PseudoFdInfo* pseudo_obj, const char* bytes, off_t start, size_t size) { S3FS_PRN_DBG("[path=%s][pseudo_fd=%d][physical_fd=%d][offset=%lld][size=%zu]", path.c_str(), (pseudo_obj ? pseudo_obj->GetPseudoFd() : -1), physical_fd, static_cast<long long int>(start), size); if(-1 == physical_fd || !pseudo_obj){ S3FS_PRN_ERR("pseudo_fd(%d) to physical_fd(%d) for path(%s) is not opened or not writable", (pseudo_obj ? pseudo_obj->GetPseudoFd() : -1), physical_fd, path.c_str()); return -EBADF; } int result = 0; if(pseudo_obj->IsUploading()){ S3FS_PRN_ERR("Why uploading now, even though s3fs is No Multipart uploading mode."); return -EBADF; } // check disk space off_t restsize = pagelist.GetTotalUnloadedPageSize(0, start) + size; if(!ReserveDiskSpace(restsize)){ // no enough disk space S3FS_PRN_WARN("Not enough local storage to cache write request: [path=%s][physical_fd=%d][offset=%lld][size=%zu]", path.c_str(), physical_fd, static_cast<long long int>(start), size); return -ENOSPC; // No space left on device } // Load uninitialized area which starts from 0 to (start + size) before writing. if(0 < start){ result = Load(0, start); } FdManager::FreeReservedDiskSpace(restsize); if(0 != result){ S3FS_PRN_ERR("failed to load uninitialized area before writing(errno=%d)", result); return result; } // Writing ssize_t wsize; if(-1 == (wsize = pwrite(physical_fd, bytes, size, start))){ S3FS_PRN_ERR("pwrite failed. errno(%d)", errno); return -errno; } if(0 < wsize){ pagelist.SetPageLoadedStatus(start, wsize, PageList::page_status::LOAD_MODIFIED); AddUntreated(start, wsize); } // Load uninitialized area which starts from (start + size) to EOF after writing. if(pagelist.Size() > start + static_cast<off_t>(size)){ result = Load(start + size, pagelist.Size()); if(0 != result){ S3FS_PRN_ERR("failed to load uninitialized area after writing(errno=%d)", result); return result; } } return wsize; } ssize_t FdEntity::WriteMultipart(PseudoFdInfo* pseudo_obj, const char* bytes, off_t start, size_t size) { S3FS_PRN_DBG("[path=%s][pseudo_fd=%d][physical_fd=%d][offset=%lld][size=%zu]", path.c_str(), (pseudo_obj ? pseudo_obj->GetPseudoFd() : -1), physical_fd, static_cast<long long int>(start), size); if(-1 == physical_fd || !pseudo_obj){ S3FS_PRN_ERR("pseudo_fd(%d) to physical_fd(%d) for path(%s) is not opened or not writable", (pseudo_obj ? pseudo_obj->GetPseudoFd() : -1), physical_fd, path.c_str()); return -EBADF; } int result = 0; if(!pseudo_obj->IsUploading()){ // check disk space off_t restsize = pagelist.GetTotalUnloadedPageSize(0, start) + size; if(ReserveDiskSpace(restsize)){ // enough disk space // Load uninitialized area which starts from 0 to (start + size) before writing. if(0 < start){ result = Load(0, start); } FdManager::FreeReservedDiskSpace(restsize); if(0 != result){ S3FS_PRN_ERR("failed to load uninitialized area before writing(errno=%d)", result); return result; } }else{ // no enough disk space if((start + static_cast<off_t>(size)) <= S3fsCurl::GetMultipartSize()){ S3FS_PRN_WARN("Not enough local storage to cache write request till multipart upload can start: [path=%s][physical_fd=%d][offset=%lld][size=%zu]", path.c_str(), physical_fd, static_cast<long long int>(start), size); return -ENOSPC; // No space left on device } if(0 != (result = NoCachePreMultipartUploadRequest(pseudo_obj))){ S3FS_PRN_ERR("failed to switch multipart uploading with no cache(errno=%d)", result); return result; } // start multipart uploading if(0 != (result = NoCacheLoadAndPost(pseudo_obj, 0, start))){ S3FS_PRN_ERR("failed to load uninitialized area and multipart uploading it(errno=%d)", result); return result; } untreated_list.ClearAll(); } }else{ // already start multipart uploading } // Writing ssize_t wsize; if(-1 == (wsize = pwrite(physical_fd, bytes, size, start))){ S3FS_PRN_ERR("pwrite failed. errno(%d)", errno); return -errno; } if(0 < wsize){ pagelist.SetPageLoadedStatus(start, wsize, PageList::page_status::LOAD_MODIFIED); AddUntreated(start, wsize); } // Load uninitialized area which starts from (start + size) to EOF after writing. if(pagelist.Size() > start + static_cast<off_t>(size)){ result = Load(start + size, pagelist.Size()); if(0 != result){ S3FS_PRN_ERR("failed to load uninitialized area after writing(errno=%d)", result); return result; } } // check multipart uploading if(pseudo_obj->IsUploading()){ // get last untreated part(maximum size is multipart size) off_t untreated_start = 0; off_t untreated_size = 0; if(untreated_list.GetLastUpdatedPart(untreated_start, untreated_size, S3fsCurl::GetMultipartSize())){ // when multipart max size is reached if(0 != (result = NoCacheMultipartUploadRequest(pseudo_obj, physical_fd, untreated_start, untreated_size))){ S3FS_PRN_ERR("failed to multipart upload(start=%lld, size=%lld) for file(physical_fd=%d).", static_cast<long long int>(untreated_start), static_cast<long long int>(untreated_size), physical_fd); return result; } // [NOTE] // truncate file to zero and set length to part offset + size // after this, file length is (offset + size), but file does not use any disk space. // if(-1 == ftruncate(physical_fd, 0) || -1 == ftruncate(physical_fd, (untreated_start + untreated_size))){ S3FS_PRN_ERR("failed to truncate file(physical_fd=%d).", physical_fd); return -errno; } untreated_list.ClearParts(untreated_start, untreated_size); } } return wsize; } ssize_t FdEntity::WriteMixMultipart(PseudoFdInfo* pseudo_obj, const char* bytes, off_t start, size_t size) { S3FS_PRN_DBG("[path=%s][pseudo_fd=%d][physical_fd=%d][offset=%lld][size=%zu]", path.c_str(), (pseudo_obj ? pseudo_obj->GetPseudoFd() : -1), physical_fd, static_cast<long long int>(start), size); if(-1 == physical_fd || !pseudo_obj){ S3FS_PRN_ERR("pseudo_fd(%d) to physical_fd(%d) for path(%s) is not opened or not writable", (pseudo_obj ? pseudo_obj->GetPseudoFd() : -1), physical_fd, path.c_str()); return -EBADF; } int result; if(!pseudo_obj->IsUploading()){ // check disk space off_t restsize = pagelist.GetTotalUnloadedPageSize(0, start, MIN_MULTIPART_SIZE) + size; if(ReserveDiskSpace(restsize)){ // enough disk space FdManager::FreeReservedDiskSpace(restsize); }else{ // no enough disk space if((start + static_cast<off_t>(size)) <= S3fsCurl::GetMultipartSize()){ S3FS_PRN_WARN("Not enough local storage to cache write request till multipart upload can start: [path=%s][physical_fd=%d][offset=%lld][size=%zu]", path.c_str(), physical_fd, static_cast<long long int>(start), size); return -ENOSPC; // No space left on device } if(0 != (result = NoCachePreMultipartUploadRequest(pseudo_obj))){ S3FS_PRN_ERR("failed to switch multipart uploading with no cache(errno=%d)", result); return result; } // start multipart uploading if(0 != (result = NoCacheLoadAndPost(pseudo_obj, 0, start))){ S3FS_PRN_ERR("failed to load uninitialized area and multipart uploading it(errno=%d)", result); return result; } untreated_list.ClearAll(); } }else{ // already start multipart uploading } // Writing ssize_t wsize; if(-1 == (wsize = pwrite(physical_fd, bytes, size, start))){ S3FS_PRN_ERR("pwrite failed. errno(%d)", errno); return -errno; } if(0 < wsize){ pagelist.SetPageLoadedStatus(start, wsize, PageList::page_status::LOAD_MODIFIED); AddUntreated(start, wsize); } // check multipart uploading if(pseudo_obj->IsUploading()){ // get last untreated part(maximum size is multipart size) off_t untreated_start = 0; off_t untreated_size = 0; if(untreated_list.GetLastUpdatedPart(untreated_start, untreated_size, S3fsCurl::GetMultipartSize())){ // when multipart max size is reached if(0 != (result = NoCacheMultipartUploadRequest(pseudo_obj, physical_fd, untreated_start, untreated_size))){ S3FS_PRN_ERR("failed to multipart upload(start=%lld, size=%lld) for file(physical_fd=%d).", static_cast<long long int>(untreated_start), static_cast<long long int>(untreated_size), physical_fd); return result; } // [NOTE] // truncate file to zero and set length to part offset + size // after this, file length is (offset + size), but file does not use any disk space. // if(-1 == ftruncate(physical_fd, 0) || -1 == ftruncate(physical_fd, (untreated_start + untreated_size))){ S3FS_PRN_ERR("failed to truncate file(physical_fd=%d).", physical_fd); return -errno; } untreated_list.ClearParts(untreated_start, untreated_size); } } return wsize; } // // On Stream upload, the uploading is executed in another thread when the // written area exceeds the maximum size of multipart upload. // ssize_t FdEntity::WriteStreamUpload(PseudoFdInfo* pseudo_obj, const char* bytes, off_t start, size_t size) { S3FS_PRN_DBG("[path=%s][pseudo_fd=%d][physical_fd=%d][offset=%lld][size=%zu]", path.c_str(), (pseudo_obj ? pseudo_obj->GetPseudoFd() : -1), physical_fd, static_cast<long long int>(start), size); if(-1 == physical_fd || !pseudo_obj){ S3FS_PRN_ERR("pseudo_fd(%d) to physical_fd(%d) for path(%s) is not opened or not writable", (pseudo_obj ? pseudo_obj->GetPseudoFd() : -1), physical_fd, path.c_str()); return -EBADF; } // Writing ssize_t wsize; if(-1 == (wsize = pwrite(physical_fd, bytes, size, start))){ S3FS_PRN_ERR("pwrite failed. errno(%d)", errno); return -errno; } if(0 < wsize){ pagelist.SetPageLoadedStatus(start, wsize, PageList::page_status::LOAD_MODIFIED); AddUntreated(start, wsize); } // Check and Upload // // If the last updated Untreated area exceeds the maximum upload size, // upload processing is performed. // headers_t tmporgmeta = orgmeta; bool isuploading = pseudo_obj->IsUploading(); ssize_t result; if(0 != (result = pseudo_obj->UploadBoundaryLastUntreatedArea(path.c_str(), tmporgmeta, this))){ S3FS_PRN_ERR("Failed to upload the last untreated parts(area) : result=%zd", result); return result; } if(!isuploading && pseudo_obj->IsUploading()){ // Clear the dirty flag, because the meta data is updated. pending_status = pending_status_t::NO_UPDATE_PENDING; } return wsize; } // [NOTE] // Returns true if merged to orgmeta. // If true is returned, the caller can update the header. // If it is false, do not update the header because multipart upload is in progress. // In this case, the header is pending internally and is updated after the upload // is complete(flush file). // bool FdEntity::MergeOrgMeta(headers_t& updatemeta) { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> data_lock(fdent_data_lock); merge_headers(orgmeta, updatemeta, true); // overwrite all keys // [NOTE] // this is special cases, we remove the key which has empty values. for(auto hiter = orgmeta.cbegin(); hiter != orgmeta.cend(); ){ if(hiter->second.empty()){ hiter = orgmeta.erase(hiter); }else{ ++hiter; } } updatemeta = orgmeta; orgmeta.erase("x-amz-copy-source"); // update ctime/mtime/atime struct timespec mtime = get_mtime(updatemeta, false); // not overcheck struct timespec ctime = get_ctime(updatemeta, false); // not overcheck struct timespec atime = get_atime(updatemeta, false); // not overcheck if(0 <= mtime.tv_sec){ SetMCtimeHasLock(mtime, (ctime.tv_sec < 0 ? mtime : ctime)); } if(0 <= atime.tv_sec){ SetAtimeHasLock(atime); } if(pending_status_t::NO_UPDATE_PENDING == pending_status && (IsUploading() || pagelist.IsModified())){ pending_status = pending_status_t::UPDATE_META_PENDING; } return (pending_status_t::NO_UPDATE_PENDING != pending_status); } // global function in s3fs.cpp int put_headers(const char* path, headers_t& meta, bool is_copy, bool use_st_size = true); int FdEntity::UploadPendingHasLock(int fd) { int result; if(pending_status_t::NO_UPDATE_PENDING == pending_status){ // nothing to do result = 0; }else if(pending_status_t::UPDATE_META_PENDING == pending_status){ headers_t updatemeta = orgmeta; updatemeta["x-amz-copy-source"] = urlEncodePath(service_path + S3fsCred::GetBucket() + get_realpath(path.c_str())); updatemeta["x-amz-metadata-directive"] = "REPLACE"; // put headers, no need to update mtime to avoid dead lock result = put_headers(path.c_str(), updatemeta, true); if(0 != result){ S3FS_PRN_ERR("failed to put header after flushing file(%s) by(%d).", path.c_str(), result); }else{ pending_status = pending_status_t::NO_UPDATE_PENDING; } }else{ // CREATE_FILE_PENDING == pending_status if(-1 == fd){ S3FS_PRN_ERR("could not create a new file(%s), because fd is not specified.", path.c_str()); result = -EBADF; }else{ result = RowFlushHasLock(fd, nullptr, true); if(0 != result){ S3FS_PRN_ERR("failed to flush for file(%s) by(%d).", path.c_str(), result); }else{ pending_status = pending_status_t::NO_UPDATE_PENDING; } } } return result; } // [NOTE] // For systems where the fallocate function cannot be detected, use a dummy function. // ex. OSX // #if !defined(HAVE_FALLOCATE) || defined(__MSYS__) static int fallocate(int /*fd*/, int /*mode*/, off_t /*offset*/, off_t /*len*/) { errno = ENOSYS; // This is a bad idea, but the caller can handle it simply. return -1; } #endif // HAVE_FALLOCATE // [NOTE] // If HAVE_FALLOCATE is undefined, or versions prior to 2.6.38(fallocate function exists), // following flags are undefined. Then we need these symbols defined in fallocate, so we // define them here. // The definitions are copied from linux/falloc.h, but if HAVE_FALLOCATE is undefined, // these values can be anything. // #ifndef FALLOC_FL_PUNCH_HOLE #define FALLOC_FL_PUNCH_HOLE 0x02 /* de-allocates range */ #endif #ifndef FALLOC_FL_KEEP_SIZE #define FALLOC_FL_KEEP_SIZE 0x01 #endif // [NOTE] // This method punches an area(on cache file) that has no data at the time it is called. // This is called to prevent the cache file from growing. // However, this method uses the non-portable(Linux specific) system call fallocate(). // Also, depending on the file system, FALLOC_FL_PUNCH_HOLE mode may not work and HOLE // will not open.(Filesystems for which this method works are ext4, btrfs, xfs, etc.) // bool FdEntity::PunchHole(off_t start, size_t size) { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> data_lock(fdent_data_lock); S3FS_PRN_DBG("[path=%s][physical_fd=%d][offset=%lld][size=%zu]", path.c_str(), physical_fd, static_cast<long long int>(start), size); if(-1 == physical_fd){ return false; } // get page list that have no data fdpage_list_t nodata_pages; if(!pagelist.GetNoDataPageLists(nodata_pages)){ S3FS_PRN_ERR("failed to get page list that have no data."); return false; } if(nodata_pages.empty()){ S3FS_PRN_DBG("there is no page list that have no data, so nothing to do."); return true; } // try to punch hole to file for(auto iter = nodata_pages.cbegin(); iter != nodata_pages.cend(); ++iter){ if(0 != fallocate(physical_fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, iter->offset, iter->bytes)){ if(ENOSYS == errno || EOPNOTSUPP == errno){ S3FS_PRN_ERR("failed to fallocate for punching hole to file with errno(%d), it maybe the fallocate function is not implemented in this kernel, or the file system does not support FALLOC_FL_PUNCH_HOLE.", errno); }else{ S3FS_PRN_ERR("failed to fallocate for punching hole to file with errno(%d)", errno); } return false; } if(!pagelist.SetPageLoadedStatus(iter->offset, iter->bytes, PageList::page_status::NOT_LOAD_MODIFIED)){ S3FS_PRN_ERR("succeed to punch HOLEs in the cache file, but failed to update the cache stat."); return false; } S3FS_PRN_DBG("made a hole at [%lld - %lld bytes](into a boundary) of the cache file.", static_cast<long long int>(iter->offset), static_cast<long long int>(iter->bytes)); } return true; } // [NOTE] // Indicate that a new file's is dirty. // This ensures that both metadata and data are synced during flush. // void FdEntity::MarkDirtyNewFile() { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> data_lock(fdent_data_lock); pagelist.Init(0, false, true); pending_status = pending_status_t::CREATE_FILE_PENDING; } bool FdEntity::IsDirtyNewFile() const { const std::lock_guard<std::mutex> lock(fdent_data_lock); return (pending_status_t::CREATE_FILE_PENDING == pending_status); } // [NOTE] // The fdatasync call only uploads the content but does not update // the meta data. In the flush call, if there is no update contents, // need to upload only metadata, so use these functions. // void FdEntity::MarkDirtyMetadata() { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> data_lock(fdent_data_lock); if(pending_status_t::NO_UPDATE_PENDING == pending_status){ pending_status = pending_status_t::UPDATE_META_PENDING; } } bool FdEntity::IsDirtyMetadata() const { return (pending_status_t::UPDATE_META_PENDING == pending_status); } bool FdEntity::AddUntreated(off_t start, off_t size) { bool result = untreated_list.AddPart(start, size); if(!result){ S3FS_PRN_DBG("Failed adding untreated area part."); }else if(S3fsLog::IsS3fsLogDbg()){ untreated_list.Dump(); } return result; } bool FdEntity::GetLastUpdateUntreatedPart(off_t& start, off_t& size) const { // Get last untreated area if(!untreated_list.GetLastUpdatePart(start, size)){ return false; } return true; } bool FdEntity::ReplaceLastUpdateUntreatedPart(off_t front_start, off_t front_size, off_t behind_start, off_t behind_size) { if(0 < front_size){ if(!untreated_list.ReplaceLastUpdatePart(front_start, front_size)){ return false; } }else{ if(!untreated_list.RemoveLastUpdatePart()){ return false; } } if(0 < behind_size){ if(!untreated_list.AddPart(behind_start, behind_size)){ return false; } } return true; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
97,109
C++
.cpp
2,370
32.48481
283
0.587878
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,445
cache.cpp
s3fs-fuse_s3fs-fuse/src/cache.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <algorithm> #include <cerrno> #include <cstdlib> #include <mutex> #include <string> #include <sys/stat.h> #include <utility> #include <vector> #include "s3fs.h" #include "s3fs_logger.h" #include "s3fs_util.h" #include "cache.h" #include "string_util.h" //------------------------------------------------------------------- // Utility //------------------------------------------------------------------- static void SetStatCacheTime(struct timespec& ts) { if(-1 == clock_gettime(static_cast<clockid_t>(CLOCK_MONOTONIC_COARSE), &ts)){ S3FS_PRN_CRIT("clock_gettime failed: %d", errno); abort(); } } static int CompareStatCacheTime(const struct timespec& ts1, const struct timespec& ts2) { // return -1: ts1 < ts2 // 0: ts1 == ts2 // 1: ts1 > ts2 if(ts1.tv_sec < ts2.tv_sec){ return -1; }else if(ts1.tv_sec > ts2.tv_sec){ return 1; }else{ if(ts1.tv_nsec < ts2.tv_nsec){ return -1; }else if(ts1.tv_nsec > ts2.tv_nsec){ return 1; } } return 0; } static bool IsExpireStatCacheTime(const struct timespec& ts, time_t expire) { struct timespec nowts; SetStatCacheTime(nowts); nowts.tv_sec -= expire; return (0 < CompareStatCacheTime(nowts, ts)); } // // For stats cache out // typedef std::vector<stat_cache_t::iterator> statiterlist_t; struct sort_statiterlist{ // ascending order bool operator()(const stat_cache_t::iterator& src1, const stat_cache_t::iterator& src2) const { int result = CompareStatCacheTime(src1->second.cache_date, src2->second.cache_date); if(0 == result){ if(src1->second.hit_count < src2->second.hit_count){ result = -1; } } return (result < 0); } }; // // For symbolic link cache out // typedef std::vector<symlink_cache_t::iterator> symlinkiterlist_t; struct sort_symlinkiterlist{ // ascending order bool operator()(const symlink_cache_t::iterator& src1, const symlink_cache_t::iterator& src2) const { int result = CompareStatCacheTime(src1->second.cache_date, src2->second.cache_date); // use the same as Stats if(0 == result){ if(src1->second.hit_count < src2->second.hit_count){ result = -1; } } return (result < 0); } }; //------------------------------------------------------------------- // Static //------------------------------------------------------------------- StatCache StatCache::singleton; std::mutex StatCache::stat_cache_lock; //------------------------------------------------------------------- // Constructor/Destructor //------------------------------------------------------------------- StatCache::StatCache() : IsExpireTime(true), IsExpireIntervalType(false), ExpireTime(15 * 60), CacheSize(100000), IsCacheNoObject(true) { if(this == StatCache::getStatCacheData()){ stat_cache.clear(); }else{ abort(); } } StatCache::~StatCache() { if(this == StatCache::getStatCacheData()){ Clear(); }else{ abort(); } } //------------------------------------------------------------------- // Methods //------------------------------------------------------------------- unsigned long StatCache::GetCacheSize() const { return CacheSize; } unsigned long StatCache::SetCacheSize(unsigned long size) { unsigned long old = CacheSize; CacheSize = size; return old; } time_t StatCache::GetExpireTime() const { return (IsExpireTime ? ExpireTime : (-1)); } time_t StatCache::SetExpireTime(time_t expire, bool is_interval) { time_t old = ExpireTime; ExpireTime = expire; IsExpireTime = true; IsExpireIntervalType = is_interval; return old; } time_t StatCache::UnsetExpireTime() { time_t old = IsExpireTime ? ExpireTime : (-1); ExpireTime = 0; IsExpireTime = false; IsExpireIntervalType = false; return old; } bool StatCache::SetCacheNoObject(bool flag) { bool old = IsCacheNoObject; IsCacheNoObject = flag; return old; } void StatCache::Clear() { const std::lock_guard<std::mutex> lock(StatCache::stat_cache_lock); stat_cache.clear(); S3FS_MALLOCTRIM(0); } bool StatCache::GetStat(const std::string& key, struct stat* pst, headers_t* meta, bool overcheck, const char* petag, bool* pisforce) { bool is_delete_cache = false; std::string strpath = key; const std::lock_guard<std::mutex> lock(StatCache::stat_cache_lock); auto iter = stat_cache.end(); if(overcheck && '/' != *strpath.rbegin()){ strpath += "/"; iter = stat_cache.find(strpath); } if(iter == stat_cache.end()){ strpath = key; iter = stat_cache.find(strpath); } if(iter != stat_cache.end()){ stat_cache_entry* ent = &iter->second; if(0 < ent->notruncate || !IsExpireTime || !IsExpireStatCacheTime(ent->cache_date, ExpireTime)){ if(ent->noobjcache){ if(!IsCacheNoObject){ // need to delete this cache. DelStatHasLock(strpath); }else{ // noobjcache = true means no object. } return false; } // hit without checking etag std::string stretag; if(petag){ // find & check ETag auto hiter = ent->meta.find("etag"); if(hiter != ent->meta.end()){ stretag = hiter->second; if('\0' != petag[0] && petag != stretag){ 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=%lld.%09ld][hit count=%lu][ETag(%s)!=(%s)]", strpath.c_str(), static_cast<long long>(ent->cache_date.tv_sec), ent->cache_date.tv_nsec, ent->hit_count, petag ? petag : "null", stretag.c_str()); }else{ // hit S3FS_PRN_DBG("stat cache hit [path=%s][time=%lld.%09ld][hit count=%lu]", strpath.c_str(), static_cast<long long>(ent->cache_date.tv_sec), ent->cache_date.tv_nsec, ent->hit_count); if(pst!= nullptr){ *pst= ent->stbuf; } if(meta != nullptr){ *meta = ent->meta; } if(pisforce != nullptr){ (*pisforce) = ent->isforce; } ent->hit_count++; if(IsExpireIntervalType){ SetStatCacheTime(ent->cache_date); } return true; } }else{ // timeout is_delete_cache = true; } } if(is_delete_cache){ DelStatHasLock(strpath); } return false; } bool StatCache::IsNoObjectCache(const std::string& key, bool overcheck) { bool is_delete_cache = false; std::string strpath = key; if(!IsCacheNoObject){ return false; } const std::lock_guard<std::mutex> lock(StatCache::stat_cache_lock); auto iter = stat_cache.end(); if(overcheck && '/' != *strpath.rbegin()){ strpath += "/"; iter = stat_cache.find(strpath); } if(iter == stat_cache.end()){ strpath = key; iter = stat_cache.find(strpath); } if(iter != stat_cache.end()) { const stat_cache_entry* ent = &iter->second; if(0 < ent->notruncate || !IsExpireTime || !IsExpireStatCacheTime(iter->second.cache_date, ExpireTime)){ if(iter->second.noobjcache){ // noobjcache = true means no object. SetStatCacheTime((*iter).second.cache_date); return true; } }else{ // timeout is_delete_cache = true; } } if(is_delete_cache){ DelStatHasLock(strpath); } return false; } bool StatCache::AddStat(const std::string& key, const headers_t& meta, bool forcedir, bool no_truncate) { if(!no_truncate && CacheSize< 1){ return true; } S3FS_PRN_INFO3("add stat cache entry[path=%s]", key.c_str()); const std::lock_guard<std::mutex> lock(StatCache::stat_cache_lock); if(stat_cache.cend() != stat_cache.find(key)){ // found cache DelStatHasLock(key); }else{ // check: need to truncate cache if(stat_cache.size() > CacheSize){ // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(!TruncateCache()){ return false; } } } // make new stat_cache_entry ent; if(!convert_header_to_stat(key.c_str(), meta, &ent.stbuf, forcedir)){ return false; } ent.hit_count = 0; ent.isforce = forcedir; ent.noobjcache = false; ent.notruncate = (no_truncate ? 1L : 0L); ent.meta.clear(); SetStatCacheTime(ent.cache_date); // Set time. //copy only some keys for(auto iter = meta.cbegin(); iter != meta.cend(); ++iter){ auto tag = CaseInsensitiveStringView(iter->first); const auto& value = iter->second; if(tag == "content-type" || tag == "content-length" || tag == "etag" || tag == "last-modified" || tag.is_prefix("x-amz")){ ent.meta[iter->first] = value; } } const auto& value = stat_cache[key] = std::move(ent); // check symbolic link cache if(!S_ISLNK(value.stbuf.st_mode)){ if(symlink_cache.cend() != symlink_cache.find(key)){ // if symbolic link cache has key, thus remove it. DelSymlinkHasLock(key); } } // If no_truncate flag is set, set file name to notruncate_file_cache // if(no_truncate){ AddNotruncateCache(key); } return true; } // [NOTE] // Updates only meta data if cached data exists. // And when these are updated, it also updates the cache time. // // Since the file mode may change while the file is open, it is // updated as well. // bool StatCache::UpdateMetaStats(const std::string& key, const headers_t& meta) { if(CacheSize < 1){ return true; } S3FS_PRN_INFO3("update stat cache entry[path=%s]", key.c_str()); const std::lock_guard<std::mutex> lock(StatCache::stat_cache_lock); auto iter = stat_cache.find(key); if(stat_cache.cend() == iter){ return true; } stat_cache_entry* ent = &iter->second; // update only meta keys for(auto metaiter = meta.cbegin(); metaiter != meta.cend(); ++metaiter){ auto tag = CaseInsensitiveStringView(metaiter->first); const auto& value = metaiter->second; if(tag == "content-type" || tag == "content-length" || tag == "etag" || tag == "last-modified" || tag.is_prefix("x-amz")){ ent->meta[metaiter->first] = value; } } // Update time. SetStatCacheTime(ent->cache_date); // Update only mode ent->stbuf.st_mode = get_mode(meta, key); return true; } bool StatCache::AddNoObjectCache(const std::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()); const std::lock_guard<std::mutex> lock(StatCache::stat_cache_lock); if(stat_cache.cend() != stat_cache.find(key)){ // found DelStatHasLock(key); }else{ // check: need to truncate cache if(stat_cache.size() > CacheSize){ // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(!TruncateCache()){ return false; } } } // make new stat_cache_entry ent{}; ent.hit_count = 0; ent.isforce = false; ent.noobjcache = true; ent.notruncate = 0L; ent.meta.clear(); SetStatCacheTime(ent.cache_date); // Set time. stat_cache[key] = std::move(ent); // check symbolic link cache if(symlink_cache.cend() != symlink_cache.find(key)){ // if symbolic link cache has key, thus remove it. DelSymlinkHasLock(key); } return true; } void StatCache::ChangeNoTruncateFlag(const std::string& key, bool no_truncate) { const std::lock_guard<std::mutex> lock(StatCache::stat_cache_lock); auto iter = stat_cache.find(key); if(stat_cache.cend() != iter){ stat_cache_entry* ent = &iter->second; if(no_truncate){ if(0L == ent->notruncate){ // need to add no truncate cache. AddNotruncateCache(key); } ++(ent->notruncate); }else{ if(0L < ent->notruncate){ --(ent->notruncate); if(0L == ent->notruncate){ // need to delete from no truncate cache. DelNotruncateCache(key); } } } } } bool StatCache::TruncateCache() { if(stat_cache.empty()){ return true; } // 1) erase over expire time if(IsExpireTime){ for(auto iter = stat_cache.cbegin(); iter != stat_cache.cend(); ){ const stat_cache_entry* entry = &iter->second; if(0L == entry->notruncate && IsExpireStatCacheTime(entry->cache_date, ExpireTime)){ iter = stat_cache.erase(iter); }else{ ++iter; } } } // 2) check stat cache count if(stat_cache.size() < CacheSize){ return true; } // 3) erase from the old cache in order size_t erase_count= stat_cache.size() - CacheSize + 1; statiterlist_t erase_iters; for(auto iter = stat_cache.begin(); iter != stat_cache.end() && 0 < erase_count; ++iter){ // check no truncate const stat_cache_entry* ent = &iter->second; if(0L < ent->notruncate){ // skip for no truncate entry and keep extra counts for this entity. if(0 < erase_count){ --erase_count; // decrement } }else{ // iter is not have notruncate flag erase_iters.push_back(iter); } if(erase_count < erase_iters.size()){ std::sort(erase_iters.begin(), erase_iters.end(), sort_statiterlist()); while(erase_count < erase_iters.size()){ erase_iters.pop_back(); } } } for(auto iiter = erase_iters.cbegin(); iiter != erase_iters.cend(); ++iiter){ auto siter = *iiter; S3FS_PRN_DBG("truncate stat cache[path=%s]", siter->first.c_str()); stat_cache.erase(siter); } S3FS_MALLOCTRIM(0); return true; } bool StatCache::DelStatHasLock(const std::string& key) { S3FS_PRN_INFO3("delete stat cache entry[path=%s]", key.c_str()); stat_cache_t::iterator iter; if(stat_cache.cend() != (iter = stat_cache.find(key))){ stat_cache.erase(iter); DelNotruncateCache(key); } if(!key.empty() && key != "/"){ std::string strpath = key; if('/' == *strpath.rbegin()){ // If there is "path" cache, delete it. strpath.erase(strpath.length() - 1); }else{ // If there is "path/" cache, delete it. strpath += "/"; } if(stat_cache.cend() != (iter = stat_cache.find(strpath))){ stat_cache.erase(iter); DelNotruncateCache(strpath); } } S3FS_MALLOCTRIM(0); return true; } bool StatCache::GetSymlink(const std::string& key, std::string& value) { bool is_delete_cache = false; const std::string& strpath = key; const std::lock_guard<std::mutex> lock(StatCache::stat_cache_lock); auto iter = symlink_cache.find(strpath); if(iter != symlink_cache.cend()){ symlink_cache_entry* ent = &iter->second; if(!IsExpireTime || !IsExpireStatCacheTime(ent->cache_date, ExpireTime)){ // use the same as Stats // found S3FS_PRN_DBG("symbolic link cache hit [path=%s][time=%lld.%09ld][hit count=%lu]", strpath.c_str(), static_cast<long long>(ent->cache_date.tv_sec), ent->cache_date.tv_nsec, ent->hit_count); value = ent->link; ent->hit_count++; if(IsExpireIntervalType){ SetStatCacheTime(ent->cache_date); } return true; }else{ // timeout is_delete_cache = true; } } if(is_delete_cache){ DelSymlinkHasLock(strpath); } return false; } bool StatCache::AddSymlink(const std::string& key, const std::string& value) { if(CacheSize< 1){ return true; } S3FS_PRN_INFO3("add symbolic link cache entry[path=%s, value=%s]", key.c_str(), value.c_str()); const std::lock_guard<std::mutex> lock(StatCache::stat_cache_lock); if(symlink_cache.cend() != symlink_cache.find(key)){ // found DelSymlinkHasLock(key); }else{ // check: need to truncate cache if(symlink_cache.size() > CacheSize){ // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(!TruncateSymlink()){ return false; } } } // make new symlink_cache_entry ent; ent.link = value; ent.hit_count = 0; SetStatCacheTime(ent.cache_date); // Set time(use the same as Stats). symlink_cache[key] = std::move(ent); return true; } bool StatCache::TruncateSymlink() { if(symlink_cache.empty()){ return true; } // 1) erase over expire time if(IsExpireTime){ for(auto iter = symlink_cache.cbegin(); iter != symlink_cache.cend(); ){ const symlink_cache_entry* entry = &iter->second; if(IsExpireStatCacheTime(entry->cache_date, ExpireTime)){ // use the same as Stats iter = symlink_cache.erase(iter); }else{ ++iter; } } } // 2) check stat cache count if(symlink_cache.size() < CacheSize){ return true; } // 3) erase from the old cache in order size_t erase_count= symlink_cache.size() - CacheSize + 1; symlinkiterlist_t erase_iters; for(auto iter = symlink_cache.begin(); iter != symlink_cache.end(); ++iter){ erase_iters.push_back(iter); sort(erase_iters.begin(), erase_iters.end(), sort_symlinkiterlist()); if(erase_count < erase_iters.size()){ erase_iters.pop_back(); } } for(auto iiter = erase_iters.cbegin(); iiter != erase_iters.cend(); ++iiter){ auto siter = *iiter; S3FS_PRN_DBG("truncate symbolic link cache[path=%s]", siter->first.c_str()); symlink_cache.erase(siter); } S3FS_MALLOCTRIM(0); return true; } bool StatCache::DelSymlinkHasLock(const std::string& key) { S3FS_PRN_INFO3("delete symbolic link cache entry[path=%s]", key.c_str()); symlink_cache_t::iterator iter; if(symlink_cache.cend() != (iter = symlink_cache.find(key))){ symlink_cache.erase(iter); } S3FS_MALLOCTRIM(0); return true; } bool StatCache::AddNotruncateCache(const std::string& key) { if(key.empty() || '/' == *key.rbegin()){ return false; } std::string parentdir = mydirname(key); std::string filename = mybasename(key); if(parentdir.empty() || filename.empty()){ return false; } parentdir += '/'; // directory path must be '/' termination. auto iter = notruncate_file_cache.find(parentdir); if(iter == notruncate_file_cache.cend()){ // add new list notruncate_filelist_t list; list.push_back(filename); notruncate_file_cache[parentdir] = list; }else{ // add filename to existed list notruncate_filelist_t& filelist = iter->second; auto fiter = std::find(filelist.cbegin(), filelist.cend(), filename); if(fiter == filelist.cend()){ filelist.push_back(filename); } } return true; } bool StatCache::DelNotruncateCache(const std::string& key) { if(key.empty() || '/' == *key.rbegin()){ return false; } std::string parentdir = mydirname(key); std::string filename = mybasename(key); if(parentdir.empty() || filename.empty()){ return false; } parentdir += '/'; // directory path must be '/' termination. auto iter = notruncate_file_cache.find(parentdir); if(iter != notruncate_file_cache.cend()){ // found directory in map notruncate_filelist_t& filelist = iter->second; auto fiter = std::find(filelist.begin(), filelist.end(), filename); if(fiter != filelist.cend()){ // found filename in directory file list filelist.erase(fiter); if(filelist.empty()){ notruncate_file_cache.erase(parentdir); } } } return true; } // [Background] // When s3fs creates a new file, the file does not exist until the file contents // are uploaded.(because it doesn't create a 0 byte file) // From the time this file is created(opened) until it is uploaded(flush), it // will have a Stat cache with the No truncate flag added. // This avoids file not existing errors in operations such as chmod and utimens // that occur in the short period before file upload. // Besides this, we also need to support readdir(list_bucket), this method is // called to maintain the cache for readdir and return its value. // // [NOTE] // Add the file names under parentdir to the list. // However, if the same file name exists in the list, it will not be added. // parentdir must be terminated with a '/'. // bool StatCache::GetNotruncateCache(const std::string& parentdir, notruncate_filelist_t& list) { if(parentdir.empty()){ return false; } std::string dirpath = parentdir; if('/' != *dirpath.rbegin()){ dirpath += '/'; } const std::lock_guard<std::mutex> lock(StatCache::stat_cache_lock); auto iter = notruncate_file_cache.find(dirpath); if(iter == notruncate_file_cache.cend()){ // not found directory map return true; } // found directory in map const notruncate_filelist_t& filelist = iter->second; for(auto fiter = filelist.cbegin(); fiter != filelist.cend(); ++fiter){ if(list.cend() == std::find(list.cbegin(), list.cend(), *fiter)){ // found notuncate file that does not exist in the list, so add it. list.push_back(*fiter); } } return true; } //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- bool convert_header_to_stat(const char* path, const headers_t& meta, struct stat* pst, bool forcedir) { if(!path || !pst){ return false; } *pst = {}; 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 struct timespec mtime = get_mtime(meta); if(pst->st_mtime < 0){ pst->st_mtime = 0L; }else{ if(mtime.tv_sec < 0){ mtime.tv_sec = 0; mtime.tv_nsec = 0; } set_timespec_to_stat(*pst, stat_time_type::MTIME, mtime); } // ctime struct timespec ctime = get_ctime(meta); if(pst->st_ctime < 0){ pst->st_ctime = 0L; }else{ if(ctime.tv_sec < 0){ ctime.tv_sec = 0; ctime.tv_nsec = 0; } set_timespec_to_stat(*pst, stat_time_type::CTIME, ctime); } // atime struct timespec atime = get_atime(meta); if(pst->st_atime < 0){ pst->st_atime = 0L; }else{ if(atime.tv_sec < 0){ atime.tv_sec = 0; atime.tv_nsec = 0; } set_timespec_to_stat(*pst, stat_time_type::ATIME, atime); } // size if(S_ISDIR(pst->st_mode)){ pst->st_size = 4096; }else{ 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: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
25,790
C++
.cpp
774
26.293282
167
0.570608
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,446
s3fs.cpp
s3fs-fuse_s3fs-fuse/src/s3fs.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <algorithm> #include <atomic> #include <cerrno> #include <cstdio> #include <cstdlib> #include <limits> #include <memory> #include <mutex> #include <set> #include <string> #include <unistd.h> #include <utility> #include <dirent.h> #include <sys/types.h> #include <sys/wait.h> #include <getopt.h> #include "common.h" #include "s3fs.h" #include "s3fs_logger.h" #include "metaheader.h" #include "fdcache.h" #include "fdcache_auto.h" #include "fdcache_stat.h" #include "curl.h" #include "curl_multi.h" #include "s3objlist.h" #include "cache.h" #include "addhead.h" #include "sighandlers.h" #include "s3fs_xml.h" #include "string_util.h" #include "s3fs_auth.h" #include "s3fs_cred.h" #include "s3fs_help.h" #include "s3fs_util.h" #include "s3fs_threadreqs.h" #include "mpu_util.h" #include "threadpoolman.h" //------------------------------------------------------------------- // Symbols //------------------------------------------------------------------- #if !defined(ENOATTR) #define ENOATTR ENODATA #endif enum class dirtype : int8_t { UNKNOWN = -1, NEW = 0, OLD = 1, FOLDER = 2, NOOBJ = 3, }; //------------------------------------------------------------------- // Static variables //------------------------------------------------------------------- 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::unique_ptr<S3fsCred> ps3fscred; // using only in this file static std::string mimetype_file; 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 is_use_xattr = false; static off_t multipart_threshold = 25 * 1024 * 1024; static int64_t singlepart_copy_limit = 512 * 1024 * 1024; static bool is_specified_endpoint = false; static int s3fs_init_deferred_exit_status = 0; static bool support_compat_dir = false;// default does not support compatibility directory type static int max_keys_list_object = 1000;// default is 1000 static off_t max_dirty_data = 5LL * 1024LL * 1024LL * 1024LL; static bool use_wtf8 = false; static off_t fake_diskfree_size = -1; // default is not set(-1) static int max_thread_count = 5; // default is 5 static bool update_parent_dir_stat= false; // default not updating parent directory stats static fsblkcnt_t bucket_block_count; // advertised block count of the bucket static unsigned long s3fs_block_size = 16 * 1024 * 1024; // s3fs block size is 16MB //------------------------------------------------------------------- // Global functions : prototype //------------------------------------------------------------------- int put_headers(const char* path, headers_t& meta, bool is_copy, bool use_st_size = true); // [NOTE] global function because this is called from FdEntity class //------------------------------------------------------------------- // Static functions : prototype //------------------------------------------------------------------- static bool is_special_name_folder_object(const char* path); static int chk_dir_object_type(const char* path, std::string& newpath, std::string& nowpath, std::string& nowcache, headers_t* pmeta = nullptr, dirtype* pDirType = nullptr); static int remove_old_type_dir(const std::string& path, dirtype type); static int get_object_attribute(const char* path, struct stat* pstbuf, headers_t* pmeta = nullptr, bool overcheck = true, bool* pisforce = nullptr, bool add_no_truncate_cache = false); 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 int get_local_fent(AutoFdEntity& autoent, FdEntity **entity, const char* path, int flags = O_RDONLY, bool is_load = false); static int readdir_multi_head(const char* path, const 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 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, const struct timespec& ts_atime, const struct timespec& ts_mtime, const struct timespec& ts_ctime, uid_t uid, gid_t gid, const char* pxattrvalue); static int rename_object(const char* from, const char* to, bool update_ctime); static int rename_object_nocopy(const char* from, const char* to, bool update_ctime); static int clone_directory_object(const char* from, const char* to, bool update_ctime, const char* pxattrvalue); static int rename_directory(const char* from, const char* to); static int update_mctime_parent_directory(const char* _path); static int remote_mountpath_exists(const char* path, bool compat_dir); static bool get_meta_xattr_value(const char* path, std::string& rawvalue); static bool get_parent_meta_xattr_value(const char* path, std::string& rawvalue); static bool get_xattr_posix_key_value(const char* path, std::string& xattrvalue, bool default_key); static bool build_inherited_xattr_value(const char* path, std::string& xattrvalue); static bool parse_xattr_keyval(const std::string& xattrpair, std::string& key, std::string* pval); static size_t parse_xattrs(const std::string& strxattrs, xattrs_t& xattrs); static std::string raw_build_xattrs(const xattrs_t& xattrs); static std::string build_xattrs(const xattrs_t& xattrs); static int s3fs_check_service(); static bool set_mountpoint_attribute(struct stat& mpst); static int set_bucket(const std::string& arg); static int my_fuse_opt_proc(void* data, const char* arg, int key, struct fuse_args* outargs); static fsblkcnt_t parse_bucket_size(std::string max_size); static bool is_cmd_exists(const std::string& command); static int print_umount_message(const std::string& mp, bool force) __attribute__ ((unused)); //------------------------------------------------------------------- // 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); //------------------------------------------------------------------- // Classes //------------------------------------------------------------------- // // A flag indicating whether the mount point has a stat // // [NOTE] // The flag is accessed from child threads, so std::atomic is used for exclusive control of flags. static std::atomic<bool> has_mp_stat; //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- static bool IS_REPLACEDIR(dirtype type) { return dirtype::OLD == type || dirtype::FOLDER == type || dirtype::NOOBJ == type; } static bool IS_RMTYPEDIR(dirtype type) { return dirtype::OLD == type || dirtype::FOLDER == type; } static bool IS_CREATE_MP_STAT(const char* path) { // [NOTE] has_mp_stat is set in get_object_attribute() return (path != nullptr && 0 == strcmp(path, "/") && !has_mp_stat); } static bool is_special_name_folder_object(const char* path) { if(!support_compat_dir){ // s3fs does not support compatibility directory type("_$folder$" etc) now, // thus always returns false. return false; } if(!path || '\0' == path[0]){ return false; } if(0 == strcmp(path, "/") && mount_prefix.empty()){ // the path is the mount point which is the bucket root return false; } std::string strpath = path; headers_t header; if(std::string::npos == strpath.find("_$folder$", 0)){ if('/' == *strpath.rbegin()){ strpath.erase(strpath.length() - 1); } strpath += "_$folder$"; } // send request if(0 != head_request(strpath, 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, std::string& newpath, std::string& nowpath, std::string& nowcache, headers_t* pmeta, dirtype* pDirType) { dirtype TypeTmp = dirtype::UNKNOWN; int result = -1; bool isforce = false; dirtype* pType = pDirType ? pDirType : &TypeTmp; // Normalize new path. newpath = path; if('/' != *newpath.rbegin()){ std::string::size_type Pos; if(std::string::npos != (Pos = newpath.find("_$folder$", 0))){ newpath.erase(Pos); } newpath += "/"; } // Always check "dir/" at first. if(0 == (result = get_object_attribute(newpath.c_str(), nullptr, pmeta, false, &isforce))){ // Found "dir/" cache --> Check for "_$folder$", "no dir object" nowcache = newpath; if(is_special_name_folder_object(newpath.c_str())){ // check support_compat_dir in this function // "_$folder$" type. (*pType) = dirtype::FOLDER; nowpath.erase(newpath.length() - 1); nowpath += "_$folder$"; // cut and add }else if(isforce){ // "no dir object" type. (*pType) = dirtype::NOOBJ; nowpath = ""; }else{ nowpath = newpath; if(!nowpath.empty() && '/' == *nowpath.rbegin()){ // "dir/" type (*pType) = dirtype::NEW; }else{ // "dir" type (*pType) = dirtype::OLD; } } }else if(support_compat_dir){ // Check "dir" when support_compat_dir is enabled nowpath.erase(newpath.length() - 1); if(0 == (result = get_object_attribute(nowpath.c_str(), nullptr, 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 object" 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". // (come here is that support_compat_dir is enabled) nowcache = ""; // This case is no cache. 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; } static int remove_old_type_dir(const std::string& path, dirtype type) { if(IS_RMTYPEDIR(type)){ int result; if(0 != (result = delete_request(path))){ return result; } // succeed removing or not found the directory }else{ // nothing to do } return 0; } // // 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$" // // Special two case of the mount point directory: // [Case 1] the mount point is the root of the bucket: // 1) "/" // // [Case 2] the mount point is a directory path(ex. foo) below the bucket: // 1) "foo" // 2) "foo/" // 3) "foo_$folder$" // static int get_object_attribute(const char* path, struct stat* pstbuf, headers_t* pmeta, bool overcheck, bool* pisforce, bool add_no_truncate_cache) { int result = -1; struct stat tmpstbuf; struct stat* pstat = pstbuf ? pstbuf : &tmpstbuf; headers_t tmpHead; headers_t* pheader = pmeta ? pmeta : &tmpHead; std::string strpath; bool forcedir = false; bool is_mountpoint = false; // path is the mount point bool is_bucket_mountpoint = false; // path is the mount point which is the bucket root std::string::size_type Pos; S3FS_PRN_DBG("[path=%s]", path); if(!path || '\0' == path[0]){ return -ENOENT; } *pstat = {}; // check mount point if(0 == strcmp(path, "/") || 0 == strcmp(path, ".")){ is_mountpoint = true; if(mount_prefix.empty()){ is_bucket_mountpoint = true; } // default stat for mount point if the directory stat file is not existed. 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; } // Check cache. pisforce = (nullptr != pisforce ? pisforce : &forcedir); (*pisforce) = false; strpath = path; if(support_compat_dir && overcheck && std::string::npos != (Pos = strpath.find("_$folder$", 0))){ strpath.erase(Pos); strpath += "/"; } // [NOTE] // For mount points("/"), the Stat cache key name is "/". // if(StatCache::getStatCacheData()->GetStat(strpath, pstat, pheader, overcheck, pisforce)){ if(is_mountpoint){ // if mount point, we need to set this. pstat->st_nlink = 1; // see fuse faq } return 0; } if(StatCache::getStatCacheData()->IsNoObjectCache(strpath)){ // there is the path in the cache for no object, it is no object. return -ENOENT; } // set query(head request) path if(is_bucket_mountpoint){ // [NOTE] // This is a special process for mount point // The path is "/" for mount points. // If the bucket mounted at a mount point, we try to find "/" object under // the bucket for mount point's stat. // In this case, we will send the request "HEAD // HTTP /1.1" to S3 server. // // If the directory under the bucket is mounted, it will be sent // "HEAD /<directories ...>/ HTTP/1.1", so we do not need to change path at // here. // strpath = "//"; // strpath is "//" }else{ strpath = path; } // get headers result = head_request(strpath, *pheader); // if not found target path object, do over checking if(-EPERM == result){ // [NOTE] // In case of a permission error, it exists in directory // file list but inaccessible. So there is a problem that // it will send a HEAD request every time, because it is // not registered in the Stats cache. // Therefore, even if the file has a permission error, it // should be registered in the Stats cache. However, if // the response without modifying is registered in the // cache, the file permission will be 0644(umask dependent) // because the meta header does not exist. // Thus, set the mode of 0000 here in the meta header so // that s3fs can print a permission error when the file // is actually accessed. // It is better not to set meta header other than mode, // so do not do it. // (*pheader)["x-amz-meta-mode"] = "0"; }else if(0 != result){ if(overcheck && !is_bucket_mountpoint){ // when support_compat_dir is disabled, strpath maybe have "_$folder$". if('/' != *strpath.rbegin() && std::string::npos == strpath.find("_$folder$", 0)){ // now path is "object", do check "object/" for over checking strpath += "/"; // re-get headers result = head_request(strpath, *pheader); } if(support_compat_dir && 0 != result){ // now path is "object/", do check "object_$folder$" for over checking strpath.erase(strpath.length() - 1); strpath += "_$folder$"; // re-get headers result = head_request(strpath, *pheader); // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(0 != result){ // cut "_$folder$" for over checking "no dir object" after here if(std::string::npos != (Pos = strpath.find("_$folder$", 0))){ strpath.erase(Pos); } } } } if(0 != result && std::string::npos == strpath.find("_$folder$", 0)){ // now path is "object" or "object/", do check "no dir object" which is not object but has only children. // // [NOTE] // If the path is mount point and there is no Stat information file for it, we need this process. // if('/' == *strpath.rbegin()){ strpath.erase(strpath.length() - 1); } if(-ENOTEMPTY == directory_empty(strpath.c_str())){ // found "no dir object". strpath += "/"; *pisforce = true; result = 0; } } }else{ if('/' != *strpath.rbegin() && std::string::npos == strpath.find("_$folder$", 0) && is_need_check_obj_detail(*pheader)){ // check a case of that "object" does not have attribute and "object" is possible to be directory. if(-ENOTEMPTY == directory_empty(strpath.c_str())){ // found "no dir object". strpath += "/"; *pisforce = true; result = 0; } } } // set headers for mount point from default stat if(is_mountpoint){ if(0 != result || pheader->empty()){ has_mp_stat = false; // [NOTE] // If mount point and no stat information file, create header // information from the default stat. // (*pheader)["Content-Type"] = S3fsCurl::LookupMimeType(strpath); (*pheader)["x-amz-meta-uid"] = std::to_string(pstat->st_uid); (*pheader)["x-amz-meta-gid"] = std::to_string(pstat->st_gid); (*pheader)["x-amz-meta-mode"] = std::to_string(pstat->st_mode); (*pheader)["x-amz-meta-atime"] = std::to_string(pstat->st_atime); (*pheader)["x-amz-meta-ctime"] = std::to_string(pstat->st_ctime); (*pheader)["x-amz-meta-mtime"] = std::to_string(pstat->st_mtime); result = 0; }else{ has_mp_stat = true; } } // [NOTE] // If the file is listed but not allowed access, put it in // the positive cache instead of the negative cache. // // When mount points, the following error does not occur. // if(0 != result && -EPERM != result){ // finally, "path" object did not find. Add no object cache. strpath = path; // reset original StatCache::getStatCacheData()->AddNoObjectCache(strpath); return result; } // set cache key if(is_bucket_mountpoint){ strpath = "/"; }else if(std::string::npos != (Pos = strpath.find("_$folder$", 0))){ // if path has "_$folder$", need to cut it. strpath.erase(Pos); strpath += "/"; } // Set into cache // // [NOTE] // When add_no_truncate_cache is true, the stats is always cached. // This cached stats is only removed by DelStat(). // This is necessary for the case to access the attribute of opened file. // (ex. getxattr() is called while writing to the opened file.) // if(add_no_truncate_cache || 0 != StatCache::getStatCacheData()->GetCacheSize()){ // add into stat cache if(!StatCache::getStatCacheData()->AddStat(strpath, (*pheader), forcedir, add_no_truncate_cache)){ 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; } } if(is_mountpoint){ // if mount point, we need to set this. pstat->st_nlink = 1; // see fuse faq } 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: nullptr 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(nullptr == (pcxt = fuse_get_context())){ return -EIO; } S3FS_PRN_DBG("[pid=%u,uid=%u,gid=%u]", (unsigned int)(pcxt->pid), (unsigned int)(pcxt->uid), (unsigned int)(pcxt->gid)); if(0 != (result = get_object_attribute(path, pst))){ // If there is not the target file(object), result 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; } else if(1 == is_uid_include_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 -EACCES; } } 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); const struct fuse_context* pcxt; S3FS_PRN_DBG("[path=%s]", path); if(nullptr == (pcxt = fuse_get_context())){ return -EIO; } if(0 != (result = get_object_attribute(path, pst))){ // If there is not the target file(object), result 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) { std::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); !parent.empty(); parent = mydirname(parent)){ if(parent == "."){ parent = "/"; } if(0 != (result = check_object_access(parent.c_str(), X_OK, nullptr))){ 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, nullptr))){ 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, std::string& ssevalue) { if(!path){ return false; } headers_t meta; if(0 != get_object_attribute(path, nullptr, &meta)){ S3FS_PRN_ERR("Failed to get object(%s) headers", path); return false; } ssetype = sse_type_t::SSE_DISABLE; ssevalue.clear(); for(auto iter = meta.cbegin(); iter != meta.cend(); ++iter){ std::string key = (*iter).first; if(0 == strcasecmp(key.c_str(), "x-amz-server-side-encryption") && 0 == strcasecmp((*iter).second.c_str(), "AES256")){ ssetype = sse_type_t::SSE_S3; }else if(0 == strcasecmp(key.c_str(), "x-amz-server-side-encryption-aws-kms-key-id")){ ssetype = sse_type_t::SSE_KMS; ssevalue = (*iter).second; }else if(0 == strcasecmp(key.c_str(), "x-amz-server-side-encryption-customer-key-md5")){ ssetype = sse_type_t::SSE_C; ssevalue = (*iter).second; } } return true; } static int get_local_fent(AutoFdEntity& autoent, FdEntity **entity, const char* path, int flags, bool is_load) { int result; struct stat stobj; FdEntity* ent; headers_t meta; S3FS_PRN_INFO2("[path=%s]", path); if(0 != (result = get_object_attribute(path, &stobj, &meta))){ return result; } // open struct timespec st_mctime; if(!S_ISREG(stobj.st_mode) && !S_ISLNK(stobj.st_mode)){ st_mctime = S3FS_OMIT_TS; }else{ set_stat_to_timespec(stobj, stat_time_type::MTIME, st_mctime); } bool force_tmpfile = S_ISREG(stobj.st_mode) ? false : true; if(nullptr == (ent = autoent.Open(path, &meta, stobj.st_size, st_mctime, flags, force_tmpfile, true, false))){ S3FS_PRN_ERR("Could not open file. errno(%d)", errno); return -EIO; } // load if(is_load && !ent->LoadAll(autoent.GetPseudoFd())){ S3FS_PRN_ERR("Could not load file. errno(%d)", errno); autoent.Close(); return -EIO; } *entity = ent; return 0; } // // create or update s3 meta // @return fuse return code // int put_headers(const char* path, headers_t& meta, bool is_copy, bool use_st_size) { int result; off_t size; std::string strpath; S3FS_PRN_INFO2("[path=%s]", path); if(0 == strcmp(path, "/") && mount_prefix.empty()){ strpath = "//"; // for the mount point that is bucket root, change "/" to "//". }else{ strpath = path; } // files larger than 5GB must be modified via the multipart interface // call use_st_size as false when the file does not exist(ex. rename object) if(use_st_size && '/' != *strpath.rbegin()){ // directory object("dir/") is always 0(Content-Length = 0) struct stat buf; if(0 != (result = get_object_attribute(path, &buf))){ return result; } size = buf.st_size; }else{ size = get_size(meta); } if(!nocopyapi && !nomultipart && size >= multipart_threshold){ // [TODO] // This object will be removed after removing S3fsMultiCurl // S3fsCurl s3fscurl(true); if(0 != (result = s3fscurl.MultipartHeadRequest(strpath.c_str(), size, meta))){ return result; } }else{ // send put head request if(0 != (result = put_head_request(strpath, meta, is_copy))){ return result; } } return 0; } static int s3fs_getattr(const char* _path, struct stat* stbuf) { WTF8_ENCODE(path) int result; #if defined(__APPLE__) FUSE_CTX_DBG("[path=%s]", path); #else FUSE_CTX_INFO("[path=%s]", path); #endif // 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 should be instead. // (See: Issue 241) if(stbuf){ AutoFdEntity autoent; const FdEntity* ent; if(nullptr != (ent = autoent.OpenExistFdEntity(path))){ struct stat tmpstbuf; if(ent->GetStats(tmpstbuf)){ stbuf->st_size = tmpstbuf.st_size; } } if(0 == strcmp(path, "/")){ stbuf->st_size = 4096; } 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; } WTF8_ENCODE(path) std::string strValue; FUSE_CTX_INFO("[path=%s]", path); // check symbolic link cache if(!StatCache::getStatCacheData()->GetSymlink(path, strValue)){ // not found in cache, then open the path { // scope for AutoFdEntity AutoFdEntity autoent; FdEntity* ent; int result; if(0 != (result = get_local_fent(autoent, &ent, path, O_RDONLY))){ S3FS_PRN_ERR("could not get fent(file=%s)", path); return result; } // Get size off_t readsize; if(!ent->GetSize(readsize)){ S3FS_PRN_ERR("could not get file size(file=%s)", path); return -EIO; } if(static_cast<off_t>(size) <= readsize){ readsize = size - 1; } // Read ssize_t ressize; if(0 > (ressize = ent->Read(autoent.GetPseudoFd(), buf, 0, readsize))){ S3FS_PRN_ERR("could not read file(file=%s, ressize=%zd)", path, ressize); return static_cast<int>(ressize); } buf[ressize] = '\0'; } // check buf if it has space words. strValue = trim(buf); // decode wtf8. This will always be shorter if(use_wtf8){ strValue = s3fs_wtf8_decode(strValue); } // add symbolic link cache if(!StatCache::getStatCacheData()->AddSymlink(path, strValue)){ S3FS_PRN_ERR("failed to add symbolic link cache for %s", path); } } // copy result strncpy(buf, strValue.c_str(), size - 1); buf[size - 1] = '\0'; S3FS_MALLOCTRIM(0); return 0; } // 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); std::string strnow = s3fs_str_realtime(); headers_t meta; meta["Content-Type"] = S3fsCurl::LookupMimeType(path); meta["x-amz-meta-uid"] = std::to_string(uid); meta["x-amz-meta-gid"] = std::to_string(gid); meta["x-amz-meta-mode"] = std::to_string(mode); meta["x-amz-meta-atime"] = strnow; meta["x-amz-meta-ctime"] = strnow; meta["x-amz-meta-mtime"] = strnow; int result; if(0 != (result = put_request(std::string(SAFESTRPTR(path)), meta, -1, true/* ahbe */))){ return result; } return 0; } static int s3fs_mknod(const char *_path, mode_t mode, dev_t rdev) { WTF8_ENCODE(path) int result; struct fuse_context* pcxt; FUSE_CTX_INFO("[path=%s][mode=%04o][dev=%llu]", path, mode, (unsigned long long)rdev); if(nullptr == (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); // update parent directory timestamp int update_result; if(0 != (update_result = update_mctime_parent_directory(path))){ S3FS_PRN_ERR("succeed to mknod the file(%s), but could not update timestamp of its parent directory(result=%d).", path, update_result); } S3FS_MALLOCTRIM(0); return result; } static int s3fs_create(const char* _path, mode_t mode, struct fuse_file_info* fi) { WTF8_ENCODE(path) int result; const struct fuse_context* pcxt; FUSE_CTX_INFO("[path=%s][mode=%04o][flags=0x%x]", path, mode, fi->flags); if(nullptr == (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, nullptr); if(-ENOENT == result){ if(0 != (result = check_parent_object_access(path, W_OK))){ return result; } }else if(0 != result){ return result; } std::string strnow = s3fs_str_realtime(); headers_t meta; meta["Content-Length"] = "0"; meta["x-amz-meta-uid"] = std::to_string(pcxt->uid); meta["x-amz-meta-gid"] = std::to_string(pcxt->gid); meta["x-amz-meta-mode"] = std::to_string(mode); meta["x-amz-meta-atime"] = strnow; meta["x-amz-meta-mtime"] = strnow; meta["x-amz-meta-ctime"] = strnow; std::string xattrvalue; if(build_inherited_xattr_value(path, xattrvalue)){ S3FS_PRN_DBG("Set xattrs = %s", urlDecode(xattrvalue).c_str()); meta["x-amz-meta-xattr"] = xattrvalue; } // [NOTE] set no_truncate flag // At this point, the file has not been created(uploaded) and // the data is only present in the Stats cache. // The Stats cache should not be deleted automatically by // timeout. If this stats is deleted, s3fs will try to get it // from the server with a Head request and will get an // unexpected error because the result object does not exist. // if(!StatCache::getStatCacheData()->AddStat(path, meta, false, true)){ return -EIO; } AutoFdEntity autoent; FdEntity* ent; int error = 0; if(nullptr == (ent = autoent.Open(path, &meta, 0, S3FS_OMIT_TS, fi->flags, false, true, false, &error))){ StatCache::getStatCacheData()->DelStat(path); return error; } ent->MarkDirtyNewFile(); fi->fh = autoent.Detach(); // KEEP fdentity open; S3FS_MALLOCTRIM(0); return 0; } static int create_directory_object(const char* path, mode_t mode, const struct timespec& ts_atime, const struct timespec& ts_mtime, const struct timespec& ts_ctime, uid_t uid, gid_t gid, const char* pxattrvalue) { S3FS_PRN_INFO1("[path=%s][mode=%04o][atime=%s][mtime=%s][ctime=%s][uid=%u][gid=%u]", path, mode, str(ts_atime).c_str(), str(ts_mtime).c_str(), str(ts_ctime).c_str(), (unsigned int)uid, (unsigned int)gid); if(!path || '\0' == path[0]){ return -EINVAL; } std::string tpath = path; if('/' != *tpath.rbegin()){ tpath += "/"; }else if("/" == tpath && mount_prefix.empty()){ tpath = "//"; // for the mount point that is bucket root, change "/" to "//". } headers_t meta; meta["x-amz-meta-uid"] = std::to_string(uid); meta["x-amz-meta-gid"] = std::to_string(gid); meta["x-amz-meta-mode"] = std::to_string(mode); meta["x-amz-meta-atime"] = str(ts_atime); meta["x-amz-meta-mtime"] = str(ts_mtime); meta["x-amz-meta-ctime"] = str(ts_ctime); if(pxattrvalue){ S3FS_PRN_DBG("Set xattrs = %s", urlDecode(pxattrvalue).c_str()); meta["x-amz-meta-xattr"] = pxattrvalue; } int result; if(0 != (result = put_request(tpath, meta, -1, false/* ahbe */))){ return result; } return 0; } static int s3fs_mkdir(const char* _path, mode_t mode) { WTF8_ENCODE(path) int result; struct fuse_context* pcxt; FUSE_CTX_INFO("[path=%s][mode=%04o]", path, mode); if(nullptr == (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, nullptr))){ if(0 == result){ result = -EEXIST; } return result; } std::string xattrvalue; const char* pxattrvalue; if(get_parent_meta_xattr_value(path, xattrvalue)){ pxattrvalue = xattrvalue.c_str(); }else{ pxattrvalue = nullptr; } struct timespec now; s3fs_realtime(now); result = create_directory_object(path, mode, now, now, now, pcxt->uid, pcxt->gid, pxattrvalue); StatCache::getStatCacheData()->DelStat(path); // update parent directory timestamp int update_result; if(0 != (update_result = update_mctime_parent_directory(path))){ S3FS_PRN_ERR("succeed to create the directory(%s), but could not update timestamp of its parent directory(result=%d).", path, update_result); } S3FS_MALLOCTRIM(0); return result; } static int s3fs_unlink(const char* _path) { WTF8_ENCODE(path) int result; FUSE_CTX_INFO("[path=%s]", path); if(0 != (result = check_parent_object_access(path, W_OK | X_OK))){ return result; } if(0 != (result = delete_request(std::string(SAFESTRPTR(path))))){ return result; } StatCache::getStatCacheData()->DelStat(path); StatCache::getStatCacheData()->DelSymlink(path); FdManager::DeleteCacheFile(path); // update parent directory timestamp int update_result; if(0 != (update_result = update_mctime_parent_directory(path))){ S3FS_PRN_ERR("succeed to remove the file(%s), but could not update timestamp of its parent directory(result=%d).", path, update_result); } 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) { WTF8_ENCODE(path) int result; std::string strpath; struct stat stbuf; FUSE_CTX_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.rbegin()){ strpath += "/"; } // delete request result = delete_request(strpath); StatCache::getStatCacheData()->DelStat(strpath); // 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.rbegin()){ strpath.erase(strpath.length() - 1); } if(0 == get_object_attribute(strpath.c_str(), &stbuf, nullptr, false)){ if(S_ISDIR(stbuf.st_mode)){ // Found "dir" object. // delete request result = delete_request(strpath); StatCache::getStatCacheData()->DelStat(strpath); } } // 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 once(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$"; // delete request result = delete_request(strpath); } // update parent directory timestamp int update_result; if(0 != (update_result = update_mctime_parent_directory(path))){ S3FS_PRN_ERR("succeed to remove the directory(%s), but could not update timestamp of its parent directory(result=%d).", path, update_result); } S3FS_MALLOCTRIM(0); return result; } static int s3fs_symlink(const char* _from, const char* _to) { WTF8_ENCODE(from) WTF8_ENCODE(to) int result; const struct fuse_context* pcxt; FUSE_CTX_INFO("[from=%s][to=%s]", from, to); if(nullptr == (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, nullptr))){ if(0 == result){ result = -EEXIST; } return result; } std::string strnow = s3fs_str_realtime(); headers_t headers; headers["Content-Type"] = "application/octet-stream"; // Static headers["x-amz-meta-mode"] = std::to_string(S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO); headers["x-amz-meta-atime"] = strnow; headers["x-amz-meta-ctime"] = strnow; headers["x-amz-meta-mtime"] = strnow; headers["x-amz-meta-uid"] = std::to_string(pcxt->uid); headers["x-amz-meta-gid"] = std::to_string(pcxt->gid); // [NOTE] // Symbolic links do not set xattrs. // open tmpfile std::string strFrom; { // scope for AutoFdEntity AutoFdEntity autoent; FdEntity* ent; if(nullptr == (ent = autoent.Open(to, &headers, 0, S3FS_OMIT_TS, O_RDWR, true, true, false))){ S3FS_PRN_ERR("could not open tmpfile(errno=%d)", errno); return -errno; } // write(without space words) strFrom = trim(from); auto from_size = static_cast<ssize_t>(strFrom.length()); ssize_t ressize; if(from_size != (ressize = ent->Write(autoent.GetPseudoFd(), strFrom.c_str(), 0, from_size))){ if(ressize < 0){ S3FS_PRN_ERR("could not write tmpfile(errno=%d)", static_cast<int>(ressize)); return static_cast<int>(ressize); }else{ S3FS_PRN_ERR("could not write tmpfile %zd byte(errno=%d)", ressize, errno); return (0 == errno ? -EIO : -errno); } } // upload if(0 != (result = ent->Flush(autoent.GetPseudoFd(), true))){ S3FS_PRN_WARN("could not upload tmpfile(result=%d)", result); } } StatCache::getStatCacheData()->DelStat(to); if(!StatCache::getStatCacheData()->AddSymlink(to, strFrom)){ S3FS_PRN_ERR("failed to add symbolic link cache for %s", to); } // update parent directory timestamp int update_result; if(0 != (update_result = update_mctime_parent_directory(to))){ S3FS_PRN_ERR("succeed to create symbolic link(%s), but could not update timestamp of its parent directory(result=%d).", to, update_result); } S3FS_MALLOCTRIM(0); return result; } static int rename_object(const char* from, const char* to, bool update_ctime) { int result; headers_t meta; struct stat buf; S3FS_PRN_INFO1("[from=%s][to=%s]", from , to); if(0 != (result = check_parent_object_access(to, W_OK | X_OK))){ // not permit writing "to" object parent dir. return result; } if(0 != (result = check_parent_object_access(from, W_OK | X_OK))){ // not permit removing "from" object parent dir. return result; } if(0 != (result = get_object_attribute(from, &buf, &meta))){ return result; } std::string strSourcePath = (mount_prefix.empty() && 0 == strcmp("/", from)) ? "//" : from; if(update_ctime){ meta["x-amz-meta-ctime"] = s3fs_str_realtime(); } meta["x-amz-copy-source"] = urlEncodePath(service_path + S3fsCred::GetBucket() + get_realpath(strSourcePath.c_str())); meta["Content-Type"] = S3fsCurl::LookupMimeType(to); meta["x-amz-metadata-directive"] = "REPLACE"; std::string xattrvalue; if(get_meta_xattr_value(from, xattrvalue)){ S3FS_PRN_DBG("Set xattrs = %s", urlDecode(xattrvalue).c_str()); meta["x-amz-meta-xattr"] = xattrvalue; } // [NOTE] // If it has a cache, open it first and leave it open until rename. // The cache is renamed after put_header, because it must be open // at the time of renaming. { // update time AutoFdEntity autoent; FdEntity* ent; if(nullptr == (ent = autoent.OpenExistFdEntity(from))){ // no opened fd // get mtime/ctime/atime from meta struct timespec mtime = get_mtime(meta); struct timespec ctime = get_ctime(meta); struct timespec atime = get_atime(meta); if(mtime.tv_sec < 0){ mtime.tv_sec = 0L; mtime.tv_nsec = 0L; } if(ctime.tv_sec < 0){ ctime.tv_sec = 0L; ctime.tv_nsec = 0L; } if(atime.tv_sec < 0){ atime.tv_sec = 0L; atime.tv_nsec = 0L; } if(FdManager::IsCacheDir()){ // create cache file if be needed // // [NOTE] // Do not specify "S3FS_OMIT_TS" for mctime parameter. // This is because if the cache file does not exist, the pagelist for it // will be recreated, but the entire file area indicated by this pagelist // will be in the "modified" state. // This does not affect the rename process, but the cache information in // the "modified" state remains, making it impossible to read the file correctly. // ent = autoent.Open(from, &meta, buf.st_size, mtime, O_RDONLY, false, true, false); } if(ent){ ent->SetMCtime(mtime, ctime); ent->SetAtime(atime); } } } // copy if(0 != (result = put_headers(to, meta, true, /* use_st_size= */ false))){ return result; } // rename FdManager::get()->Rename(from, to); // Remove file result = s3fs_unlink(from); StatCache::getStatCacheData()->DelStat(to); return result; } static int rename_object_nocopy(const char* from, const char* to, bool update_ctime) { int result; FUSE_CTX_INFO1("[from=%s][to=%s]", from , to); if(0 != (result = check_parent_object_access(to, W_OK | X_OK))){ // not permit writing "to" object parent dir. return result; } if(0 != (result = check_parent_object_access(from, W_OK | X_OK))){ // not permit removing "from" object parent dir. return result; } // open & load { // scope for AutoFdEntity AutoFdEntity autoent; FdEntity* ent; if(0 != (result = get_local_fent(autoent, &ent, from, O_RDWR, true))){ S3FS_PRN_ERR("could not open and read file(%s)", from); return result; } // Set header if(!ent->SetContentType(to)){ S3FS_PRN_ERR("could not set content-type for %s", to); return -EIO; } // update ctime if(update_ctime){ struct timespec ts; s3fs_realtime(ts); ent->SetCtime(ts); } // upload if(0 != (result = ent->RowFlush(autoent.GetPseudoFd(), to, true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", to, result); return result; } } FdManager::get()->Rename(from, to); // Remove file result = s3fs_unlink(from); // Stats StatCache::getStatCacheData()->DelStat(to); 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 permit writing "to" object parent dir. return result; } if(0 != (result = check_parent_object_access(from, W_OK | X_OK))){ // not permit removing "from" object parent dir. return result; } if(0 != (result = get_object_attribute(from, &buf, &meta, false))){ return result; } // [TODO] // This object will be removed after removing S3fsMultiCurl // S3fsCurl s3fscurl(true); if(0 != (result = s3fscurl.MultipartRenameRequest(from, to, meta, buf.st_size))){ return result; } s3fscurl.DestroyCurlHandle(); // Rename cache file FdManager::get()->Rename(from, to); // Remove file result = s3fs_unlink(from); // Stats StatCache::getStatCacheData()->DelStat(to); return result; } static int clone_directory_object(const char* from, const char* to, bool update_ctime, const char* pxattrvalue) { 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; } struct timespec ts_atime; struct timespec ts_mtime; struct timespec ts_ctime; set_stat_to_timespec(stbuf, stat_time_type::ATIME, ts_atime); set_stat_to_timespec(stbuf, stat_time_type::MTIME, ts_mtime); if(update_ctime){ s3fs_realtime(ts_ctime); }else{ set_stat_to_timespec(stbuf, stat_time_type::CTIME, ts_ctime); } result = create_directory_object(to, stbuf.st_mode, ts_atime, ts_mtime, ts_ctime, stbuf.st_uid, stbuf.st_gid, pxattrvalue); StatCache::getStatCacheData()->DelStat(to); return result; } static int rename_directory(const char* from, const char* to) { S3ObjList head; s3obj_list_t headlist; std::string strfrom = from ? from : ""; // from is without "/". std::string strto = to ? to : ""; // to is without "/" too. std::string basepath = strfrom + "/"; std::string newpath; // should be from name(not used) std::string nowcache; // now cache path(not used) dirtype DirType; bool normdir; std::vector<mvnode> mvnodes; 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, nullptr, &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. } mvnodes.emplace_back(strfrom, strto, true, normdir); }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, nullptr))){ S3FS_PRN_ERR("list_bucket returns error."); return result; } head.GetNameList(headlist); // get name without "/". StatCache::getStatCacheData()->GetNotruncateCache(basepath, headlist); // Add notruncate file name from stat cache S3ObjList::MakeHierarchizedList(headlist, false); // add hierarchized dir. s3obj_list_t::const_iterator liter; for(liter = headlist.cbegin(); headlist.cend() != liter; ++liter){ // make "from" and "to" object name. std::string from_name = basepath + (*liter); std::string to_name = strto + (*liter); std::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, nullptr)){ 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, nullptr, &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 mvnodes.emplace_back(from_name, to_name, is_dir, normdir); } std::sort(mvnodes.begin(), mvnodes.end(), [](const mvnode& a, const mvnode& b) { return a.old_path < b.old_path; }); // // rename // // rename directory objects. for(auto mn_cur = mvnodes.cbegin(); mn_cur != mvnodes.cend(); ++mn_cur){ if(mn_cur->is_dir && !mn_cur->old_path.empty()){ std::string xattrvalue; const char* pxattrvalue; if(get_meta_xattr_value(mn_cur->old_path.c_str(), xattrvalue)){ pxattrvalue = xattrvalue.c_str(); }else{ pxattrvalue = nullptr; } // [NOTE] // The ctime is updated only for the top (from) directory. // Other than that, it will not be updated. // if(0 != (result = clone_directory_object(mn_cur->old_path.c_str(), mn_cur->new_path.c_str(), (strfrom == mn_cur->old_path), pxattrvalue))){ S3FS_PRN_ERR("clone_directory_object returned an error(%d)", result); return result; } } } // iterate over the list - copy the files with rename_object // does a safe copy - copies first and then deletes old for(auto mn_cur = mvnodes.cbegin(); mn_cur != mvnodes.cend(); ++mn_cur){ if(!mn_cur->is_dir){ if(!nocopyapi && !norenameapi){ result = rename_object(mn_cur->old_path.c_str(), mn_cur->new_path.c_str(), false); // keep ctime }else{ result = rename_object_nocopy(mn_cur->old_path.c_str(), mn_cur->new_path.c_str(), false); // keep ctime } if(0 != result){ S3FS_PRN_ERR("rename_object returned an error(%d)", result); return result; } } } // Iterate over old the directories, bottoms up and remove for(auto mn_cur = mvnodes.rbegin(); mn_cur != mvnodes.rend(); ++mn_cur){ if(mn_cur->is_dir && !mn_cur->old_path.empty()){ if(!(mn_cur->is_normdir)){ if(0 != (result = s3fs_rmdir(mn_cur->old_path.c_str()))){ S3FS_PRN_ERR("s3fs_rmdir returned an error(%d)", result); return result; } }else{ // cache clear. StatCache::getStatCacheData()->DelStat(mn_cur->old_path); } } } return 0; } static int s3fs_rename(const char* _from, const char* _to) { WTF8_ENCODE(from) WTF8_ENCODE(to) struct stat buf; int result; FUSE_CTX_INFO("[from=%s][to=%s]", from, to); if(0 != (result = check_parent_object_access(to, W_OK | X_OK))){ // not permit writing "to" object parent dir. return result; } if(0 != (result = check_parent_object_access(from, W_OK | X_OK))){ // not permit removing "from" object parent dir. return result; } if(0 != (result = get_object_attribute(from, &buf, nullptr))){ return result; } if(0 != (result = directory_empty(to))){ return result; } // flush pending writes if file is open { // scope for AutoFdEntity AutoFdEntity autoent; FdEntity* ent; if(nullptr != (ent = autoent.OpenExistFdEntity(from, O_RDWR))){ if(0 != (result = ent->Flush(autoent.GetPseudoFd(), true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", to, result); return result; } StatCache::getStatCacheData()->DelStat(from); } } // 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, true); // update ctime }else{ result = rename_object_nocopy(from, to, true); // update ctime } } // update parent directory timestamp // // [NOTE] // already updated timestamp for original path in above functions. // int update_result; if(0 != (update_result = update_mctime_parent_directory(to))){ S3FS_PRN_ERR("succeed to create the file/directory(%s), but could not update timestamp of its parent directory(result=%d).", to, update_result); } S3FS_MALLOCTRIM(0); return result; } static int s3fs_link(const char* _from, const char* _to) { WTF8_ENCODE(from) WTF8_ENCODE(to) FUSE_CTX_INFO("[from=%s][to=%s]", from, to); return -ENOTSUP; } static int s3fs_chmod(const char* _path, mode_t mode) { WTF8_ENCODE(path) int result; std::string strpath; std::string newpath; std::string nowcache; headers_t meta; struct stat stbuf; dirtype nDirType = dirtype::UNKNOWN; FUSE_CTX_INFO("[path=%s][mode=%04o]", path, mode); 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(), nullptr, &meta); } if(0 != result){ return result; } if(S_ISDIR(stbuf.st_mode) && (IS_REPLACEDIR(nDirType) || IS_CREATE_MP_STAT(path))){ std::string xattrvalue; const char* pxattrvalue; if(get_meta_xattr_value(path, xattrvalue)){ pxattrvalue = xattrvalue.c_str(); }else{ pxattrvalue = nullptr; } if(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(0 != (result = remove_old_type_dir(strpath, nDirType))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") struct timespec ts_atime; struct timespec ts_mtime; struct timespec ts_ctime; set_stat_to_timespec(stbuf, stat_time_type::ATIME, ts_atime); set_stat_to_timespec(stbuf, stat_time_type::MTIME, ts_mtime); s3fs_realtime(ts_ctime); if(0 != (result = create_directory_object(newpath.c_str(), mode, ts_atime, ts_mtime, ts_ctime, stbuf.st_uid, stbuf.st_gid, pxattrvalue))){ return result; } }else{ // normal object or directory object of newer version std::string strSourcePath = (mount_prefix.empty() && "/" == strpath) ? "//" : strpath; headers_t updatemeta; updatemeta["x-amz-meta-ctime"] = s3fs_str_realtime(); updatemeta["x-amz-meta-mode"] = std::to_string(mode); updatemeta["x-amz-copy-source"] = urlEncodePath(service_path + S3fsCred::GetBucket() + get_realpath(strSourcePath.c_str())); updatemeta["x-amz-metadata-directive"] = "REPLACE"; // check opened file handle. // // If the file starts uploading by multipart when the disk capacity is insufficient, // we need to put these header after finishing upload. // Or if the file is only open, we must update to FdEntity's internal meta. // AutoFdEntity autoent; FdEntity* ent; bool need_put_header = true; if(nullptr != (ent = autoent.OpenExistFdEntity(path))){ if(ent->MergeOrgMeta(updatemeta)){ // meta is changed, but now uploading. // then the meta is pending and accumulated to be put after the upload is complete. S3FS_PRN_INFO("meta pending until upload is complete"); need_put_header = false; // If there is data in the Stats cache, update the Stats cache. StatCache::getStatCacheData()->UpdateMetaStats(strpath, updatemeta); // [NOTE] // There are cases where this function is called during the process of // creating a new file (before uploading). // In this case, a temporary cache exists in the Stat cache. // So we need to update the cache, if it exists. (see. s3fs_create and s3fs_utimens) // if(!StatCache::getStatCacheData()->AddStat(strpath, updatemeta, false, true)){ return -EIO; } } } if(need_put_header){ // not found opened file. merge_headers(meta, updatemeta, true); // upload meta directly. if(0 != (result = put_headers(strpath.c_str(), meta, true))){ return result; } StatCache::getStatCacheData()->DelStat(nowcache); } } S3FS_MALLOCTRIM(0); return 0; } static int s3fs_chmod_nocopy(const char* _path, mode_t mode) { WTF8_ENCODE(path) int result; std::string strpath; std::string newpath; std::string nowcache; struct stat stbuf; dirtype nDirType = dirtype::UNKNOWN; FUSE_CTX_INFO1("[path=%s][mode=%04o]", path, mode); 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, nullptr, &nDirType); }else{ strpath = path; nowcache = strpath; result = get_object_attribute(strpath.c_str(), nullptr, nullptr); } if(0 != result){ return result; } if(S_ISDIR(stbuf.st_mode)){ std::string xattrvalue; const char* pxattrvalue; if(get_meta_xattr_value(path, xattrvalue)){ pxattrvalue = xattrvalue.c_str(); }else{ pxattrvalue = nullptr; } if(IS_REPLACEDIR(nDirType)){ // Should rebuild all directory object // Need to remove old dir("dir" etc) and make new dir("dir/") // At first, remove directory old object if(0 != (result = remove_old_type_dir(strpath, nDirType))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") struct timespec ts_atime; struct timespec ts_mtime; struct timespec ts_ctime; set_stat_to_timespec(stbuf, stat_time_type::ATIME, ts_atime); set_stat_to_timespec(stbuf, stat_time_type::MTIME, ts_mtime); s3fs_realtime(ts_ctime); if(0 != (result = create_directory_object(newpath.c_str(), mode, ts_atime, ts_mtime, ts_ctime, stbuf.st_uid, stbuf.st_gid, pxattrvalue))){ return result; } }else{ // normal object or directory object of newer version // open & load AutoFdEntity autoent; FdEntity* ent; if(0 != (result = get_local_fent(autoent, &ent, strpath.c_str(), O_RDWR, true))){ S3FS_PRN_ERR("could not open and read file(%s)", strpath.c_str()); return result; } struct timespec ts; s3fs_realtime(ts); ent->SetCtime(ts); // Change file mode ent->SetMode(mode); // upload if(0 != (result = ent->Flush(autoent.GetPseudoFd(), true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", strpath.c_str(), result); return result; } StatCache::getStatCacheData()->DelStat(nowcache); } S3FS_MALLOCTRIM(0); return result; } static int s3fs_chown(const char* _path, uid_t uid, gid_t gid) { WTF8_ENCODE(path) int result; std::string strpath; std::string newpath; std::string nowcache; headers_t meta; struct stat stbuf; dirtype nDirType = dirtype::UNKNOWN; FUSE_CTX_INFO("[path=%s][uid=%u][gid=%u]", path, (unsigned int)uid, (unsigned int)gid); 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(), nullptr, &meta); } if(0 != result){ return result; } if(S_ISDIR(stbuf.st_mode) && (IS_REPLACEDIR(nDirType) || IS_CREATE_MP_STAT(path))){ std::string xattrvalue; const char* pxattrvalue; if(get_meta_xattr_value(path, xattrvalue)){ pxattrvalue = xattrvalue.c_str(); }else{ pxattrvalue = nullptr; } if(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(0 != (result = remove_old_type_dir(strpath, nDirType))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") struct timespec ts_atime; struct timespec ts_mtime; struct timespec ts_ctime; set_stat_to_timespec(stbuf, stat_time_type::ATIME, ts_atime); set_stat_to_timespec(stbuf, stat_time_type::MTIME, ts_mtime); s3fs_realtime(ts_ctime); if(0 != (result = create_directory_object(newpath.c_str(), stbuf.st_mode, ts_atime, ts_mtime, ts_ctime, uid, gid, pxattrvalue))){ return result; } }else{ std::string strSourcePath = (mount_prefix.empty() && "/" == strpath) ? "//" : strpath; headers_t updatemeta; updatemeta["x-amz-meta-ctime"] = s3fs_str_realtime(); updatemeta["x-amz-meta-uid"] = std::to_string(uid); updatemeta["x-amz-meta-gid"] = std::to_string(gid); updatemeta["x-amz-copy-source"] = urlEncodePath(service_path + S3fsCred::GetBucket() + get_realpath(strSourcePath.c_str())); updatemeta["x-amz-metadata-directive"] = "REPLACE"; // check opened file handle. // // If the file starts uploading by multipart when the disk capacity is insufficient, // we need to put these header after finishing upload. // Or if the file is only open, we must update to FdEntity's internal meta. // AutoFdEntity autoent; FdEntity* ent; bool need_put_header = true; if(nullptr != (ent = autoent.OpenExistFdEntity(path))){ if(ent->MergeOrgMeta(updatemeta)){ // meta is changed, but now uploading. // then the meta is pending and accumulated to be put after the upload is complete. S3FS_PRN_INFO("meta pending until upload is complete"); need_put_header = false; // If there is data in the Stats cache, update the Stats cache. StatCache::getStatCacheData()->UpdateMetaStats(strpath, updatemeta); // [NOTE] // There are cases where this function is called during the process of // creating a new file (before uploading). // In this case, a temporary cache exists in the Stat cache. // So we need to update the cache, if it exists. (see. s3fs_create and s3fs_utimens) // if(!StatCache::getStatCacheData()->AddStat(strpath, updatemeta, false, true)){ return -EIO; } } } if(need_put_header){ // not found opened file. merge_headers(meta, updatemeta, true); // upload meta directly. if(0 != (result = put_headers(strpath.c_str(), meta, true))){ return result; } StatCache::getStatCacheData()->DelStat(nowcache); } } S3FS_MALLOCTRIM(0); return 0; } static int s3fs_chown_nocopy(const char* _path, uid_t uid, gid_t gid) { WTF8_ENCODE(path) int result; std::string strpath; std::string newpath; std::string nowcache; struct stat stbuf; dirtype nDirType = dirtype::UNKNOWN; FUSE_CTX_INFO1("[path=%s][uid=%u][gid=%u]", path, (unsigned int)uid, (unsigned int)gid); 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; } // Get attributes if(S_ISDIR(stbuf.st_mode)){ result = chk_dir_object_type(path, newpath, strpath, nowcache, nullptr, &nDirType); }else{ strpath = path; nowcache = strpath; result = get_object_attribute(strpath.c_str(), nullptr, nullptr); } if(0 != result){ return result; } if(S_ISDIR(stbuf.st_mode)){ std::string xattrvalue; const char* pxattrvalue; if(get_meta_xattr_value(path, xattrvalue)){ pxattrvalue = xattrvalue.c_str(); }else{ pxattrvalue = nullptr; } if(IS_REPLACEDIR(nDirType)){ // Should rebuild all directory object // Need to remove old dir("dir" etc) and make new dir("dir/") // At first, remove directory old object if(0 != (result = remove_old_type_dir(strpath, nDirType))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") struct timespec ts_atime; struct timespec ts_mtime; struct timespec ts_ctime; set_stat_to_timespec(stbuf, stat_time_type::ATIME, ts_atime); set_stat_to_timespec(stbuf, stat_time_type::MTIME, ts_mtime); s3fs_realtime(ts_ctime); if(0 != (result = create_directory_object(newpath.c_str(), stbuf.st_mode, ts_atime, ts_mtime, ts_ctime, uid, gid, pxattrvalue))){ return result; } }else{ // normal object or directory object of newer version // open & load AutoFdEntity autoent; FdEntity* ent; if(0 != (result = get_local_fent(autoent, &ent, strpath.c_str(), O_RDWR, true))){ S3FS_PRN_ERR("could not open and read file(%s)", strpath.c_str()); return result; } struct timespec ts; s3fs_realtime(ts); ent->SetCtime(ts); // Change owner ent->SetUId(uid); ent->SetGId(gid); // upload if(0 != (result = ent->Flush(autoent.GetPseudoFd(), true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", strpath.c_str(), result); return result; } StatCache::getStatCacheData()->DelStat(nowcache); } S3FS_MALLOCTRIM(0); return result; } static timespec handle_utimens_special_values(timespec ts, timespec now, timespec orig) { if(ts.tv_nsec == UTIME_NOW){ return now; }else if(ts.tv_nsec == UTIME_OMIT){ return orig; }else{ return ts; } } static int update_mctime_parent_directory(const char* _path) { if(!update_parent_dir_stat){ // Disable updating parent directory stat. S3FS_PRN_DBG("Updating parent directory stats is disabled"); return 0; } WTF8_ENCODE(path) int result; std::string parentpath; // parent directory path std::string nowpath; // now directory object path("dir" or "dir/" or "xxx_$folder$", etc) std::string newpath; // directory path for the current version("dir/") std::string nowcache; headers_t meta; struct stat stbuf; struct timespec mctime; struct timespec atime; dirtype nDirType = dirtype::UNKNOWN; S3FS_PRN_INFO2("[path=%s]", path); // get parent directory path parentpath = mydirname(path); // check & get directory type if(0 != (result = chk_dir_object_type(parentpath.c_str(), newpath, nowpath, nowcache, &meta, &nDirType))){ return result; } // get directory stat // // [NOTE] // It is assumed that this function is called after the operation on // the file is completed, so there is no need to check the permissions // on the parent directory. // if(0 != (result = get_object_attribute(parentpath.c_str(), &stbuf))){ // If there is not the target file(object), result is -ENOENT. return result; } if(!S_ISDIR(stbuf.st_mode)){ S3FS_PRN_ERR("path(%s) is not parent directory.", parentpath.c_str()); return -EIO; } // make atime/mtime/ctime for updating s3fs_realtime(mctime); set_stat_to_timespec(stbuf, stat_time_type::ATIME, atime); if(0 == atime.tv_sec && 0 == atime.tv_nsec){ atime = mctime; } if(nocopyapi || IS_REPLACEDIR(nDirType) || IS_CREATE_MP_STAT(parentpath.c_str())){ // Should rebuild directory object(except new type) // Need to remove old dir("dir" etc) and make new dir("dir/") std::string xattrvalue; const char* pxattrvalue; if(get_meta_xattr_value(path, xattrvalue)){ pxattrvalue = xattrvalue.c_str(); }else{ pxattrvalue = nullptr; } // At first, remove directory old object if(!nowpath.empty()){ if(0 != (result = remove_old_type_dir(nowpath, nDirType))){ return result; } } if(!nowcache.empty()){ StatCache::getStatCacheData()->DelStat(nowcache); } // Make new directory object("dir/") if(0 != (result = create_directory_object(newpath.c_str(), stbuf.st_mode, atime, mctime, mctime, stbuf.st_uid, stbuf.st_gid, pxattrvalue))){ return result; } }else{ std::string strSourcePath = (mount_prefix.empty() && "/" == nowpath) ? "//" : nowpath; headers_t updatemeta; updatemeta["x-amz-meta-mtime"] = str(mctime); updatemeta["x-amz-meta-ctime"] = str(mctime); updatemeta["x-amz-meta-atime"] = str(atime); updatemeta["x-amz-copy-source"] = urlEncodePath(service_path + S3fsCred::GetBucket() + get_realpath(strSourcePath.c_str())); updatemeta["x-amz-metadata-directive"] = "REPLACE"; merge_headers(meta, updatemeta, true); // upload meta for parent directory. if(0 != (result = put_headers(nowpath.c_str(), meta, true))){ return result; } StatCache::getStatCacheData()->DelStat(nowcache); } S3FS_MALLOCTRIM(0); return 0; } static int s3fs_utimens(const char* _path, const struct timespec ts[2]) { WTF8_ENCODE(path) int result; std::string strpath; std::string newpath; std::string nowcache; headers_t meta; struct stat stbuf; dirtype nDirType = dirtype::UNKNOWN; FUSE_CTX_INFO("[path=%s][mtime=%s][ctime/atime=%s]", path, str(ts[1]).c_str(), str(ts[0]).c_str()); 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; } } struct timespec now; struct timespec ts_atime; struct timespec ts_ctime; struct timespec ts_mtime; s3fs_realtime(now); set_stat_to_timespec(stbuf, stat_time_type::ATIME, ts_atime); set_stat_to_timespec(stbuf, stat_time_type::CTIME, ts_ctime); set_stat_to_timespec(stbuf, stat_time_type::MTIME, ts_mtime); struct timespec atime = handle_utimens_special_values(ts[0], now, ts_atime); struct timespec ctime = handle_utimens_special_values(ts[0], now, ts_ctime); struct timespec mtime = handle_utimens_special_values(ts[1], now, ts_mtime); 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(), nullptr, &meta); } if(0 != result){ return result; } if(S_ISDIR(stbuf.st_mode) && (IS_REPLACEDIR(nDirType) || IS_CREATE_MP_STAT(path))){ std::string xattrvalue; const char* pxattrvalue; if(get_meta_xattr_value(path, xattrvalue)){ pxattrvalue = xattrvalue.c_str(); }else{ pxattrvalue = nullptr; } if(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(0 != (result = remove_old_type_dir(strpath, nDirType))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") if(0 != (result = create_directory_object(newpath.c_str(), stbuf.st_mode, atime, mtime, ctime, stbuf.st_uid, stbuf.st_gid, pxattrvalue))){ return result; } }else{ std::string strSourcePath = (mount_prefix.empty() && "/" == strpath) ? "//" : strpath; headers_t updatemeta; updatemeta["x-amz-meta-mtime"] = str(mtime); updatemeta["x-amz-meta-ctime"] = str(ctime); updatemeta["x-amz-meta-atime"] = str(atime); updatemeta["x-amz-copy-source"] = urlEncodePath(service_path + S3fsCred::GetBucket() + get_realpath(strSourcePath.c_str())); updatemeta["x-amz-metadata-directive"] = "REPLACE"; // check opened file handle. // // If the file starts uploading by multipart when the disk capacity is insufficient, // we need to put these header after finishing upload. // Or if the file is only open, we must update to FdEntity's internal meta. // AutoFdEntity autoent; FdEntity* ent; bool need_put_header = true; bool keep_mtime = false; if(nullptr != (ent = autoent.OpenExistFdEntity(path))){ if(ent->MergeOrgMeta(updatemeta)){ // meta is changed, but now uploading. // then the meta is pending and accumulated to be put after the upload is complete. S3FS_PRN_INFO("meta pending until upload is complete"); need_put_header = false; ent->SetHoldingMtime(mtime); // If there is data in the Stats cache, update the Stats cache. StatCache::getStatCacheData()->UpdateMetaStats(strpath, updatemeta); // [NOTE] // There are cases where this function is called during the process of // creating a new file (before uploading). // In this case, a temporary cache exists in the Stat cache.(see s3fs_create) // So we need to update the cache, if it exists. // // Previously, the process of creating a new file was to update the // file content after first uploading the file, but now the file is // not created until flushing. // So we need to create a temporary Stat cache for it. // if(!StatCache::getStatCacheData()->AddStat(strpath, updatemeta, false, true)){ return -EIO; } }else{ S3FS_PRN_INFO("meta is not pending, but need to keep current mtime."); // [NOTE] // Depending on the order in which write/flush and utimens are called, // the mtime updated here may be overwritten at the time of flush. // To avoid that, set a special flag. // keep_mtime = true; } } if(need_put_header){ // not found opened file. merge_headers(meta, updatemeta, true); // upload meta directly. if(0 != (result = put_headers(strpath.c_str(), meta, true))){ return result; } StatCache::getStatCacheData()->DelStat(nowcache); if(keep_mtime){ ent->SetHoldingMtime(mtime); } } } S3FS_MALLOCTRIM(0); return 0; } static int s3fs_utimens_nocopy(const char* _path, const struct timespec ts[2]) { WTF8_ENCODE(path) int result; std::string strpath; std::string newpath; std::string nowcache; struct stat stbuf; dirtype nDirType = dirtype::UNKNOWN; FUSE_CTX_INFO1("[path=%s][mtime=%s][atime/ctime=%s]", path, str(ts[1]).c_str(), str(ts[0]).c_str()); 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; } } struct timespec now; struct timespec ts_atime; struct timespec ts_ctime; struct timespec ts_mtime; s3fs_realtime(now); set_stat_to_timespec(stbuf, stat_time_type::ATIME, ts_atime); set_stat_to_timespec(stbuf, stat_time_type::CTIME, ts_ctime); set_stat_to_timespec(stbuf, stat_time_type::MTIME, ts_mtime); struct timespec atime = handle_utimens_special_values(ts[0], now, ts_atime); struct timespec ctime = handle_utimens_special_values(ts[0], now, ts_ctime); struct timespec mtime = handle_utimens_special_values(ts[1], now, ts_mtime); // Get attributes if(S_ISDIR(stbuf.st_mode)){ result = chk_dir_object_type(path, newpath, strpath, nowcache, nullptr, &nDirType); }else{ strpath = path; nowcache = strpath; result = get_object_attribute(strpath.c_str(), nullptr, nullptr); } if(0 != result){ return result; } if(S_ISDIR(stbuf.st_mode)){ std::string xattrvalue; const char* pxattrvalue; if(get_meta_xattr_value(path, xattrvalue)){ pxattrvalue = xattrvalue.c_str(); }else{ pxattrvalue = nullptr; } if(IS_REPLACEDIR(nDirType)){ // Should rebuild all directory object // Need to remove old dir("dir" etc) and make new dir("dir/") // At first, remove directory old object if(0 != (result = remove_old_type_dir(strpath, nDirType))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") if(0 != (result = create_directory_object(newpath.c_str(), stbuf.st_mode, atime, mtime, ctime, stbuf.st_uid, stbuf.st_gid, pxattrvalue))){ return result; } }else{ // normal object or directory object of newer version // open & load AutoFdEntity autoent; FdEntity* ent; if(0 != (result = get_local_fent(autoent, &ent, strpath.c_str(), O_RDWR, true))){ S3FS_PRN_ERR("could not open and read file(%s)", strpath.c_str()); return result; } // set mtime/ctime if(0 != (result = ent->SetMCtime(mtime, ctime))){ S3FS_PRN_ERR("could not set mtime and ctime to file(%s): result=%d", strpath.c_str(), result); return result; } // set atime if(0 != (result = ent->SetAtime(atime))){ S3FS_PRN_ERR("could not set atime to file(%s): result=%d", strpath.c_str(), result); return result; } // upload if(0 != (result = ent->Flush(autoent.GetPseudoFd(), true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", strpath.c_str(), result); return result; } StatCache::getStatCacheData()->DelStat(nowcache); } S3FS_MALLOCTRIM(0); return result; } static int s3fs_truncate(const char* _path, off_t size) { WTF8_ENCODE(path) int result; headers_t meta; AutoFdEntity autoent; FdEntity* ent = nullptr; FUSE_CTX_INFO("[path=%s][size=%lld]", path, static_cast<long long>(size)); size = std::max<off_t>(size, 0); if(0 != (result = check_parent_object_access(path, X_OK))){ return result; } if(0 != (result = check_object_access(path, W_OK, nullptr))){ return result; } // Get file information if(0 == (result = get_object_attribute(path, nullptr, &meta))){ // File exists // [NOTE] // If the file exists, the file has already been opened by FUSE before // truncate is called. Then the call below will change the file size. // (When an already open file is changed the file size, FUSE will not // reopen it.) // The Flush is called before this file is closed, so there is no need // to do it here. // // [NOTICE] // FdManager::Open() ignores changes that reduce the file size for the // file you are editing. However, if user opens only once, edit it, // and then shrink the file, it should be done. // When this function is called, the file is already open by FUSE or // some other operation. Therefore, if the number of open files is 1, // no edits other than that fd will be made, and the files will be // shrunk using ignore_modify flag even while editing. // See the comments when merging this code for FUSE2 limitations. // (In FUSE3, it will be possible to handle it reliably using fuse_file_info.) // bool ignore_modify; if(1 < FdManager::GetOpenFdCount(path)){ ignore_modify = false; }else{ ignore_modify = true; } if(nullptr == (ent = autoent.Open(path, &meta, size, S3FS_OMIT_TS, O_RDWR, false, true, ignore_modify))){ S3FS_PRN_ERR("could not open file(%s): errno=%d", path, errno); return -EIO; } ent->UpdateCtime(); #if defined(__APPLE__) // [NOTE] // Only for macos, this truncate calls to "size=0" do not reflect size. // The cause is unknown now, but it can be avoided by flushing the file. // if(0 == size){ if(0 != (result = ent->Flush(autoent.GetPseudoFd(), true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", path, result); return result; } StatCache::getStatCacheData()->DelStat(path); } #endif }else{ // Not found -> Make tmpfile(with size) const struct fuse_context* pcxt; if(nullptr == (pcxt = fuse_get_context())){ return -EIO; } std::string strnow = s3fs_str_realtime(); meta["Content-Type"] = "application/octet-stream"; // Static meta["x-amz-meta-mode"] = std::to_string(S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO); meta["x-amz-meta-ctime"] = strnow; meta["x-amz-meta-mtime"] = strnow; meta["x-amz-meta-uid"] = std::to_string(pcxt->uid); meta["x-amz-meta-gid"] = std::to_string(pcxt->gid); if(nullptr == (ent = autoent.Open(path, &meta, size, S3FS_OMIT_TS, O_RDWR, true, true, false))){ S3FS_PRN_ERR("could not open file(%s): errno=%d", path, errno); return -EIO; } if(0 != (result = ent->Flush(autoent.GetPseudoFd(), true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", path, result); return result; } StatCache::getStatCacheData()->DelStat(path); } S3FS_MALLOCTRIM(0); return result; } static int s3fs_open(const char* _path, struct fuse_file_info* fi) { WTF8_ENCODE(path) int result; struct stat st; bool needs_flush = false; FUSE_CTX_INFO("[path=%s][flags=0x%x]", path, fi->flags); if ((fi->flags & O_ACCMODE) == O_RDONLY && fi->flags & O_TRUNC) { return -EACCES; } // [NOTE] // Delete the Stats cache only if the file is not open. // If the file is open, the stats cache will not be deleted as // there are cases where the object does not exist on the server // and only the Stats cache exists. // if(StatCache::getStatCacheData()->HasStat(path)){ if(!FdManager::HasOpenEntityFd(path)){ 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; } AutoFdEntity autoent; FdEntity* ent; headers_t meta; if((unsigned int)fi->flags & O_TRUNC){ if(0 != st.st_size){ st.st_size = 0; needs_flush = true; } }else{ // [NOTE] // If the file has already been opened and edited, the file size in // the edited state is given priority. // This prevents the file size from being reset to its original size // if you keep the file open, shrink its size, and then read the file // from another process while it has not yet been flushed. // if(nullptr != (ent = autoent.OpenExistFdEntity(path)) && ent->IsModified()){ // sets the file size being edited. ent->GetSize(st.st_size); } } if(!S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)){ st.st_mtime = -1; } if(0 != (result = get_object_attribute(path, nullptr, &meta, true, nullptr, true))){ // no truncate cache return result; } struct timespec st_mctime; set_stat_to_timespec(st, stat_time_type::MTIME, st_mctime); if(nullptr == (ent = autoent.Open(path, &meta, st.st_size, st_mctime, fi->flags, false, true, false))){ StatCache::getStatCacheData()->DelStat(path); return -EIO; } if (needs_flush){ struct timespec ts; s3fs_realtime(ts); ent->SetMCtime(ts, ts); if(0 != (result = ent->RowFlush(autoent.GetPseudoFd(), path, true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", path, result); StatCache::getStatCacheData()->DelStat(path); return result; } } fi->fh = autoent.Detach(); // KEEP fdentity open; 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) { WTF8_ENCODE(path) ssize_t res; FUSE_CTX_DBG("[path=%s][size=%zu][offset=%lld][pseudo_fd=%llu]", path, size, static_cast<long long>(offset), (unsigned long long)(fi->fh)); AutoFdEntity autoent; FdEntity* ent; if(nullptr == (ent = autoent.GetExistFdEntity(path, static_cast<int>(fi->fh)))){ S3FS_PRN_ERR("could not find opened pseudo_fd(=%llu) for path(%s)", (unsigned long long)(fi->fh), path); return -EIO; } // check real file size off_t realsize = 0; if(!ent->GetSize(realsize) || 0 == realsize){ S3FS_PRN_DBG("file size is 0, so break to read."); return 0; } if(0 > (res = ent->Read(static_cast<int>(fi->fh), buf, offset, size, false))){ S3FS_PRN_WARN("failed to read file(%s). result=%zd", path, res); } return static_cast<int>(res); } static int s3fs_write(const char* _path, const char* buf, size_t size, off_t offset, struct fuse_file_info* fi) { WTF8_ENCODE(path) ssize_t res; FUSE_CTX_DBG("[path=%s][size=%zu][offset=%lld][pseudo_fd=%llu]", path, size, static_cast<long long int>(offset), (unsigned long long)(fi->fh)); AutoFdEntity autoent; FdEntity* ent; if(nullptr == (ent = autoent.GetExistFdEntity(path, static_cast<int>(fi->fh)))){ S3FS_PRN_ERR("could not find opened pseudo_fd(%llu) for path(%s)", (unsigned long long)(fi->fh), path); return -EIO; } if(0 > (res = ent->Write(static_cast<int>(fi->fh), buf, offset, size))){ S3FS_PRN_WARN("failed to write file(%s). result=%zd", path, res); } if(max_dirty_data != -1 && ent->BytesModified() >= max_dirty_data){ int flushres; if(0 != (flushres = ent->RowFlush(static_cast<int>(fi->fh), path, true))){ S3FS_PRN_ERR("could not upload file(%s): result=%d", path, flushres); StatCache::getStatCacheData()->DelStat(path); return flushres; } // Punch a hole in the file to recover disk space. if(!ent->PunchHole()){ S3FS_PRN_WARN("could not punching HOLEs to a cache file, but continue."); } } return static_cast<int>(res); } static int s3fs_statfs(const char* _path, struct statvfs* stbuf) { // WTF8_ENCODE(path) stbuf->f_bsize = s3fs_block_size; stbuf->f_namemax = NAME_MAX; #if defined(__MSYS__) // WinFsp resolves the free space from f_bfree * f_frsize, and the total space from f_blocks * f_frsize (in bytes). stbuf->f_blocks = bucket_block_count; stbuf->f_frsize = stbuf->f_bsize; stbuf->f_bfree = stbuf->f_blocks; #elif defined(__APPLE__) stbuf->f_blocks = bucket_block_count; stbuf->f_frsize = stbuf->f_bsize; stbuf->f_bfree = stbuf->f_blocks; stbuf->f_files = UINT32_MAX; stbuf->f_ffree = UINT32_MAX; stbuf->f_favail = UINT32_MAX; #else stbuf->f_frsize = stbuf->f_bsize; stbuf->f_blocks = bucket_block_count; stbuf->f_bfree = stbuf->f_blocks; #endif stbuf->f_bavail = stbuf->f_blocks; return 0; } static int s3fs_flush(const char* _path, struct fuse_file_info* fi) { WTF8_ENCODE(path) int result; FUSE_CTX_INFO("[path=%s][pseudo_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, nullptr); if(-ENOENT == result){ if(0 != (result = check_parent_object_access(path, W_OK))){ return result; } }else if(0 != result){ return result; } AutoFdEntity autoent; FdEntity* ent; if(nullptr != (ent = autoent.GetExistFdEntity(path, static_cast<int>(fi->fh)))){ bool is_new_file = ent->IsDirtyNewFile(); ent->UpdateMtime(true); // clear the flag not to update mtime. ent->UpdateCtime(); result = ent->Flush(static_cast<int>(fi->fh), false); StatCache::getStatCacheData()->DelStat(path); if(is_new_file){ // update parent directory timestamp int update_result; if(0 != (update_result = update_mctime_parent_directory(path))){ S3FS_PRN_ERR("succeed to create the file(%s), but could not update timestamp of its parent directory(result=%d).", path, update_result); } } } 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) { WTF8_ENCODE(path) int result = 0; FUSE_CTX_INFO("[path=%s][datasync=%d][pseudo_fd=%llu]", path, datasync, (unsigned long long)(fi->fh)); AutoFdEntity autoent; FdEntity* ent; if(nullptr != (ent = autoent.GetExistFdEntity(path, static_cast<int>(fi->fh)))){ bool is_new_file = ent->IsDirtyNewFile(); if(0 == datasync){ ent->UpdateMtime(); ent->UpdateCtime(); } result = ent->Flush(static_cast<int>(fi->fh), false); if(0 != datasync){ // [NOTE] // The metadata are not updated when fdatasync is called. // Instead of it, these metadata are pended and set the dirty flag here. // Setting this flag allows metadata to be updated even if there is no // content update between the fdatasync call and the flush call. // ent->MarkDirtyMetadata(); } if(is_new_file){ // update parent directory timestamp int update_result; if(0 != (update_result = update_mctime_parent_directory(path))){ S3FS_PRN_ERR("succeed to create the file(%s), but could not update timestamp of its parent directory(result=%d).", path, update_result); } } } S3FS_MALLOCTRIM(0); // Issue 320: Delete stat cache entry because st_size may have changed. StatCache::getStatCacheData()->DelStat(path); return result; } static int s3fs_release(const char* _path, struct fuse_file_info* fi) { WTF8_ENCODE(path) FUSE_CTX_INFO("[path=%s][pseudo_fd=%llu]", path, (unsigned long long)(fi->fh)); { // scope for AutoFdEntity AutoFdEntity autoent; // [NOTE] // The pseudo fd stored in fi->fh is attached to AutoFdEntry so that it can be // destroyed here. // FdEntity* ent; if(nullptr == (ent = autoent.Attach(path, static_cast<int>(fi->fh)))){ S3FS_PRN_ERR("could not find pseudo_fd(%llu) for path(%s)", (unsigned long long)(fi->fh), path); return -EIO; } // [NOTE] // There are cases when s3fs_flush is not called and s3fs_release is called. // (There have been reported cases where it is not called when exported as NFS.) // Therefore, Flush() is called here to try to upload the data. // Flush() will only perform an upload if the file has been updated. // int result; if(ent->IsModified()){ if(0 != (result = ent->Flush(static_cast<int>(fi->fh), false))){ S3FS_PRN_ERR("failed to upload file contentsfor pseudo_fd(%llu) / path(%s) by result(%d)", (unsigned long long)(fi->fh), path, result); return result; } } // [NOTE] // All opened file's stats is cached with no truncate flag. // Thus we unset it here. StatCache::getStatCacheData()->ChangeNoTruncateFlag(path, false); // [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 ASAP. // if((fi->flags & O_RDWR) || (fi->flags & O_WRONLY)){ StatCache::getStatCacheData()->DelStat(path); } bool is_new_file = ent->IsDirtyNewFile(); if(0 != (result = ent->UploadPending(static_cast<int>(fi->fh)))){ S3FS_PRN_ERR("could not upload pending data(meta, etc) for pseudo_fd(%llu) / path(%s)", (unsigned long long)(fi->fh), path); return result; } if(is_new_file){ // update parent directory timestamp int update_result; if(0 != (update_result = update_mctime_parent_directory(path))){ S3FS_PRN_ERR("succeed to create the file(%s), but could not update timestamp of its parent directory(result=%d).", path, update_result); } } } // check - for debug if(S3fsLog::IsS3fsLogDbg()){ if(FdManager::HasOpenEntityFd(path)){ S3FS_PRN_DBG("file(%s) is still opened(another pseudo fd is opened).", path); } } S3FS_MALLOCTRIM(0); return 0; } static int s3fs_opendir(const char* _path, struct fuse_file_info* fi) { WTF8_ENCODE(path) int result; int mask = (O_RDONLY != (fi->flags & O_ACCMODE) ? W_OK : R_OK); FUSE_CTX_INFO("[path=%s][flags=0x%x]", path, fi->flags); if(0 == (result = check_object_access(path, mask, nullptr))){ result = check_parent_object_access(path, X_OK); } S3FS_MALLOCTRIM(0); return result; } static int readdir_multi_head(const char* path, const S3ObjList& head, void* buf, fuse_fill_dir_t filler) { S3FS_PRN_INFO1("[path=%s][head=<%s>][filler=%p]", path, head.IsEmpty() ? "empty" : "not empty", filler); // Make base path list. s3obj_list_t headlist; head.GetNameList(headlist, true, false); // get name with "/". StatCache::getStatCacheData()->GetNotruncateCache(std::string(path), headlist); // Add notruncate file name from stat cache // Initialize SyncFiller object SyncFiller syncfiller(buf, filler); // common variables Semaphore multi_head_sem(0); int req_count = 0; int req_result = 0; int retrycount = 0; std::mutex thparam_lock; s3obj_list_t notfound_list; // Make single head request(with max). for(auto iter = headlist.cbegin(); headlist.cend() != iter; ++iter){ std::string disppath = path + (*iter); std::string etag = head.GetETag((*iter).c_str()); struct stat st; // [NOTE] // If there is a cache hit, file stat is filled by filler at here. // if(StatCache::getStatCacheData()->HasStat(disppath, &st, etag.c_str())){ std::string bpath = mybasename(disppath); if(use_wtf8){ bpath = s3fs_wtf8_decode(bpath); } syncfiller.Fill(bpath, &st, 0); continue; } // parameter for thread worker auto* thargs = new multi_head_req_thparam; // free in multi_head_req_threadworker thargs->psyncfiller = &syncfiller; thargs->pthparam_lock = &thparam_lock; // for pretrycount and presult member thargs->pretrycount = &retrycount; thargs->pnotfound_list = &notfound_list; thargs->use_wtf8 = use_wtf8; thargs->path = disppath; thargs->presult = &req_result; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = thargs; ppoolparam.psem = &multi_head_sem; ppoolparam.pfunc = multi_head_req_threadworker; // setup instruction if(!ThreadPoolMan::Instruct(ppoolparam)){ S3FS_PRN_ERR("failed setup instruction for one header request."); delete thargs; return -EIO; } ++req_count; } // wait for finish all requests while(req_count > 0){ multi_head_sem.acquire(); --req_count; } // print messages if(0 != req_result){ S3FS_PRN_DBG("Some head requests returned error, first error is %d.", req_result); } // [NOTE] // Objects that could not be found by HEAD request may exist only // as a path, so search for objects under that path.(a case of no dir object) // if(!support_compat_dir){ syncfiller.SufficiencyFill(head.GetCommonPrefixes()); } if(support_compat_dir && !notfound_list.empty()){ // [NOTE] not need to lock to access this here. // dummy header mode_t dirmask = umask(0); // macos does not have getumask() umask(dirmask); headers_t dummy_header; dummy_header["Content-Type"] = "application/x-directory"; // directory dummy_header["x-amz-meta-uid"] = std::to_string(is_s3fs_uid ? s3fs_uid : geteuid()); dummy_header["x-amz-meta-gid"] = std::to_string(is_s3fs_gid ? s3fs_gid : getegid()); dummy_header["x-amz-meta-mode"] = std::to_string(S_IFDIR | (~dirmask & (S_IRWXU | S_IRWXG | S_IRWXO))); dummy_header["x-amz-meta-atime"] = "0"; dummy_header["x-amz-meta-ctime"] = "0"; dummy_header["x-amz-meta-mtime"] = "0"; for(auto reiter = notfound_list.cbegin(); reiter != notfound_list.cend(); ++reiter){ int dir_result; const std::string& dirpath = *reiter; if(-ENOTEMPTY == (dir_result = directory_empty(dirpath.c_str()))){ // Found objects under the path, so the path is directory. // Add stat cache if(StatCache::getStatCacheData()->AddStat(dirpath, dummy_header, true)){ // set forcedir=true // Get stats from stats cache(for converting from meta), and fill std::string bpath = mybasename(dirpath); if(use_wtf8){ bpath = s3fs_wtf8_decode(bpath); } struct stat st; if(StatCache::getStatCacheData()->GetStat(dirpath, &st)){ syncfiller.Fill(bpath, &st, 0); }else{ S3FS_PRN_INFO2("Could not find %s directory(no dir object) in stat cache.", dirpath.c_str()); syncfiller.Fill(bpath, nullptr, 0); } }else{ S3FS_PRN_ERR("failed adding stat cache [path=%s], but dontinue...", dirpath.c_str()); } }else{ S3FS_PRN_WARN("%s object does not have any object under it(errno=%d),", reiter->c_str(), dir_result); } } } return 0; } static int s3fs_readdir(const char* _path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fi) { WTF8_ENCODE(path) S3ObjList head; int result; FUSE_CTX_INFO("[path=%s]", path); if(0 != (result = check_object_access(path, R_OK, nullptr))){ 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, ".", nullptr, 0); filler(buf, "..", nullptr, 0); if(head.IsEmpty()){ return 0; } // Send multi head request for stats caching. std::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) { std::string s3_realpath; std::string query_delimiter; std::string query_prefix; std::string query_maxkey; std::string next_continuation_token; std::string next_marker; bool truncated = true; 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(s3_realpath.empty() || '/' != *s3_realpath.rbegin()){ // last word must be "/" query_prefix += urlEncodePath(s3_realpath.substr(1) + "/"); }else{ query_prefix += urlEncodePath(s3_realpath.substr(1)); } if (check_content_only){ // Just need to know if there are child objects in dir // For dir with children, expect "dir/" and "dir/child" query_maxkey += "max-keys=2"; }else{ query_maxkey += "max-keys=" + std::to_string(max_keys_list_object); } while(truncated){ int result; std::string each_query; std::string responseBody; // append parameters to query in alphabetical order if(!next_continuation_token.empty()){ each_query += "continuation-token=" + urlEncodePath(next_continuation_token) + "&"; next_continuation_token = ""; } each_query += query_delimiter; if(S3fsCurl::IsListObjectsV2()){ each_query += "list-type=2&"; } if(!next_marker.empty()){ each_query += "marker=" + urlEncodePath(next_marker) + "&"; next_marker = ""; } each_query += query_maxkey; each_query += query_prefix; // send request if(0 != (result = list_bucket_request(std::string(SAFESTRPTR(path)), each_query, responseBody))){ return result; } // [NOTE] // CR code(\r) is replaced with LF(\n) by xmlReadMemory() function. // To prevent that, only CR code is encoded by following function. // The encoded CR code is decoded with append_objects_from_xml(_ex). // std::string encbody = get_encoded_cr_code(responseBody.c_str()); // xmlDocPtr std::unique_ptr<xmlDoc, decltype(&xmlFreeDoc)> doc(xmlReadMemory(encbody.c_str(), static_cast<int>(encbody.size()), "", nullptr, 0), xmlFreeDoc); if(nullptr == doc){ S3FS_PRN_ERR("xmlReadMemory returns with error."); return -EIO; } if(0 != append_objects_from_xml(path, doc.get(), head)){ S3FS_PRN_ERR("append_objects_from_xml returns with error."); return -EIO; } if(true == (truncated = is_truncated(doc.get()))){ auto tmpch = get_next_continuation_token(doc.get()); if(nullptr != tmpch){ next_continuation_token = reinterpret_cast<const char*>(tmpch.get()); }else if(nullptr != (tmpch = get_next_marker(doc.get()))){ next_marker = reinterpret_cast<const char*>(tmpch.get()); } if(next_continuation_token.empty() && next_marker.empty()){ // If did not specify "delimiter", s3 did not return "NextMarker". // On this case, can use last name for next marker. // std::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(s3_realpath.empty() || '/' != *s3_realpath.rbegin()){ next_marker += "/"; } next_marker += lastname; } } } if(check_content_only){ break; } } S3FS_MALLOCTRIM(0); return 0; } static int remote_mountpath_exists(const char* path, bool compat_dir) { struct stat stbuf; int result; S3FS_PRN_INFO1("[path=%s]", path); // getattr will prefix the path with the remote mountpoint if(0 != (result = get_object_attribute(path, &stbuf, nullptr))){ return result; } // [NOTE] // If there is no mount point(directory object) that s3fs can recognize, // an error will occur. // A mount point with a directory path(ex. "<bucket>/<directory>...") // requires that directory object. // If the directory or object is created by a client other than s3fs, // s3fs may not be able to recognize it. If you specify such a directory // as a mount point, you can avoid the error by starting with "compat_dir" // specified. // if(!compat_dir && !has_mp_stat){ return -ENOENT; } return 0; } static bool get_meta_xattr_value(const char* path, std::string& rawvalue) { if(!path || '\0' == path[0]){ S3FS_PRN_ERR("path is empty."); return false; } S3FS_PRN_DBG("[path=%s]", path); rawvalue.clear(); headers_t meta; if(0 != get_object_attribute(path, nullptr, &meta)){ S3FS_PRN_ERR("Failed to get object(%s) headers", path); return false; } headers_t::const_iterator iter; if(meta.cend() == (iter = meta.find("x-amz-meta-xattr"))){ return false; } rawvalue = iter->second; return true; } static bool get_parent_meta_xattr_value(const char* path, std::string& rawvalue) { if(0 == strcmp(path, "/") || 0 == strcmp(path, ".")){ // path is mount point, thus does not have parent. return false; } std::string parent = mydirname(path); if(parent.empty()){ S3FS_PRN_ERR("Could not get parent path for %s.", path); return false; } return get_meta_xattr_value(parent.c_str(), rawvalue); } static bool get_xattr_posix_key_value(const char* path, std::string& xattrvalue, bool default_key) { xattrvalue.clear(); std::string rawvalue; if(!get_meta_xattr_value(path, rawvalue)){ return false; } xattrs_t xattrs; if(0 == parse_xattrs(rawvalue, xattrs)){ return false; } std::string targetkey; if(default_key){ targetkey = "system.posix_acl_default"; }else{ targetkey = "system.posix_acl_access"; } xattrs_t::iterator iter; if(xattrs.cend() == (iter = xattrs.find(targetkey))){ return false; } // convert value by base64 xattrvalue = s3fs_base64(reinterpret_cast<const unsigned char*>(iter->second.c_str()), iter->second.length()); return true; } // [NOTE] // Converts and returns the POSIX ACL default(system.posix_acl_default) value of // the parent directory as a POSIX ACL(system.posix_acl_access) value. // Returns false if the parent directory has no POSIX ACL defaults. // static bool build_inherited_xattr_value(const char* path, std::string& xattrvalue) { S3FS_PRN_DBG("[path=%s]", path); xattrvalue.clear(); if(0 == strcmp(path, "/") || 0 == strcmp(path, ".")){ // path is mount point, thus does not have parent. return false; } std::string parent = mydirname(path); if(parent.empty()){ S3FS_PRN_ERR("Could not get parent path for %s.", path); return false; } // get parent's "system.posix_acl_default" value(base64'd). std::string parent_default_value; if(!get_xattr_posix_key_value(parent.c_str(), parent_default_value, true)){ return false; } // build "system.posix_acl_access" from parent's default value std::string raw_xattr_value; raw_xattr_value = "{\"system.posix_acl_access\":\""; raw_xattr_value += parent_default_value; raw_xattr_value += "\"}"; xattrvalue = urlEncodePath(raw_xattr_value); return true; } static bool parse_xattr_keyval(const std::string& xattrpair, std::string& key, std::string* pval) { // parse key and value size_t pos; std::string tmpval; if(std::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 = s3fs_decode64(tmpval.c_str(), tmpval.size()); return true; } static size_t parse_xattrs(const std::string& strxattrs, xattrs_t& xattrs) { xattrs.clear(); // decode std::string jsonxattrs = urlDecode(strxattrs); // get from "{" to "}" std::string restxattrs; { size_t startpos; size_t endpos = std::string::npos; if(std::string::npos != (startpos = jsonxattrs.find_first_of('{'))){ endpos = jsonxattrs.find_last_of('}'); } if(startpos == std::string::npos || endpos == std::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(','); !restxattrs.empty(); restxattrs = (pair_nextpos != std::string::npos ? restxattrs.substr(pair_nextpos + 1) : ""), pair_nextpos = restxattrs.find_first_of(',')){ std::string pair = pair_nextpos != std::string::npos ? restxattrs.substr(0, pair_nextpos) : restxattrs; std::string key; std::string val; if(!parse_xattr_keyval(pair, key, &val)){ // something format error, so skip this. continue; } xattrs[key] = val; } return xattrs.size(); } static std::string raw_build_xattrs(const xattrs_t& xattrs) { std::string strxattrs; bool is_set = false; for(auto iter = xattrs.cbegin(); iter != xattrs.cend(); ++iter){ if(is_set){ strxattrs += ','; }else{ is_set = true; strxattrs = "{"; } strxattrs += '\"'; strxattrs += iter->first; strxattrs += "\":\""; strxattrs += s3fs_base64(reinterpret_cast<const unsigned char*>(iter->second.c_str()), iter->second.length()); strxattrs += '\"'; } if(is_set){ strxattrs += "}"; } return strxattrs; } static std::string build_xattrs(const xattrs_t& xattrs) { std::string strxattrs = raw_build_xattrs(xattrs); if(strxattrs.empty()){ strxattrs = "{}"; } strxattrs = urlEncodePath(strxattrs); return strxattrs; } static int set_xattrs_to_header(headers_t& meta, const char* name, const char* value, size_t size, int flags) { std::string strxattrs; xattrs_t xattrs; headers_t::iterator iter; if(meta.cend() == (iter = meta.find("x-amz-meta-xattr"))){ #if defined(XATTR_REPLACE) if(XATTR_REPLACE == (flags & XATTR_REPLACE)){ // there is no xattr header but flags is replace, so failure. return -ENOATTR; } #endif }else{ #if defined(XATTR_CREATE) if(XATTR_CREATE == (flags & XATTR_CREATE)){ // found xattr header but flags is only creating, so failure. return -EEXIST; } #endif strxattrs = iter->second; } // get map as xattrs_t parse_xattrs(strxattrs, xattrs); // add name(do not care overwrite and empty name/value) xattrs[name] = std::string(value, size); // build new strxattrs(not encoded) and set it to headers_t meta["x-amz-meta-xattr"] = build_xattrs(xattrs); S3FS_PRN_DBG("Set xattrs(after adding %s key) = %s", name, raw_build_xattrs(xattrs).c_str()); 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 { FUSE_CTX_INFO("[path=%s][name=%s][value=%p][size=%zu][flags=0x%x]", path, name, value, size, flags); if(!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; std::string strpath; std::string newpath; std::string nowcache; headers_t meta; struct stat stbuf; dirtype nDirType = dirtype::UNKNOWN; 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(), nullptr, &meta); } if(0 != result){ return result; } if(S_ISDIR(stbuf.st_mode) && (IS_REPLACEDIR(nDirType) || IS_CREATE_MP_STAT(path))){ if(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(0 != (result = remove_old_type_dir(strpath, nDirType))){ return result; } } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") struct timespec ts_atime; struct timespec ts_mtime; struct timespec ts_ctime; set_stat_to_timespec(stbuf, stat_time_type::ATIME, ts_atime); set_stat_to_timespec(stbuf, stat_time_type::MTIME, ts_mtime); set_stat_to_timespec(stbuf, stat_time_type::CTIME, ts_ctime); if(0 != (result = create_directory_object(newpath.c_str(), stbuf.st_mode, ts_atime, ts_mtime, ts_ctime, stbuf.st_uid, stbuf.st_gid, nullptr))){ return result; } // need to set xattr header for directory. strpath = newpath; nowcache = strpath; } // set xattr all object std::string strSourcePath = (mount_prefix.empty() && "/" == strpath) ? "//" : strpath; headers_t updatemeta; updatemeta["x-amz-meta-ctime"] = s3fs_str_realtime(); updatemeta["x-amz-copy-source"] = urlEncodePath(service_path + S3fsCred::GetBucket() + get_realpath(strSourcePath.c_str())); updatemeta["x-amz-metadata-directive"] = "REPLACE"; // check opened file handle. // // If the file starts uploading by multipart when the disk capacity is insufficient, // we need to put these header after finishing upload. // Or if the file is only open, we must update to FdEntity's internal meta. // AutoFdEntity autoent; FdEntity* ent; bool need_put_header = true; if(nullptr != (ent = autoent.OpenExistFdEntity(path))){ // get xattr and make new xattr std::string strxattr; if(ent->GetXattr(strxattr)){ updatemeta["x-amz-meta-xattr"] = strxattr; }else{ // [NOTE] // Set an empty xattr. // This requires the key to be present in order to add xattr. ent->SetXattr(strxattr); } // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(0 != (result = set_xattrs_to_header(updatemeta, name, value, size, flags))){ return result; } if(ent->MergeOrgMeta(updatemeta)){ // meta is changed, but now uploading. // then the meta is pending and accumulated to be put after the upload is complete. S3FS_PRN_INFO("meta pending until upload is complete"); need_put_header = false; // If there is data in the Stats cache, update the Stats cache. StatCache::getStatCacheData()->UpdateMetaStats(strpath, updatemeta); // [NOTE] // There are cases where this function is called during the process of // creating a new file (before uploading). // In this case, a temporary cache exists in the Stat cache. // So we need to update the cache, if it exists. (see. s3fs_create and s3fs_utimens) // if(!StatCache::getStatCacheData()->AddStat(strpath, updatemeta, false, true)){ return -EIO; } } } if(need_put_header){ // not found opened file. // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(0 != (result = set_xattrs_to_header(meta, name, value, size, flags))){ return result; } merge_headers(meta, updatemeta, true); // upload meta directly. if(0 != (result = put_headers(strpath.c_str(), meta, true))){ return result; } 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 { #if defined(__APPLE__) FUSE_CTX_DBG("[path=%s][name=%s][value=%p][size=%zu]", path, name, value, size); #else FUSE_CTX_INFO("[path=%s][name=%s][value=%p][size=%zu]", path, name, value, size); #endif if(!path || !name){ return -EIO; } #if defined(__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 headers if(0 != (result = get_object_attribute(path, nullptr, &meta))){ return result; } // get xattrs auto hiter = meta.find("x-amz-meta-xattr"); if(meta.cend() == hiter){ // object does not have xattrs return -ENOATTR; } const auto& strxattrs = hiter->second; parse_xattrs(strxattrs, xattrs); // search name std::string strname = name; auto xiter = xattrs.find(strname); if(xattrs.cend() == xiter){ // not found name in xattrs return -ENOATTR; } // decode size_t length = xiter->second.length(); const char* pvalue = xiter->second.c_str(); if(0 < size){ if(size < length){ // over buffer size return -ERANGE; } if(pvalue){ memcpy(value, pvalue, length); } } return static_cast<int>(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 headers if(0 != (result = get_object_attribute(path, nullptr, &meta))){ return result; } // get xattrs headers_t::iterator iter; if(meta.cend() == (iter = meta.find("x-amz-meta-xattr"))){ // object does not have xattrs return 0; } const auto& strxattrs = iter->second; parse_xattrs(strxattrs, xattrs); S3FS_PRN_DBG("Get xattrs = %s", raw_build_xattrs(xattrs).c_str()); // calculate total name length size_t total = 0; for(auto xiter = xattrs.cbegin(); xiter != xattrs.cend(); ++xiter){ if(!xiter->first.empty()){ total += xiter->first.length() + 1; } } if(0 == total){ return 0; } // check parameters if(0 == size){ return static_cast<int>(total); } if(!list || size < total){ return -ERANGE; } // copy to list char* setpos = list; for(auto xiter = xattrs.cbegin(); xiter != xattrs.cend(); ++xiter){ if(!xiter->first.empty()){ strcpy(setpos, xiter->first.c_str()); setpos = &setpos[strlen(setpos) + 1]; } } return static_cast<int>(total); } static int s3fs_removexattr(const char* path, const char* name) { FUSE_CTX_INFO("[path=%s][name=%s]", path, name); if(!path || !name){ return -EIO; } int result; std::string strpath; std::string newpath; std::string nowcache; headers_t meta; xattrs_t xattrs; struct stat stbuf; dirtype 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(), nullptr, &meta); } if(0 != result){ return result; } // get xattrs auto hiter = meta.find("x-amz-meta-xattr"); if(meta.cend() == hiter){ // object does not have xattrs return -ENOATTR; } const auto& strxattrs = hiter->second; parse_xattrs(strxattrs, xattrs); // check name xattrs std::string strname = name; auto xiter = xattrs.find(strname); if(xattrs.cend() == xiter){ return -ENOATTR; } // make new header_t after deleting name xattr xattrs.erase(xiter); S3FS_PRN_DBG("Reset xattrs(after delete %s key) = %s", name, raw_build_xattrs(xattrs).c_str()); 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(0 != (result = remove_old_type_dir(strpath, nDirType))){ return result; } StatCache::getStatCacheData()->DelStat(nowcache); // Make new directory object("dir/") struct timespec ts_atime; struct timespec ts_mtime; struct timespec ts_ctime; set_stat_to_timespec(stbuf, stat_time_type::ATIME, ts_atime); set_stat_to_timespec(stbuf, stat_time_type::MTIME, ts_mtime); set_stat_to_timespec(stbuf, stat_time_type::CTIME, ts_ctime); if(0 != (result = create_directory_object(newpath.c_str(), stbuf.st_mode, ts_atime, ts_mtime, ts_ctime, stbuf.st_uid, stbuf.st_gid, nullptr))){ return result; } // need to set xattr header for directory. strpath = newpath; nowcache = strpath; } // set xattr all object std::string strSourcePath = (mount_prefix.empty() && "/" == strpath) ? "//" : strpath; headers_t updatemeta; updatemeta["x-amz-copy-source"] = urlEncodePath(service_path + S3fsCred::GetBucket() + get_realpath(strSourcePath.c_str())); updatemeta["x-amz-metadata-directive"] = "REPLACE"; if(!xattrs.empty()){ updatemeta["x-amz-meta-xattr"] = build_xattrs(xattrs); }else{ updatemeta["x-amz-meta-xattr"] = ""; // This is a special case. If empty, this header will eventually be removed. } // check opened file handle. // // If the file starts uploading by multipart when the disk capacity is insufficient, // we need to put these header after finishing upload. // Or if the file is only open, we must update to FdEntity's internal meta. // AutoFdEntity autoent; FdEntity* ent; bool need_put_header = true; if(nullptr != (ent = autoent.OpenExistFdEntity(path))){ if(ent->MergeOrgMeta(updatemeta)){ // meta is changed, but now uploading. // then the meta is pending and accumulated to be put after the upload is complete. S3FS_PRN_INFO("meta pending until upload is complete"); need_put_header = false; // If there is data in the Stats cache, update the Stats cache. StatCache::getStatCacheData()->UpdateMetaStats(strpath, updatemeta); } } if(need_put_header){ // not found opened file. if(updatemeta["x-amz-meta-xattr"].empty()){ updatemeta.erase("x-amz-meta-xattr"); } merge_headers(meta, updatemeta, true); // upload meta directly. if(0 != (result = put_headers(strpath.c_str(), meta, true))){ return result; } StatCache::getStatCacheData()->DelStat(nowcache); } return 0; } // s3fs_init calls this function to exit cleanly from the fuse event loop. // // There's no way to pass an exit status to the high-level event loop API, so // this function stores the exit value in a global for main() static void s3fs_exit_fuseloop(int exit_status) { S3FS_PRN_ERR("Exiting FUSE event loop due to errors\n"); s3fs_init_deferred_exit_status = exit_status; struct fuse_context *ctx = fuse_get_context(); if (nullptr != ctx) { fuse_exit(ctx->fuse); } } static void* s3fs_init(struct fuse_conn_info* conn) { S3FS_PRN_INIT_INFO("init v%s%s with %s, credential-library(%s)", VERSION, COMMIT_HASH_VAL, s3fs_crypt_lib_name(), ps3fscred->GetCredFuncVersion(false)); // cache(remove cache dirs at first) if(is_remove_cache && (!CacheFileStat::DeleteCacheFileStatDirectory() || !FdManager::DeleteCacheDirectory())){ S3FS_PRN_DBG("Could not initialize cache directory."); } if(!ThreadPoolMan::Initialize(max_thread_count)){ S3FS_PRN_CRIT("Could not create thread pool(%d)", max_thread_count); s3fs_exit_fuseloop(EXIT_FAILURE); } // check loading IAM role name if(!ps3fscred->LoadIAMRoleFromMetaData()){ S3FS_PRN_CRIT("could not load IAM role name from meta data."); s3fs_exit_fuseloop(EXIT_FAILURE); return nullptr; } // Check Bucket { int result; if(EXIT_SUCCESS != (result = s3fs_check_service())){ s3fs_exit_fuseloop(result); return nullptr; } } // Investigate system capabilities #ifndef __APPLE__ if(conn->capable & FUSE_CAP_ATOMIC_O_TRUNC){ conn->want |= FUSE_CAP_ATOMIC_O_TRUNC; } #endif if(conn->capable & FUSE_CAP_BIG_WRITES){ conn->want |= FUSE_CAP_BIG_WRITES; } // Signal object if(!S3fsSignals::Initialize()){ S3FS_PRN_ERR("Failed to initialize signal object, but continue..."); } return nullptr; } static void s3fs_destroy(void*) { S3FS_PRN_INFO("destroy"); // Signal object if(!S3fsSignals::Destroy()){ S3FS_PRN_WARN("Failed to clean up signal object."); } ThreadPoolMan::Destroy(); // cache(remove at last) if(is_remove_cache && (!CacheFileStat::DeleteCacheFileStatDirectory() || !FdManager::DeleteCacheDirectory())){ S3FS_PRN_WARN("Could not remove cache directory."); } } static int s3fs_access(const char* path, int mask) { FUSE_CTX_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, nullptr); S3FS_MALLOCTRIM(0); return result; } // // If calling with wrong region, s3fs gets following error body as 400 error code. // "<Error> // <Code>AuthorizationHeaderMalformed</Code> // <Message>The authorization header is malformed; the region 'us-east-1' is wrong; expecting 'ap-northeast-1'</Message> // <Region>ap-northeast-1</Region> // <RequestId>...</RequestId> // <HostId>...</HostId> // </Error>" // // So this is cheap code but s3fs should get correct region automatically. // static bool check_region_error(const char* pbody, size_t len, std::string& expectregion) { if(!pbody){ return false; } std::string code; if(!simple_parse_xml(pbody, len, "Code", code) || code != "AuthorizationHeaderMalformed"){ return false; } if(!simple_parse_xml(pbody, len, "Region", expectregion)){ return false; } return true; } static bool check_endpoint_error(const char* pbody, size_t len, std::string& expectendpoint) { if(!pbody){ return false; } std::string code; if(!simple_parse_xml(pbody, len, "Code", code) || code != "PermanentRedirect"){ return false; } if(!simple_parse_xml(pbody, len, "Endpoint", expectendpoint)){ return false; } return true; } static bool check_invalid_sse_arg_error(const char* pbody, size_t len) { if(!pbody){ return false; } std::string code; if(!simple_parse_xml(pbody, len, "Code", code) || code != "InvalidArgument"){ return false; } std::string argname; if(!simple_parse_xml(pbody, len, "ArgumentName", argname) || argname != "x-amz-server-side-encryption"){ return false; } return true; } static bool check_error_message(const char* pbody, size_t len, std::string& message) { message.clear(); if(!pbody){ return false; } if(!simple_parse_xml(pbody, len, "Message", message)){ return false; } return true; } // [NOTE] // This function checks if the bucket is accessible when s3fs starts. // // The following patterns for mount points are supported by s3fs: // (1) Mount the bucket top // (2) Mount to a directory(folder) under the bucket. In this case: // (2A) Directories created by clients other than s3fs // (2B) Directory created by s3fs // // Both case of (1) and (2) check access permissions to the mount point // path(directory). // In the case of (2A), if the directory(object) for the mount point does // not exist, the check fails. However, launching s3fs with the "compat_dir" // option avoids this error and the check succeeds. If you do not specify // the "compat_dir" option in case (2A), please create a directory(object) // for the mount point before launching s3fs. // static int s3fs_check_service() { S3FS_PRN_INFO("check services."); // At first time for access S3, we check IAM role if it sets. if(!ps3fscred->CheckIAMCredentialUpdate()){ S3FS_PRN_CRIT("Failed to initialize IAM credential."); return EXIT_FAILURE; } bool forceNoSSE = false; // it is not mandatory at first. for(bool isLoop = true; isLoop; ){ long responseCode = S3fsCurl::S3FSCURL_RESPONSECODE_NOTSET; std::string responseBody; if(0 > check_service_request(get_realpath("/"), forceNoSSE, support_compat_dir, responseCode, responseBody)){ // check wrong endpoint, and automatically switch endpoint if(300 <= responseCode && responseCode < 500){ // check region error(for putting message or retrying) std::string expectregion; std::string expectendpoint; // Check if any case can be retried if(check_region_error(responseBody.c_str(), responseBody.size(), expectregion)){ // [NOTE] // If endpoint is not specified(using us-east-1 region) and // an error is encountered accessing a different region, we // will retry the check on the expected region. // see) https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro // if(s3host != "http://s3.amazonaws.com" && s3host != "https://s3.amazonaws.com"){ // specified endpoint for specified url is wrong. if(is_specified_endpoint){ S3FS_PRN_CRIT("The bucket region is not '%s'(specified) for specified url(%s), it is correctly '%s'. You should specify url(http(s)://s3-%s.amazonaws.com) and endpoint(%s) option.", endpoint.c_str(), s3host.c_str(), expectregion.c_str(), expectregion.c_str(), expectregion.c_str()); }else{ S3FS_PRN_CRIT("The bucket region is not '%s'(default) for specified url(%s), it is correctly '%s'. You should specify url(http(s)://s3-%s.amazonaws.com) and endpoint(%s) option.", endpoint.c_str(), s3host.c_str(), expectregion.c_str(), expectregion.c_str(), expectregion.c_str()); } isLoop = false; }else if(is_specified_endpoint){ // specified endpoint is wrong. S3FS_PRN_CRIT("The bucket region is not '%s'(specified), it is correctly '%s'. You should specify endpoint(%s) option.", endpoint.c_str(), expectregion.c_str(), expectregion.c_str()); isLoop = false; }else if(S3fsCurl::GetSignatureType() == signature_type_t::V4_ONLY || S3fsCurl::GetSignatureType() == signature_type_t::V2_OR_V4){ // current endpoint and url are default value, so try to connect to expected region. S3FS_PRN_CRIT("Failed to connect region '%s'(default), so retry to connect region '%s' for url(http(s)://s3-%s.amazonaws.com).", endpoint.c_str(), expectregion.c_str(), expectregion.c_str()); // change endpoint endpoint = expectregion; // change url if(s3host == "http://s3.amazonaws.com"){ s3host = "http://s3-" + endpoint + ".amazonaws.com"; }else if(s3host == "https://s3.amazonaws.com"){ s3host = "https://s3-" + endpoint + ".amazonaws.com"; } }else{ S3FS_PRN_CRIT("The bucket region is not '%s'(default), it is correctly '%s'. You should specify endpoint(%s) option.", endpoint.c_str(), expectregion.c_str(), expectregion.c_str()); isLoop = false; } }else if(check_endpoint_error(responseBody.c_str(), responseBody.size(), expectendpoint)){ // redirect error if(pathrequeststyle){ S3FS_PRN_CRIT("S3 service returned PermanentRedirect (current is url(%s) and endpoint(%s)). You need to specify correct url(http(s)://s3-<endpoint>.amazonaws.com) and endpoint option with use_path_request_style option.", s3host.c_str(), endpoint.c_str()); }else{ S3FS_PRN_CRIT("S3 service returned PermanentRedirect with %s (current is url(%s) and endpoint(%s)). You need to specify correct endpoint option.", expectendpoint.c_str(), s3host.c_str(), endpoint.c_str()); } return EXIT_FAILURE; }else if(check_invalid_sse_arg_error(responseBody.c_str(), responseBody.size())){ // SSE argument error, so retry it without SSE S3FS_PRN_CRIT("S3 service returned InvalidArgument(x-amz-server-side-encryption), so retry without adding x-amz-server-side-encryption."); // Retry without sse parameters forceNoSSE = true; } } // Try changing signature from v4 to v2 // // [NOTE] // If there is no case to retry with the previous checks, and there // is a chance to retry with signature v2, prepare to retry with v2. // if(!isLoop && (responseCode == 400 || responseCode == 403) && S3fsCurl::GetSignatureType() == signature_type_t::V2_OR_V4){ // switch sigv2 S3FS_PRN_CRIT("Failed to connect by sigv4, so retry to connect by signature version 2. But you should to review url and endpoint option."); // retry to check with sigv2 isLoop = true; S3fsCurl::SetSignatureType(signature_type_t::V2_ONLY); } // check errors(after retrying) if(!isLoop && responseCode != 200 && responseCode != 301){ // parse error message if existed std::string errMessage; check_error_message(responseBody.c_str(), responseBody.size(), errMessage); if(responseCode == 400){ S3FS_PRN_CRIT("Failed to check bucket and directory for mount point : Bad Request(host=%s, message=%s)", s3host.c_str(), errMessage.c_str()); }else if(responseCode == 403){ S3FS_PRN_CRIT("Failed to check bucket and directory for mount point : Invalid Credentials(host=%s, message=%s)", s3host.c_str(), errMessage.c_str()); }else if(responseCode == 404){ if(mount_prefix.empty()){ S3FS_PRN_CRIT("Failed to check bucket and directory for mount point : Bucket or directory not found(host=%s, message=%s)", s3host.c_str(), errMessage.c_str()); }else{ S3FS_PRN_CRIT("Failed to check bucket and directory for mount point : Bucket or directory(%s) not found(host=%s, message=%s) - You may need to specify the compat_dir option.", mount_prefix.c_str(), s3host.c_str(), errMessage.c_str()); } }else{ S3FS_PRN_CRIT("Failed to check bucket and directory for mount point : Unable to connect(host=%s, message=%s)", s3host.c_str(), errMessage.c_str()); } return EXIT_FAILURE; } }else{ // break loop isLoop = false; } } // make sure remote mountpath exists and is a directory if(!mount_prefix.empty()){ if(remote_mountpath_exists("/", support_compat_dir) != 0){ S3FS_PRN_CRIT("Remote mountpath %s not found, this may be resolved with the compat_dir option.", mount_prefix.c_str()); return EXIT_FAILURE; } } S3FS_MALLOCTRIM(0); return EXIT_SUCCESS; } // // Check & Set attributes for mount point. // static bool set_mountpoint_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); // In MSYS2 environment with WinFsp, it is not supported to change mode of mount point. // Doing that forcely will occurs permission problem, so disabling it. #ifdef __MSYS__ return true; #else 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_include_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; #endif } // // Set bucket and mount_prefix based on passed bucket name. // static int set_bucket(const std::string& arg) { size_t pos; if((pos = arg.find(':')) != std::string::npos){ if(arg.find("://") != std::string::npos){ S3FS_PRN_EXIT("bucket name and path(\"%s\") is wrong, it must be \"bucket[:/path]\".", arg.c_str()); return -1; } std::string bucket_name = arg.substr(0, pos); if(!S3fsCred::SetBucket(bucket_name)){ S3FS_PRN_EXIT("bucket name and path(\"%s\") is wrong, it must be \"bucket[:/path]\".", arg.c_str()); return -1; } std::string pmount_prefix = arg.substr(pos + 1); if(pmount_prefix.empty() || '/' != pmount_prefix[0]){ S3FS_PRN_EXIT("path(%s) must be prefix \"/\".", pmount_prefix.c_str()); return -1; } mount_prefix = pmount_prefix; // Trim the last consecutive '/' mount_prefix = trim_right(mount_prefix, "/"); }else{ if(!S3fsCred::SetBucket(arg)){ S3FS_PRN_EXIT("bucket name and path(\"%s\") is wrong, it must be \"bucket[:/path]\".", arg.c_str()); return -1; } } return 0; } // // Utility function for parse "--bucket_size" option // // max_size: A string like 20000000, 30GiB, 20TB etc // return: An integer of type fsblkcnt_t corresponding to the number // of blocks with max_size calculated with the s3fs block size, // or 0 on error // static fsblkcnt_t parse_bucket_size(std::string max_size) { const unsigned long long ten00 = 1000L; const unsigned long long ten24 = 1024L; unsigned long long scale = 1; unsigned long long n_bytes = 0; size_t pos; if((pos = max_size.find("GB")) != std::string::npos){ scale = ten00 * ten00 * ten00; if(2 < max_size.size() - pos){ return 0; // no trailing garbage } max_size.erase(pos); }else if((pos = max_size.find("GiB")) != std::string::npos){ scale = ten24 * ten24 * ten24; if(3 < max_size.size() - pos){ return 0; // no trailing garbage } max_size.erase(pos); }else if((pos = max_size.find("TB")) != std::string::npos){ scale = ten00 * ten00 * ten00 * ten00; if(2 < max_size.size() - pos){ return 0; // no trailing garbage } max_size.erase(pos); }else if((pos = max_size.find("TiB")) != std::string::npos){ scale = ten24 * ten24 * ten24 * ten24; if(3 < max_size.size() - pos){ return 0; // no trailing garbage } max_size.erase(pos); }else if((pos = max_size.find("PB")) != std::string::npos){ scale = ten00 * ten00 * ten00 * ten00 * ten00; if(2 < max_size.size() - pos){ return 0; // no trailing garbage } max_size.erase(pos); }else if((pos = max_size.find("PiB")) != std::string::npos){ scale = ten24 * ten24 * ten24 * ten24 * ten24; if(3 < max_size.size() - pos){ return 0; // no trailing garbage } max_size.erase(pos); }else if((pos = max_size.find("EB")) != std::string::npos){ scale = ten00 * ten00 * ten00 * ten00 * ten00 * ten00; if(2 < max_size.size() - pos){ return 0; // no trailing garbage } max_size.erase(pos); }else if((pos = max_size.find("EiB")) != std::string::npos){ scale = ten24 * ten24 * ten24 * ten24 * ten24 * ten24; if(3 < max_size.size() - pos){ return 0; // no trailing garbage } max_size.erase(pos); } // extra check for(size_t i = 0; i < pos; ++i){ if(!isdigit(max_size[i])){ return 0; // wrong number } n_bytes = strtoull(max_size.c_str(), nullptr, 10); if((INT64_MAX / scale) < n_bytes){ return 0; // overflow } n_bytes *= scale; } // [NOTE] // To round a number by s3fs block size. // And need to check the result value because fsblkcnt_t is 32bit in macos etc. // n_bytes /= s3fs_block_size; if(sizeof(fsblkcnt_t) <= 4){ if(INT32_MAX < n_bytes){ return 0; // overflow } } return static_cast<fsblkcnt_t>(n_bytes); // cast to fsblkcnt_t } static bool is_cmd_exists(const std::string& command) { // The `command -v` is a POSIX-compliant method for checking the existence of a program. std::string cmd = "command -v " + command + " >/dev/null 2>&1"; int result = system(cmd.c_str()); return (result !=-1 && WIFEXITED(result) && WEXITSTATUS(result) == 0); } static int print_umount_message(const std::string& mp, bool force) { std::string cmd; if (is_cmd_exists("fusermount")){ if (force){ cmd = "fusermount -uz " + mp; } else { cmd = "fusermount -u " + mp; } }else{ if (force){ cmd = "umount -l " + mp; } else { cmd = "umount " + mp; } } S3FS_PRN_EXIT("MOUNTPOINT %s is stale, you could use this command to fix: %s", mp.c_str(), cmd.c_str()); return 0; } // 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) { int ret; if(key == FUSE_OPT_KEY_NONOPT){ // the first NONOPT option is the bucket name if(S3fsCred::GetBucket().empty()){ if ((ret = set_bucket(arg)) != 0){ return ret; } return 0; }else if (!strcmp(arg, "s3fs")) { return 0; } // the second NONOPT option is the mountpoint(not utility mode) if(mountpoint.empty() && utility_incomp_type::NO_UTILITY_MODE == utility_mode){ // save the mountpoint and do some basic error checking mountpoint = arg; struct stat stbuf; // In MSYS2 environment with WinFsp, it is not needed to create the mount point before mounting. // Also it causes a conflict with WinFsp's validation, so disabling it. #ifdef __MSYS__ stbuf = {}; set_mountpoint_attribute(stbuf); #else if(stat(arg, &stbuf) == -1){ // check stale mountpoint if(errno == ENOTCONN){ print_umount_message(mountpoint, true); } else { 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_mountpoint_attribute(stbuf)){ S3FS_PRN_EXIT("MOUNTPOINT: %s permission denied.", mountpoint.c_str()); return -1; } if(!nonempty){ const struct dirent *ent; DIR *dp = opendir(mountpoint.c_str()); if(dp == nullptr){ S3FS_PRN_EXIT("failed to open MOUNTPOINT: %s: %s", mountpoint.c_str(), strerror(errno)); return -1; } while((ent = readdir(dp)) != nullptr){ 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); } #endif return 1; } // Unknown option if(utility_incomp_type::NO_UTILITY_MODE == utility_mode){ S3FS_PRN_EXIT("specified unknown third option(%s).", arg); }else{ S3FS_PRN_EXIT("specified unknown second option(%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(is_prefix(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 } else if(is_prefix(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 } else if(is_prefix(arg, "bucket_size=")){ bucket_block_count = parse_bucket_size(strchr(arg, '=') + sizeof(char)); if(0 == bucket_block_count){ S3FS_PRN_EXIT("invalid bucket_size option."); return -1; } return 0; } else if(is_prefix(arg, "umask=")){ off_t s3fs_umask_tmp = cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 8); s3fs_umask = s3fs_umask_tmp & (S_IRWXU | S_IRWXG | S_IRWXO); is_s3fs_umask = true; return 1; // continue for fuse option } else if(0 == strcmp(arg, "allow_other")){ allow_other = true; return 1; // continue for fuse option } else if(is_prefix(arg, "mp_umask=")){ off_t mp_umask_tmp = cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 8); mp_umask = mp_umask_tmp & (S_IRWXU | S_IRWXG | S_IRWXO); is_mp_umask = true; return 0; } else if(is_prefix(arg, "default_acl=")){ const char* acl_string = strchr(arg, '=') + sizeof(char); acl_t acl = to_acl(acl_string); if(acl == acl_t::UNKNOWN){ S3FS_PRN_EXIT("unknown value for default_acl: %s", acl_string); return -1; } S3fsCurl::SetDefaultAcl(acl); return 0; } else if(is_prefix(arg, "retries=")){ off_t retries = cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10); if(retries == 0){ S3FS_PRN_EXIT("retries must be greater than zero"); return -1; } S3fsCurl::SetRetries(static_cast<int>(retries)); return 0; } else if(is_prefix(arg, "tmpdir=")){ FdManager::SetTmpDir(strchr(arg, '=') + sizeof(char)); return 0; } else if(is_prefix(arg, "use_cache=")){ FdManager::SetCacheDir(strchr(arg, '=') + sizeof(char)); return 0; } else if(0 == strcmp(arg, "check_cache_dir_exist")){ FdManager::SetCheckCacheDirExist(true); return 0; } else if(0 == strcmp(arg, "del_cache")){ is_remove_cache = true; return 0; } else if(is_prefix(arg, "multireq_max=")){ int maxreq = static_cast<int>(cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10)); S3fsCurl::SetMaxMultiRequest(maxreq); return 0; } else if(0 == strcmp(arg, "nonempty")){ nonempty = true; return 1; // need to continue for fuse. } else if(0 == strcmp(arg, "nomultipart")){ nomultipart = true; return 0; } // old format for storage_class else if(0 == strcmp(arg, "use_rrs") || is_prefix(arg, "use_rrs=")){ off_t rrs = 1; // for an old format. if(is_prefix(arg, "use_rrs=")){ rrs = cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10); } 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; } else if(is_prefix(arg, "storage_class=")){ const char *storage_class = strchr(arg, '=') + sizeof(char); S3fsCurl::SetStorageClass(storage_class); 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 Loading Environment for Server Side Encrypting custom keys // AWSSSEKMSID Loading Environment for Server Side Encrypting Key id // else if(is_prefix(arg, "use_sse")){ if(0 == strcmp(arg, "use_sse") || 0 == strcmp(arg, "use_sse=1")){ // use_sse=1 is old type parameter // sse type is SSE_S3 if(!S3fsCurl::IsSseDisable() && !S3fsCurl::IsSseS3Type()){ S3FS_PRN_EXIT("already set SSE another type, so conflict use_sse option or environment."); return -1; } S3fsCurl::SetSseType(sse_type_t::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 conflict use_sse option or environment."); return -1; } if(!S3fsCurl::IsSetSseKmsId()){ S3FS_PRN_EXIT("use_sse=kms but not loaded kms id by environment."); return -1; } S3fsCurl::SetSseType(sse_type_t::SSE_KMS); }else if(is_prefix(arg, "use_sse=kmsid:") || is_prefix(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 conflict use_sse option or environment."); return -1; } const char* kmsid; if(is_prefix(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_type_t::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 keys are loaded by environment or load_sse_c option) if(!S3fsCurl::IsSseDisable() && !S3fsCurl::IsSseCType()){ S3FS_PRN_EXIT("already set SSE another type, so conflict use_sse option or environment."); return -1; } // [NOTE] // do not check ckeys exists here. // S3fsCurl::SetSseType(sse_type_t::SSE_C); }else if(is_prefix(arg, "use_sse=custom:") || is_prefix(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 conflict use_sse option or environment."); return -1; } const char* ssecfile; if(is_prefix(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_type_t::SSE_C); }else if(0 == strcmp(arg, "use_sse=")){ // this type is old style(parameter 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_type_t::SSE_C); }else{ // never come here. S3FS_PRN_EXIT("something wrong use_sse option."); return -1; } return 0; } // [NOTE] // Do only load SSE custom keys, care for set without set sse type. else if(is_prefix(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; } return 0; } else if(is_prefix(arg, "ssl_verify_hostname=")){ long sslvh = static_cast<long>(cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10)); if(-1 == S3fsCurl::SetSslVerifyHostname(sslvh)){ S3FS_PRN_EXIT("poorly formed argument to option: ssl_verify_hostname."); return -1; } return 0; } else if(is_prefix(arg, "ssl_client_cert=")){ std::string values = strchr(arg, '=') + sizeof(char); if(!S3fsCurl::SetSSLClientCertOptions(values)){ S3FS_PRN_EXIT("failed to set SSL client certification options."); return -1; } return 0; } // // Detect options for credential // else if(0 >= (ret = ps3fscred->DetectParam(arg))){ if(0 > ret){ return -1; } return 0; } else if(is_prefix(arg, "public_bucket=")){ off_t pubbucket = cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10); if(1 == pubbucket){ S3fsCurl::SetPublicBucket(true); // [NOTE] // if bucket is public(without credential), s3 do not allow copy api. // so s3fs sets nocopyapi mode. // nocopyapi = true; }else if(0 == pubbucket){ S3fsCurl::SetPublicBucket(false); }else{ S3FS_PRN_EXIT("poorly formed argument to option: public_bucket."); return -1; } return 0; } else if(is_prefix(arg, "bucket=")){ std::string bname = strchr(arg, '=') + sizeof(char); if ((ret = set_bucket(bname))){ return ret; } return 0; } else if(0 == strcmp(arg, "no_check_certificate")){ S3fsCurl::SetCheckCertificate(false); return 0; } else if(is_prefix(arg, "connect_timeout=")){ long contimeout = static_cast<long>(cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10)); S3fsCurl::SetConnectTimeout(contimeout); return 0; } else if(is_prefix(arg, "readwrite_timeout=")){ auto rwtimeout = static_cast<time_t>(cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10)); S3fsCurl::SetReadwriteTimeout(rwtimeout); return 0; } else if(is_prefix(arg, "list_object_max_keys=")){ int max_keys = static_cast<int>(cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10)); if(max_keys < 1000){ S3FS_PRN_EXIT("argument should be over 1000: list_object_max_keys"); return -1; } max_keys_list_object = max_keys; return 0; } else if(is_prefix(arg, "max_stat_cache_size=")){ auto cache_size = static_cast<unsigned long>(cvt_strtoofft(strchr(arg, '=') + sizeof(char), 10)); StatCache::getStatCacheData()->SetCacheSize(cache_size); return 0; } else if(is_prefix(arg, "stat_cache_expire=")){ auto expr_time = static_cast<time_t>(cvt_strtoofft(strchr(arg, '=') + sizeof(char), 10)); StatCache::getStatCacheData()->SetExpireTime(expr_time); return 0; } // [NOTE] // This option is for compatibility old version. else if(is_prefix(arg, "stat_cache_interval_expire=")){ auto expr_time = static_cast<time_t>(cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10)); StatCache::getStatCacheData()->SetExpireTime(expr_time, true); return 0; } else if(0 == strcmp(arg, "enable_noobj_cache")){ S3FS_PRN_WARN("enable_noobj_cache is enabled by default and a future version will remove this option."); StatCache::getStatCacheData()->EnableCacheNoObject(); return 0; } else if(0 == strcmp(arg, "disable_noobj_cache")){ StatCache::getStatCacheData()->DisableCacheNoObject(); return 0; } else if(0 == strcmp(arg, "nodnscache")){ S3fsCurl::SetDnsCache(false); return 0; } else if(0 == strcmp(arg, "nosscache")){ S3fsCurl::SetSslSessionCache(false); return 0; } else if(is_prefix(arg, "parallel_count=") || is_prefix(arg, "parallel_upload=")){ int maxpara = static_cast<int>(cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10)); if(0 >= maxpara){ S3FS_PRN_EXIT("argument should be over 1: parallel_count"); return -1; } S3fsCurl::SetMaxParallelCount(maxpara); return 0; } else if(is_prefix(arg, "max_thread_count=")){ int max_thcount = static_cast<int>(cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10)); if(0 >= max_thcount){ S3FS_PRN_EXIT("argument should be over 1: max_thread_count"); return -1; } max_thread_count = max_thcount; S3FS_PRN_WARN("The max_thread_count option is not a formal option. Please note that it will change in the future."); return 0; } else if(is_prefix(arg, "fd_page_size=")){ S3FS_PRN_ERR("option fd_page_size is no longer supported, so skip this option."); return 0; } else if(is_prefix(arg, "multipart_size=")){ off_t size = cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10); if(!S3fsCurl::SetMultipartSize(size)){ S3FS_PRN_EXIT("multipart_size option must be at least 5 MB."); return -1; } return 0; } else if(is_prefix(arg, "multipart_copy_size=")){ off_t size = cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10); if(!S3fsCurl::SetMultipartCopySize(size)){ S3FS_PRN_EXIT("multipart_copy_size option must be at least 5 MB."); return -1; } return 0; } else if(is_prefix(arg, "max_dirty_data=")){ off_t size = cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10); if(size >= 50){ size *= 1024 * 1024; }else if(size != -1){ S3FS_PRN_EXIT("max_dirty_data option must be at least 50 MB."); return -1; } max_dirty_data = size; return 0; } if(is_prefix(arg, "free_space_ratio=")){ int ratio = static_cast<int>(cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10)); if(FdManager::GetEnsureFreeDiskSpace()!=0){ S3FS_PRN_EXIT("option free_space_ratio conflicts with ensure_diskfree, please set only one of them."); return -1; } if(ratio < 0 || ratio > 100){ S3FS_PRN_EXIT("option free_space_ratio must between 0 to 100, which is: %d", ratio); return -1; } off_t dfsize = FdManager::GetTotalDiskSpaceByRatio(ratio); S3FS_PRN_INFO("Free space ratio set to %d %%, ensure the available disk space is greater than %.3f MB", ratio, static_cast<double>(dfsize) / 1024 / 1024); if(dfsize < S3fsCurl::GetMultipartSize()){ S3FS_PRN_WARN("specified size to ensure disk free space is smaller than multipart size, so set multipart size to it."); dfsize = S3fsCurl::GetMultipartSize(); } FdManager::SetEnsureFreeDiskSpace(dfsize); return 0; } else if(is_prefix(arg, "ensure_diskfree=")){ off_t dfsize = cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10) * 1024 * 1024; if(FdManager::GetEnsureFreeDiskSpace()!=0){ S3FS_PRN_EXIT("option free_space_ratio conflicts with ensure_diskfree, please set only one of them."); return -1; } S3FS_PRN_INFO("Set and ensure the available disk space is greater than %.3f MB.", static_cast<double>(dfsize) / 1024 / 1024); if(dfsize < S3fsCurl::GetMultipartSize()){ S3FS_PRN_WARN("specified size to ensure disk free space is smaller than multipart size, so set multipart size to it."); dfsize = S3fsCurl::GetMultipartSize(); } FdManager::SetEnsureFreeDiskSpace(dfsize); return 0; } else if(is_prefix(arg, "fake_diskfree=")){ S3FS_PRN_WARN("The fake_diskfree option was specified. Use this option for testing or debugging."); // [NOTE] This value is used for initializing to FdManager after parsing all options. fake_diskfree_size = cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10) * 1024 * 1024; return 0; } else if(is_prefix(arg, "multipart_threshold=")){ multipart_threshold = static_cast<int64_t>(cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10)) * 1024 * 1024; if(multipart_threshold <= MIN_MULTIPART_SIZE){ S3FS_PRN_EXIT("multipart_threshold must be at least %lld, was: %lld", static_cast<long long>(MIN_MULTIPART_SIZE), static_cast<long long>(multipart_threshold)); return -1; } return 0; } else if(is_prefix(arg, "singlepart_copy_limit=")){ singlepart_copy_limit = static_cast<int64_t>(cvt_strtoofft(strchr(arg, '=') + sizeof(char), /*base=*/ 10)) * 1024 * 1024; return 0; } else if(is_prefix(arg, "ahbe_conf=")){ std::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; } else if(0 == strcmp(arg, "noxmlns")){ noxmlns = true; return 0; } else if(0 == strcmp(arg, "nomixupload")){ FdEntity::SetNoMixMultipart(); return 0; } else if(0 == strcmp(arg, "nocopyapi")){ nocopyapi = true; return 0; } else if(0 == strcmp(arg, "streamupload")){ FdEntity::SetStreamUpload(true); S3FS_PRN_WARN("The streamupload option is not a formal option. Please note that it will change in the future."); return 0; } else if(0 == strcmp(arg, "norenameapi")){ norenameapi = true; return 0; } else if(0 == strcmp(arg, "complement_stat")){ complement_stat = true; return 0; } else if(0 == strcmp(arg, "notsup_compat_dir")){ S3FS_PRN_WARN("notsup_compat_dir is enabled by default and a future version will remove this option."); support_compat_dir = false; return 0; } else if(0 == strcmp(arg, "compat_dir")){ support_compat_dir = true; return 0; } else if(0 == strcmp(arg, "enable_content_md5")){ S3fsCurl::SetContentMd5(true); return 0; } else if(0 == strcmp(arg, "enable_unsigned_payload")){ S3fsCurl::SetUnsignedPayload(true); return 0; } else if(0 == strcmp(arg, "update_parent_dir_stat")){ update_parent_dir_stat = true; return 0; } else if(is_prefix(arg, "host=")){ s3host = strchr(arg, '=') + sizeof(char); return 0; } else if(is_prefix(arg, "servicepath=")){ service_path = strchr(arg, '=') + sizeof(char); return 0; } else if(is_prefix(arg, "url=")){ s3host = strchr(arg, '=') + sizeof(char); // strip the trailing '/', if any, off the end of the host // std::string size_t found, length; found = s3host.find_last_of('/'); length = s3host.length(); while(found == (length - 1) && length > 0){ s3host.erase(found); found = s3host.find_last_of('/'); length = s3host.length(); } // Check url for http / https protocol std::string if(!is_prefix(s3host.c_str(), "https://") && !is_prefix(s3host.c_str(), "http://")){ S3FS_PRN_EXIT("option url has invalid format, missing http / https protocol"); return -1; } return 0; } else if(0 == strcmp(arg, "sigv2")){ S3fsCurl::SetSignatureType(signature_type_t::V2_ONLY); return 0; } else if(0 == strcmp(arg, "sigv4")){ S3fsCurl::SetSignatureType(signature_type_t::V4_ONLY); return 0; } else if(is_prefix(arg, "endpoint=")){ endpoint = strchr(arg, '=') + sizeof(char); is_specified_endpoint = true; return 0; } else if(0 == strcmp(arg, "use_path_request_style")){ pathrequeststyle = true; return 0; } else if(0 == strcmp(arg, "noua")){ S3fsCurl::SetUserAgentFlag(false); return 0; } else if(0 == strcmp(arg, "listobjectsv2")){ S3fsCurl::SetListObjectsV2(true); return 0; } else if(0 == strcmp(arg, "use_xattr")){ is_use_xattr = true; return 0; }else if(is_prefix(arg, "use_xattr=")){ const char* strflag = strchr(arg, '=') + sizeof(char); if(0 == strcmp(strflag, "1")){ is_use_xattr = true; }else if(0 == strcmp(strflag, "0")){ is_use_xattr = false; }else{ S3FS_PRN_EXIT("option use_xattr has unknown parameter(%s).", strflag); return -1; } return 0; } else if(is_prefix(arg, "cipher_suites=")){ cipher_suites = strchr(arg, '=') + sizeof(char); return 0; } else if(is_prefix(arg, "instance_name=")){ instance_name = strchr(arg, '=') + sizeof(char); instance_name = "[" + instance_name + "]"; return 0; } else if(is_prefix(arg, "mime=")){ mimetype_file = strchr(arg, '=') + sizeof(char); return 0; } else if(is_prefix(arg, "proxy=")){ const char* url = &arg[strlen("proxy=")]; if(!S3fsCurl::SetProxy(url)){ S3FS_PRN_EXIT("failed to set proxy(%s).", url); return -1; } return 0; } else if(is_prefix(arg, "proxy_cred_file=")){ const char* file = &arg[strlen("proxy_cred_file=")]; if(!S3fsCurl::SetProxyUserPwd(file)){ S3FS_PRN_EXIT("failed to set proxy user and passphrase from file(%s).", file); return -1; } return 0; } else if(is_prefix(arg, "ipresolve=")){ const char* pipresolve = &arg[strlen("ipresolve=")]; if(!S3fsCurl::SetIPResolveType(pipresolve)){ S3FS_PRN_EXIT("failed to ip resolve option value(%s).", pipresolve); return -1; } return 0; } // // log file option // else if(is_prefix(arg, "logfile=")){ const char* strlogfile = strchr(arg, '=') + sizeof(char); if(!S3fsLog::SetLogfile(strlogfile)){ S3FS_PRN_EXIT("The file(%s) specified by logfile option could not be opened.", strlogfile); return -1; } return 0; } // // debug level option // else if(is_prefix(arg, "dbglevel=")){ const char* strlevel = strchr(arg, '=') + sizeof(char); if(0 == strcasecmp(strlevel, "silent") || 0 == strcasecmp(strlevel, "critical") || 0 == strcasecmp(strlevel, "crit")){ S3fsLog::SetLogLevel(S3fsLog::LEVEL_CRIT); }else if(0 == strcasecmp(strlevel, "error") || 0 == strcasecmp(strlevel, "err")){ S3fsLog::SetLogLevel(S3fsLog::LEVEL_ERR); }else if(0 == strcasecmp(strlevel, "wan") || 0 == strcasecmp(strlevel, "warn") || 0 == strcasecmp(strlevel, "warning")){ S3fsLog::SetLogLevel(S3fsLog::LEVEL_WARN); }else if(0 == strcasecmp(strlevel, "inf") || 0 == strcasecmp(strlevel, "info") || 0 == strcasecmp(strlevel, "information")){ S3fsLog::SetLogLevel(S3fsLog::LEVEL_INFO); }else if(0 == strcasecmp(strlevel, "dbg") || 0 == strcasecmp(strlevel, "debug")){ S3fsLog::SetLogLevel(S3fsLog::LEVEL_DBG); }else{ S3FS_PRN_EXIT("option dbglevel has unknown parameter(%s).", strlevel); return -1; } return 0; } // // debug option // // S3fsLog level is LEVEL_INFO, after second -d is passed to fuse. // else if(0 == strcmp(arg, "-d") || 0 == strcmp(arg, "--debug")){ if(!S3fsLog::IsS3fsLogInfo() && !S3fsLog::IsS3fsLogDbg()){ S3fsLog::SetLogLevel(S3fsLog::LEVEL_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 S3fsLog::LEVEL_DBG) else if(0 == strcmp(arg, "f2")){ S3fsLog::SetLogLevel(S3fsLog::LEVEL_DBG); return 0; } else if(0 == strcmp(arg, "curldbg")){ S3fsCurl::SetVerbose(true); return 0; }else if(is_prefix(arg, "curldbg=")){ const char* strlevel = strchr(arg, '=') + sizeof(char); if(0 == strcasecmp(strlevel, "normal")){ S3fsCurl::SetVerbose(true); }else if(0 == strcasecmp(strlevel, "body")){ S3fsCurl::SetVerbose(true); S3fsCurl::SetDumpBody(true); }else{ S3FS_PRN_EXIT("option curldbg has unknown parameter(%s).", strlevel); return -1; } return 0; } // // no time stamp in debug message // else if(0 == strcmp(arg, "no_time_stamp_msg")){ S3fsLog::SetTimeStamp(false); return 0; } // // Check cache file, using SIGUSR1 // else if(0 == strcmp(arg, "set_check_cache_sigusr1")){ if(!S3fsSignals::SetUsr1Handler(nullptr)){ S3FS_PRN_EXIT("could not set sigusr1 for checking cache."); return -1; } return 0; }else if(is_prefix(arg, "set_check_cache_sigusr1=")){ const char* strfilepath = strchr(arg, '=') + sizeof(char); if(!S3fsSignals::SetUsr1Handler(strfilepath)){ S3FS_PRN_EXIT("could not set sigusr1 for checking cache and output file(%s).", strfilepath); return -1; } return 0; } else if(is_prefix(arg, "accessKeyId=")){ S3FS_PRN_EXIT("option accessKeyId is no longer supported."); return -1; } else if(is_prefix(arg, "secretAccessKey=")){ S3FS_PRN_EXIT("option secretAccessKey is no longer supported."); return -1; } else if(0 == strcmp(arg, "use_wtf8")){ use_wtf8 = true; return 0; } else if(0 == strcmp(arg, "requester_pays")){ S3fsCurl::SetRequesterPays(true); return 0; } // [NOTE] // following option will be discarding, because these are not for fuse. // (Referenced sshfs.c) // else if(0 == strcmp(arg, "auto") || 0 == strcmp(arg, "noauto") || 0 == strcmp(arg, "user") || 0 == strcmp(arg, "nouser") || 0 == strcmp(arg, "users") || 0 == strcmp(arg, "_netdev")) { return 0; } } return 1; } int main(int argc, char* argv[]) { int ch; int fuse_res; int option_index = 0; struct fuse_operations s3fs_oper{}; time_t incomp_abort_time = (24 * 60 * 60); S3fsLog singletonLog; static constexpr struct option long_opts[] = { {"help", no_argument, nullptr, 'h'}, {"version", no_argument, nullptr, 0}, {"debug", no_argument, nullptr, 'd'}, {"incomplete-mpu-list", no_argument, nullptr, 'u'}, {"incomplete-mpu-abort", optional_argument, nullptr, 'a'}, // 'a' is only identifier and is not option. {nullptr, 0, nullptr, 0} }; // Use uint32_t instead of fsblkcnt_t::max since the latter overflows and confuses df bucket_block_count = std::numeric_limits<uint32_t>::max(); // init xml2 xmlInitParser(); LIBXML_TEST_VERSION init_sysconf_vars(); // get program name - emulate basename program_name = argv[0]; size_t found = program_name.find_last_of('/'); if(found != std::string::npos){ program_name.replace(0, found+1, ""); } // set credential object // ps3fscred.reset(new S3fsCred()); if(!S3fsCurl::InitCredentialObject(ps3fscred.get())){ S3FS_PRN_EXIT("Failed to setup credential object to s3fs curl."); exit(EXIT_FAILURE); } 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': // --incomplete-mpu-list if(utility_incomp_type::NO_UTILITY_MODE != utility_mode){ S3FS_PRN_EXIT("already utility mode option is specified."); exit(EXIT_FAILURE); } utility_mode = utility_incomp_type::INCOMP_TYPE_LIST; break; case 'a': // --incomplete-mpu-abort if(utility_incomp_type::NO_UTILITY_MODE != utility_mode){ S3FS_PRN_EXIT("already utility mode option is specified."); exit(EXIT_FAILURE); } utility_mode = utility_incomp_type::INCOMP_TYPE_ABORT; // check expire argument if(nullptr != optarg && 0 == strcasecmp(optarg, "all")){ // all is 0s incomp_abort_time = 0; }else if(nullptr != optarg){ if(!convert_unixtime_from_option_arg(optarg, incomp_abort_time)){ S3FS_PRN_EXIT("--incomplete-mpu-abort option argument is wrong."); exit(EXIT_FAILURE); } } // if optarg is null, incomp_abort_time is 24H(default) break; default: exit(EXIT_FAILURE); } } // print launch message print_launch_message(argc, argv); // Load SSE environment if(!S3fsCurl::LoadEnvSse()){ S3FS_PRN_EXIT("something wrong about SSE environment."); exit(EXIT_FAILURE); } // ssl init if(!s3fs_init_global_ssl()){ S3FS_PRN_EXIT("could not initialize for ssl libraries."); exit(EXIT_FAILURE); } // init curl (without mime types) // // [NOTE] // The curl initialization here does not load mime types. // The mime types file parameter are dynamic values according // to the user's environment, and are analyzed by the my_fuse_opt_proc // function. // The my_fuse_opt_proc function is executed after this curl // initialization. Because the curl method is used in the // my_fuse_opt_proc function, then it must be called here to // initialize. Fortunately, the processing using mime types // is only PUT/POST processing, and it is not used until the // call of my_fuse_opt_proc function is completed. Therefore, // the mime type is loaded just after calling the my_fuse_opt_proc // function. // if(!S3fsCurl::InitS3fsCurl()){ S3FS_PRN_EXIT("Could not initiate curl library."); s3fs_destroy_global_ssl(); exit(EXIT_FAILURE); } // 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, nullptr, nullptr, my_fuse_opt_proc)){ S3fsCurl::DestroyS3fsCurl(); s3fs_destroy_global_ssl(); exit(EXIT_FAILURE); } // init mime types for curl if(!S3fsCurl::InitMimeType(mimetype_file)){ S3FS_PRN_WARN("Missing MIME types prevents setting Content-Type on uploaded objects."); } // [NOTE] // exclusive option check here. // if(strcasecmp(S3fsCurl::GetStorageClass().c_str(), "REDUCED_REDUNDANCY") == 0 && !S3fsCurl::IsSseDisable()){ S3FS_PRN_EXIT("use_sse option could not be specified with storage class reduced_redundancy."); S3fsCurl::DestroyS3fsCurl(); s3fs_destroy_global_ssl(); exit(EXIT_FAILURE); } if(!S3fsCurl::FinalCheckSse()){ S3FS_PRN_EXIT("something wrong about SSE options."); S3fsCurl::DestroyS3fsCurl(); s3fs_destroy_global_ssl(); exit(EXIT_FAILURE); } if(S3fsCurl::GetSignatureType() == signature_type_t::V2_ONLY && S3fsCurl::GetUnsignedPayload()){ S3FS_PRN_WARN("Ignoring enable_unsigned_payload with sigv2"); } if(!FdEntity::GetNoMixMultipart() && max_dirty_data != -1){ S3FS_PRN_WARN("Setting max_dirty_data to -1 when nomixupload is enabled"); max_dirty_data = -1; } // // Check the combination of parameters for credential // if(!ps3fscred->CheckAllParams()){ S3fsCurl::DestroyS3fsCurl(); s3fs_destroy_global_ssl(); 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_incomp_type::NO_UTILITY_MODE == utility_mode){ if(mountpoint.empty()){ S3FS_PRN_EXIT("missing MOUNTPOINT argument."); show_usage(); S3fsCurl::DestroyS3fsCurl(); s3fs_destroy_global_ssl(); exit(EXIT_FAILURE); } } // check tmp dir permission if(!FdManager::CheckTmpDirExist()){ S3FS_PRN_EXIT("temporary directory doesn't exists."); S3fsCurl::DestroyS3fsCurl(); s3fs_destroy_global_ssl(); exit(EXIT_FAILURE); } // check cache dir permission if(!FdManager::CheckCacheDirExist() || !FdManager::CheckCacheTopDir() || !CacheFileStat::CheckCacheFileStatTopDir()){ S3FS_PRN_EXIT("could not allow cache directory permission, check permission of cache directories."); S3fsCurl::DestroyS3fsCurl(); s3fs_destroy_global_ssl(); exit(EXIT_FAILURE); } // set user agent S3fsCurl::InitUserAgent(); // 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: // https://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 = S3fsCred::GetBucket().find_first_of('.'); if(found != std::string::npos){ found = s3host.find("https:"); if(found != std::string::npos){ S3FS_PRN_EXIT("Using https and a bucket name with periods is unsupported."); S3fsCurl::DestroyS3fsCurl(); s3fs_destroy_global_ssl(); exit(EXIT_FAILURE); } } } */ if(utility_incomp_type::NO_UTILITY_MODE != utility_mode){ int exitcode = s3fs_utility_processing(incomp_abort_time); S3fsCurl::DestroyS3fsCurl(); s3fs_destroy_global_ssl(); exit(exitcode); } // Check multipart / copy api for mix multipart uploading if(nomultipart || nocopyapi || norenameapi){ FdEntity::SetNoMixMultipart(); max_dirty_data = -1; } // Free disk space if(-1 != fake_diskfree_size){ // Case: Set fake disk space // Not check free disk space for maultipart request FdManager::InitFakeUsedDiskSize(fake_diskfree_size); }else{ if(0 == FdManager::GetEnsureFreeDiskSpace()){ // Case: Not set any ensure disk free space // Set default value of free_space_ratio to 10% // int ratio = 10; off_t dfsize = FdManager::GetTotalDiskSpaceByRatio(ratio); S3FS_PRN_INFO("Free space ratio default to %d %%, ensure the available disk space is greater than %.3f MB", ratio, static_cast<double>(dfsize) / 1024 / 1024); if(dfsize < S3fsCurl::GetMultipartSize()){ S3FS_PRN_WARN("specified size to ensure disk free space is smaller than multipart size, so set multipart size to it."); dfsize = S3fsCurl::GetMultipartSize(); } FdManager::SetEnsureFreeDiskSpace(dfsize); } // Check free disk space for maultipart request if(!FdManager::IsSafeDiskSpace(nullptr, S3fsCurl::GetMultipartSize() * S3fsCurl::GetMaxParallelCount())){ // Try to clean cache dir and retry S3FS_PRN_WARN("No enough disk space for s3fs, try to clean cache dir"); FdManager::get()->CleanupCacheDir(); if(!FdManager::IsSafeDiskSpace(nullptr, S3fsCurl::GetMultipartSize() * S3fsCurl::GetMaxParallelCount(), true)){ S3fsCurl::DestroyS3fsCurl(); s3fs_destroy_global_ssl(); exit(EXIT_FAILURE); } } } 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 if(is_use_xattr){ s3fs_oper.setxattr = s3fs_setxattr; s3fs_oper.getxattr = s3fs_getxattr; s3fs_oper.listxattr = s3fs_listxattr; s3fs_oper.removexattr = s3fs_removexattr; } s3fs_oper.flag_utime_omit_ok = true; // 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, nullptr); if(fuse_res == 0){ fuse_res = s3fs_init_deferred_exit_status; } fuse_opt_free_args(&custom_args); // Destroy curl if(!S3fsCurl::DestroyS3fsCurl()){ S3FS_PRN_WARN("Could not release curl library."); } s3fs_destroy_global_ssl(); // cleanup xml2 xmlCleanupParser(); S3FS_MALLOCTRIM(0); exit(fuse_res); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
206,546
C++
.cpp
5,076
32.196217
310
0.574936
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,447
gnutls_auth.cpp
s3fs-fuse_s3fs-fuse/src/gnutls_auth.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <unistd.h> #include <syslog.h> #include <sys/types.h> #include <sys/stat.h> #include <gcrypt.h> #include <gnutls/gnutls.h> #include <gnutls/crypto.h> #ifdef USE_GNUTLS_NETTLE #include <nettle/md5.h> #include <nettle/sha1.h> #include <nettle/hmac.h> #endif #include <string> #include <map> #include "common.h" #include "s3fs.h" #include "s3fs_auth.h" #include "s3fs_logger.h" //------------------------------------------------------------------- // Utility Function for version //------------------------------------------------------------------- #ifdef USE_GNUTLS_NETTLE const char* s3fs_crypt_lib_name(void) { static constexpr char version[] = "GnuTLS(nettle)"; return version; } #else // USE_GNUTLS_NETTLE const char* s3fs_crypt_lib_name() { static constexpr char version[] = "GnuTLS(gcrypt)"; return version; } #endif // USE_GNUTLS_NETTLE //------------------------------------------------------------------- // Utility Function for global init //------------------------------------------------------------------- bool s3fs_init_global_ssl() { if(GNUTLS_E_SUCCESS != gnutls_global_init()){ return false; } #ifndef USE_GNUTLS_NETTLE if(nullptr == gcry_check_version(nullptr)){ return false; } #endif // USE_GNUTLS_NETTLE return true; } bool s3fs_destroy_global_ssl() { gnutls_global_deinit(); return true; } //------------------------------------------------------------------- // Utility Function for crypt lock //------------------------------------------------------------------- bool s3fs_init_crypt_mutex() { return true; } bool s3fs_destroy_crypt_mutex() { return true; } //------------------------------------------------------------------- // Utility Function for HMAC //------------------------------------------------------------------- #ifdef USE_GNUTLS_NETTLE std::unique_ptr<unsigned char[]> s3fs_HMAC(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned int* digestlen) { if(!key || !data || !digestlen){ return nullptr; } std::unique_ptr<unsigned char[]> digest(new unsigned char[SHA1_DIGEST_SIZE]); struct hmac_sha1_ctx ctx_hmac; hmac_sha1_set_key(&ctx_hmac, keylen, reinterpret_cast<const uint8_t*>(key)); hmac_sha1_update(&ctx_hmac, datalen, reinterpret_cast<const uint8_t*>(data)); hmac_sha1_digest(&ctx_hmac, SHA1_DIGEST_SIZE, reinterpret_cast<uint8_t*>(digest.get())); *digestlen = SHA1_DIGEST_SIZE; return digest; } std::unique_ptr<unsigned char[]> s3fs_HMAC256(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned int* digestlen) { if(!key || !data || !digestlen){ return nullptr; } std::unique_ptr<unsigned char[]> digest(new unsigned char[SHA256_DIGEST_SIZE]); struct hmac_sha256_ctx ctx_hmac; hmac_sha256_set_key(&ctx_hmac, keylen, reinterpret_cast<const uint8_t*>(key)); hmac_sha256_update(&ctx_hmac, datalen, reinterpret_cast<const uint8_t*>(data)); hmac_sha256_digest(&ctx_hmac, SHA256_DIGEST_SIZE, reinterpret_cast<uint8_t*>(digest.get())); *digestlen = SHA256_DIGEST_SIZE; return digest; } #else // USE_GNUTLS_NETTLE std::unique_ptr<unsigned char[]> s3fs_HMAC(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned int* digestlen) { if(!key || !data || !digestlen){ return nullptr; } if(0 == (*digestlen = gnutls_hmac_get_len(GNUTLS_MAC_SHA1))){ return nullptr; } std::unique_ptr<unsigned char[]> digest(new unsigned char[*digestlen + 1]); if(0 > gnutls_hmac_fast(GNUTLS_MAC_SHA1, key, keylen, data, datalen, digest.get())){ return nullptr; } return digest; } std::unique_ptr<unsigned char[]> s3fs_HMAC256(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned int* digestlen) { if(!key || !data || !digestlen){ return nullptr; } if(0 == (*digestlen = gnutls_hmac_get_len(GNUTLS_MAC_SHA256))){ return nullptr; } std::unique_ptr<unsigned char[]> digest(new unsigned char[*digestlen + 1]); if(0 > gnutls_hmac_fast(GNUTLS_MAC_SHA256, key, keylen, data, datalen, digest.get())){ return nullptr; } return digest; } #endif // USE_GNUTLS_NETTLE //------------------------------------------------------------------- // Utility Function for MD5 //------------------------------------------------------------------- #ifdef USE_GNUTLS_NETTLE bool s3fs_md5(const unsigned char* data, size_t datalen, md5_t* result) { struct md5_ctx ctx_md5; md5_init(&ctx_md5); md5_update(&ctx_md5, datalen, data); md5_digest(&ctx_md5, result->size(), result->data()); return true; } bool s3fs_md5_fd(int fd, off_t start, off_t size, md5_t* result) { struct md5_ctx ctx_md5; off_t bytes; if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ return false; } size = st.st_size; } md5_init(&ctx_md5); for(off_t total = 0; total < size; total += bytes){ std::array<char, 512> buf; bytes = std::min(static_cast<off_t>(buf.size()), (size - total)); bytes = pread(fd, buf.data(), bytes, start + total); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); return false; } md5_update(&ctx_md5, bytes, reinterpret_cast<const uint8_t*>(buf.data())); } md5_digest(&ctx_md5, result->size(), result->data()); return true; } #else // USE_GNUTLS_NETTLE bool s3fs_md5(const unsigned char* data, size_t datalen, md5_t* digest) { gcry_md_hd_t ctx_md5; gcry_error_t err; 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 false; } gcry_md_write(ctx_md5, digest->data(), digest->size()); gcry_md_close(ctx_md5); return true; } bool s3fs_md5_fd(int fd, off_t start, off_t size, md5_t* result) { gcry_md_hd_t ctx_md5; gcry_error_t err; off_t bytes; if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ return false; } size = st.st_size; } 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 false; } for(off_t total = 0; total < size; total += bytes){ std::array<char, 512> buf; bytes = std::min(static_cast<off_t>(buf.size()), (size - total)); bytes = pread(fd, buf.data(), bytes, start + total); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); gcry_md_close(ctx_md5); return false; } gcry_md_write(ctx_md5, buf.data(), bytes); } memcpy(result->data(), gcry_md_read(ctx_md5, 0), result->size()); gcry_md_close(ctx_md5); return true; } #endif // USE_GNUTLS_NETTLE //------------------------------------------------------------------- // Utility Function for SHA256 //------------------------------------------------------------------- #ifdef USE_GNUTLS_NETTLE bool s3fs_sha256(const unsigned char* data, size_t datalen, sha256_t* digest) { struct sha256_ctx ctx_sha256; sha256_init(&ctx_sha256); sha256_update(&ctx_sha256, datalen, data); sha256_digest(&ctx_sha256, digest->size(), digest->data()); return true; } bool s3fs_sha256_fd(int fd, off_t start, off_t size, sha256_t* result) { struct sha256_ctx ctx_sha256; off_t bytes; sha256_init(&ctx_sha256); for(off_t total = 0; total < size; total += bytes){ std::array<char, 512> buf; bytes = std::min(static_cast<off_t>(buf.size()), (size - total)); bytes = pread(fd, buf.data(), bytes, start + total); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); return false; } sha256_update(&ctx_sha256, bytes, reinterpret_cast<const uint8_t*>(buf.data())); } sha256_digest(&ctx_sha256, result->size(), result->data()); return true; } #else // USE_GNUTLS_NETTLE bool s3fs_sha256(const unsigned char* data, size_t datalen, sha256_t* digest) { 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)); return false; } gcry_md_write(ctx_sha256, data, datalen); memcpy(digest->data(), gcry_md_read(ctx_sha256, 0), digest->size()); gcry_md_close(ctx_sha256); return true; } bool s3fs_sha256_fd(int fd, off_t start, off_t size, sha256_t* result) { gcry_md_hd_t ctx_sha256; gcry_error_t err; off_t bytes; if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ return false; } size = st.st_size; } 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 false; } for(off_t total = 0; total < size; total += bytes){ std::array<char, 512> buf; bytes = std::min(static_cast<off_t>(buf.size()), (size - total)); bytes = pread(fd, buf.data(), bytes, start + total); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); gcry_md_close(ctx_sha256); return false; } gcry_md_write(ctx_sha256, buf.data(), bytes); } memcpy(result->data(), gcry_md_read(ctx_sha256, 0), result->size()); gcry_md_close(ctx_sha256); return true; } #endif // USE_GNUTLS_NETTLE /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
11,350
C++
.cpp
330
29.484848
145
0.584033
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,449
test_string_util.cpp
s3fs-fuse_s3fs-fuse/src/test_string_util.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2014 Andrew Gaul <andrew@gaul.org> * * 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 <cstdint> #include <cstdlib> #include <limits> #include <string> #include "s3fs_logger.h" #include "string_util.h" #include "test_util.h" //------------------------------------------------------------------- // Global variables for test_string_util //------------------------------------------------------------------- bool foreground = false; std::string instance_name; 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("1234"), peeloff("\"1234\"")); // "1234" -> 1234 ASSERT_EQUALS(std::string("\"1234\""), peeloff("\"\"1234\"\"")); // ""1234"" -> "1234" ASSERT_EQUALS(std::string("\"1234"), peeloff("\"\"1234\"")); // ""1234" -> "1234 ASSERT_EQUALS(std::string("1234\""), peeloff("\"1234\"\"")); // "1234"" -> 1234" ASSERT_EQUALS(std::string("\"1234"), peeloff("\"1234")); // "1234 -> "1234 ASSERT_EQUALS(std::string("1234\""), peeloff("1234\"")); // 1234" -> 1234" ASSERT_EQUALS(std::string(" \"1234\""), peeloff(" \"1234\"")); // _"1234" -> _"1234" ASSERT_EQUALS(std::string("\"1234\" "), peeloff("\"1234\" ")); // "1234"_ -> "1234"_ } void test_base64() { std::string buf; char tmpbuf = '\0'; ASSERT_EQUALS(s3fs_base64(nullptr, 0), std::string("")); buf = s3fs_decode64(nullptr, 0); ASSERT_BUFEQUALS(buf.c_str(), buf.length(), &tmpbuf, 0); ASSERT_EQUALS(s3fs_base64(reinterpret_cast<const unsigned char *>(""), 0), std::string("")); buf = s3fs_decode64("", 0); ASSERT_BUFEQUALS(buf.c_str(), buf.length(), &tmpbuf, 0); ASSERT_EQUALS(s3fs_base64(reinterpret_cast<const unsigned char *>("1"), 1), std::string("MQ==")); buf = s3fs_decode64("MQ==", 4); ASSERT_BUFEQUALS(buf.c_str(), buf.length(), "1", 1); ASSERT_EQUALS(buf.length(), static_cast<size_t>(1)); ASSERT_EQUALS(s3fs_base64(reinterpret_cast<const unsigned char *>("12"), 2), std::string("MTI=")); buf = s3fs_decode64("MTI=", 4); ASSERT_BUFEQUALS(buf.c_str(), buf.length(), "12", 2); ASSERT_EQUALS(buf.length(), static_cast<size_t>(2)); ASSERT_EQUALS(s3fs_base64(reinterpret_cast<const unsigned char *>("123"), 3), std::string("MTIz")); buf = s3fs_decode64("MTIz", 4); ASSERT_BUFEQUALS(buf.c_str(), buf.length(), "123", 3); ASSERT_EQUALS(buf.length(), static_cast<size_t>(3)); ASSERT_EQUALS(s3fs_base64(reinterpret_cast<const unsigned char *>("1234"), 4), std::string("MTIzNA==")); buf = s3fs_decode64("MTIzNA==", 8); ASSERT_BUFEQUALS(buf.c_str(), buf.length(), "1234", 4); ASSERT_EQUALS(buf.length(), static_cast<size_t>(4)); // TODO: invalid input } void test_strtoofft() { off_t value; ASSERT_TRUE(s3fs_strtoofft(&value, "0")); ASSERT_EQUALS(value, static_cast<off_t>(0L)); ASSERT_TRUE(s3fs_strtoofft(&value, "9")); ASSERT_EQUALS(value, static_cast<off_t>(9L)); ASSERT_FALSE(s3fs_strtoofft(&value, "A")); ASSERT_TRUE(s3fs_strtoofft(&value, "A", /*base=*/ 16)); ASSERT_EQUALS(value, static_cast<off_t>(10L)); ASSERT_TRUE(s3fs_strtoofft(&value, "F", /*base=*/ 16)); ASSERT_EQUALS(value, static_cast<off_t>(15L)); ASSERT_TRUE(s3fs_strtoofft(&value, "a", /*base=*/ 16)); ASSERT_EQUALS(value, static_cast<off_t>(10L)); ASSERT_TRUE(s3fs_strtoofft(&value, "f", /*base=*/ 16)); ASSERT_EQUALS(value, static_cast<off_t>(15L)); ASSERT_TRUE(s3fs_strtoofft(&value, "deadbeef", /*base=*/ 16)); ASSERT_EQUALS(value, static_cast<off_t>(3735928559L)); } void test_wtf8_encoding() { std::string ascii("normal std::string"); std::string utf8("Hyld\xc3\xbdpi \xc3\xbej\xc3\xb3\xc3\xb0""f\xc3\xa9lagsins vex \xc3\xbar k\xc3\xa6rkomnu b\xc3\xb6li \xc3\xad \xc3\xa1st"); std::string cp1252("Hyld\xfdpi \xfej\xf3\xf0""f\xe9lagsins vex \xfar k\xe6rkomnu b\xf6li \xed \xe1st"); std::string broken = utf8; broken[14] = '\x97'; std::string mixed = ascii + utf8 + cp1252; ASSERT_EQUALS(s3fs_wtf8_encode(ascii), ascii); ASSERT_EQUALS(s3fs_wtf8_decode(ascii), ascii); ASSERT_EQUALS(s3fs_wtf8_encode(utf8), utf8); ASSERT_EQUALS(s3fs_wtf8_decode(utf8), utf8); ASSERT_NEQUALS(s3fs_wtf8_encode(cp1252), cp1252); ASSERT_EQUALS(s3fs_wtf8_decode(s3fs_wtf8_encode(cp1252)), cp1252); ASSERT_NEQUALS(s3fs_wtf8_encode(broken), broken); ASSERT_EQUALS(s3fs_wtf8_decode(s3fs_wtf8_encode(broken)), broken); ASSERT_NEQUALS(s3fs_wtf8_encode(mixed), mixed); ASSERT_EQUALS(s3fs_wtf8_decode(s3fs_wtf8_encode(mixed)), mixed); } void test_cr_encoding() { // bse strings std::string base_no("STR"); std::string base_end_cr1("STR\r"); std::string base_mid_cr1("STR\rSTR"); std::string base_end_cr2("STR\r\r"); std::string base_mid_cr2("STR\r\rSTR"); std::string base_end_per1("STR%"); std::string base_mid_per1("STR%STR"); std::string base_end_per2("STR%%"); std::string base_mid_per2("STR%%STR"); std::string base_end_crlf1("STR\r\n"); std::string base_mid_crlf1("STR\r\nSTR"); std::string base_end_crlf2("STR\r\n\r\n"); std::string base_mid_crlf2("STR\r\n\r\nSTR"); std::string base_end_crper1("STR%\r"); std::string base_mid_crper1("STR%\rSTR"); std::string base_end_crper2("STR%\r%\r"); std::string base_mid_crper2("STR%\r%\rSTR"); // encode->decode->compare ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_no.c_str()).c_str()), base_no); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_end_cr1.c_str()).c_str()), base_end_cr1); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_mid_cr1.c_str()).c_str()), base_mid_cr1); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_end_cr2.c_str()).c_str()), base_end_cr2); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_mid_cr2.c_str()).c_str()), base_mid_cr2); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_end_per1.c_str()).c_str()), base_end_per1); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_mid_per1.c_str()).c_str()), base_mid_per1); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_end_per2.c_str()).c_str()), base_end_per2); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_mid_per2.c_str()).c_str()), base_mid_per2); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_end_crlf1.c_str()).c_str()), base_end_crlf1); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_mid_crlf1.c_str()).c_str()), base_mid_crlf1); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_end_crlf2.c_str()).c_str()), base_end_crlf2); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_mid_crlf2.c_str()).c_str()), base_mid_crlf2); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_end_crper1.c_str()).c_str()), base_end_crper1); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_mid_crper1.c_str()).c_str()), base_mid_crper1); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_end_crper2.c_str()).c_str()), base_end_crper2); ASSERT_EQUALS(get_decoded_cr_code(get_encoded_cr_code(base_mid_crper2.c_str()).c_str()), base_mid_crper2); } int main(int argc, const char *argv[]) { S3fsLog singletonLog; test_trim(); test_base64(); test_strtoofft(); test_wtf8_encoding(); test_cr_encoding(); return 0; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
9,093
C++
.cpp
177
47.316384
145
0.642849
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,450
string_util.cpp
s3fs-fuse_s3fs-fuse/src/string_util.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <algorithm> #include <cstdlib> #include <cstring> #include <cerrno> #include <climits> #include <iomanip> #include <sstream> #include <string> #include <utility> #include "s3fs_logger.h" #include "string_util.h" //------------------------------------------------------------------- // Global variables //------------------------------------------------------------------- //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- std::string str(const struct timespec& value) { std::ostringstream s; s << value.tv_sec; if(value.tv_nsec != 0){ s << "." << std::setfill('0') << std::setw(9) << value.tv_nsec; } return s.str(); } // This source code is from https://gist.github.com/jeremyfromearth/5694aa3a66714254752179ecf3c95582 . const char* s3fs_strptime(const char* s, const char* f, struct tm* tm) { std::istringstream input(s); // TODO: call to setlocale required? input.imbue(std::locale(setlocale(LC_ALL, nullptr))); input >> std::get_time(tm, f); if (input.fail()) { return nullptr; } return s + input.tellg(); } bool s3fs_strtoofft(off_t* value, const char* str, int base) { if(value == nullptr || str == nullptr){ return false; } errno = 0; char *temp; long long result = strtoll(str, &temp, base); if(temp == str || *temp != '\0'){ return false; } if((result == LLONG_MIN || result == LLONG_MAX) && errno == ERANGE){ return false; } *value = result; return true; } off_t cvt_strtoofft(const char* str, int base) { off_t result = 0; if(!s3fs_strtoofft(&result, str, base)){ S3FS_PRN_WARN("something error is occurred in convert std::string(%s) to off_t, thus return 0 as default.", (str ? str : "null")); return 0; } return result; } std::string lower(std::string s) { std::transform(s.cbegin(), s.cend(), s.begin(), ::tolower); return s; } std::string upper(std::string s) { std::transform(s.cbegin(), s.cend(), s.begin(), ::toupper); return s; } std::string trim_left(std::string d, const char *t /* = SPACES */) { return d.erase(0, d.find_first_not_of(t)); } std::string trim_right(std::string d, const char *t /* = SPACES */) { std::string::size_type i(d.find_last_not_of(t)); if(i == std::string::npos){ return ""; }else{ return d.erase(d.find_last_not_of(t) + 1); } } std::string trim(std::string s, const char *t /* = SPACES */) { return trim_left(trim_right(std::move(s), t), t); } std::string peeloff(std::string s) { if(s.size() < 2 || *s.cbegin() != '"' || *s.rbegin() != '"'){ return s; } s.erase(s.size() - 1); s.erase(0, 1); return s; } // // Three url encode functions // // urlEncodeGeneral: A general URL encoding function. // urlEncodePath : A function that URL encodes by excluding the path // separator('/'). // urlEncodeQuery : A function that does URL encoding by excluding // some characters('=', '&' and '%'). // This function can be used when the target string // contains already URL encoded strings. It also // excludes the character () used in query strings. // Therefore, it is a function to use as URL encoding // for use in query strings. // static constexpr char encode_general_except_chars[] = ".-_~"; // For general URL encode static constexpr char encode_path_except_chars[] = ".-_~/"; // For fuse(included path) URL encode static constexpr char encode_query_except_chars[] = ".-_~=&%"; // For query params(and encoded string) static std::string rawUrlEncode(const std::string &s, const char* except_chars) { std::string result; for (size_t i = 0; i < s.length(); ++i) { unsigned char c = s[i]; if((except_chars && nullptr != strchr(except_chars, c)) || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ) { result += c; }else{ result += "%"; result += s3fs_hex_upper(&c, 1); } } return result; } std::string urlEncodeGeneral(const std::string &s) { return rawUrlEncode(s, encode_general_except_chars); } std::string urlEncodePath(const std::string &s) { return rawUrlEncode(s, encode_path_except_chars); } std::string urlEncodeQuery(const std::string &s) { return rawUrlEncode(s, encode_query_except_chars); } std::string urlDecode(const std::string& s) { std::string result; for(size_t i = 0; i < s.length(); ++i){ if(s[i] != '%'){ result += s[i]; }else{ int 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 += static_cast<char>(ch); } } return result; } bool takeout_str_dquart(std::string& str) { size_t pos; // '"' for start if(std::string::npos != (pos = str.find_first_of('\"'))){ str.erase(0, pos + 1); // '"' for end if(std::string::npos == (pos = str.find_last_of('\"'))){ return false; } str.erase(pos); if(std::string::npos != str.find_first_of('\"')){ return false; } } return true; } // // ex. target="http://......?keyword=value&..." // bool get_keyword_value(const std::string& target, const char* keyword, std::string& value) { if(!keyword){ return false; } size_t spos; size_t epos; if(std::string::npos == (spos = target.find(keyword))){ return false; } spos += strlen(keyword); if('=' != target[spos]){ return false; } spos++; if(std::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. // std::string get_date_rfc850() { char buf[100]; time_t t = time(nullptr); struct tm res; strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", gmtime_r(&t, &res)); return buf; } void get_date_sigv3(std::string& date, std::string& date8601) { time_t tm = time(nullptr); date = get_date_string(tm); date8601 = get_date_iso8601(tm); } std::string get_date_string(time_t tm) { char buf[100]; struct tm res; strftime(buf, sizeof(buf), "%Y%m%d", gmtime_r(&tm, &res)); return buf; } std::string get_date_iso8601(time_t tm) { char buf[100]; struct tm res; strftime(buf, sizeof(buf), "%Y%m%dT%H%M%SZ", gmtime_r(&tm, &res)); return buf; } bool get_unixtime_from_iso8601(const char* pdate, time_t& unixtime) { if(!pdate){ return false; } struct tm tm; const char* prest = s3fs_strptime(pdate, "%Y-%m-%dT%T", &tm); if(prest == pdate){ // wrong format return false; } unixtime = mktime(&tm); return true; } // // Convert to unixtime from std::string which formatted by following: // "12Y12M12D12h12m12s", "86400s", "9h30m", etc // bool convert_unixtime_from_option_arg(const char* argv, time_t& unixtime) { if(!argv){ return false; } unixtime = 0; const char* ptmp; int last_unit_type = 0; // unit flag. bool is_last_number; time_t tmptime; for(ptmp = argv, is_last_number = true, tmptime = 0; ptmp && *ptmp; ++ptmp){ if('0' <= *ptmp && *ptmp <= '9'){ tmptime *= 10; tmptime += static_cast<time_t>(*ptmp - '0'); is_last_number = true; }else if(is_last_number){ if('Y' == *ptmp && 1 > last_unit_type){ unixtime += (tmptime * (60 * 60 * 24 * 365)); // average 365 day / year last_unit_type = 1; }else if('M' == *ptmp && 2 > last_unit_type){ unixtime += (tmptime * (60 * 60 * 24 * 30)); // average 30 day / month last_unit_type = 2; }else if('D' == *ptmp && 3 > last_unit_type){ unixtime += (tmptime * (60 * 60 * 24)); last_unit_type = 3; }else if('h' == *ptmp && 4 > last_unit_type){ unixtime += (tmptime * (60 * 60)); last_unit_type = 4; }else if('m' == *ptmp && 5 > last_unit_type){ unixtime += (tmptime * 60); last_unit_type = 5; }else if('s' == *ptmp && 6 > last_unit_type){ unixtime += tmptime; last_unit_type = 6; }else{ return false; } tmptime = 0; is_last_number = false; }else{ return false; } } if(is_last_number){ return false; } return true; } static std::string s3fs_hex(const unsigned char* input, size_t length, const char *hexAlphabet) { std::string hex; for(size_t pos = 0; pos < length; ++pos){ hex += hexAlphabet[input[pos] / 16]; hex += hexAlphabet[input[pos] % 16]; } return hex; } std::string s3fs_hex_lower(const unsigned char* input, size_t length) { return s3fs_hex(input, length, "0123456789abcdef"); } std::string s3fs_hex_upper(const unsigned char* input, size_t length) { return s3fs_hex(input, length, "0123456789ABCDEF"); } std::string s3fs_base64(const unsigned char* input, size_t length) { static constexpr char base[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; std::string result; result.reserve(((length + 3 - 1) / 3) * 4 + 1); unsigned char parts[4]; size_t rpos; for(rpos = 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 += base[parts[0]]; result += base[parts[1]]; result += base[parts[2]]; result += base[parts[3]]; } return result; } static inline unsigned char char_decode64(const char ch) { unsigned char by; if('A' <= ch && ch <= 'Z'){ // A - Z by = static_cast<unsigned char>(ch - 'A'); }else if('a' <= ch && ch <= 'z'){ // a - z by = static_cast<unsigned char>(ch - 'a' + 26); }else if('0' <= ch && ch <= '9'){ // 0 - 9 by = static_cast<unsigned char>(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; } std::string s3fs_decode64(const char* input, size_t input_len) { std::string result; result.reserve(input_len / 4 * 3); unsigned char parts[4]; size_t rpos; for(rpos = 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 += static_cast<char>(((parts[0] << 2) & 0xfc) | ((parts[1] >> 4) & 0x03)); if(64 == parts[2]){ break; } result += static_cast<char>(((parts[1] << 4) & 0xf0) | ((parts[2] >> 2) & 0x0f)); if(64 == parts[3]){ break; } result += static_cast<char>(((parts[2] << 6) & 0xc0) | (parts[3] & 0x3f)); } return result; } // // detect and rewrite invalid utf8. We take invalid bytes // and encode them into a private region of the unicode // space. This is sometimes known as wtf8, wobbly transformation format. // it is necessary because S3 validates the utf8 used for identifiers for // correctness, while some clients may provide invalid utf, notably // windows using cp1252. // // Base location for transform. The range 0xE000 - 0xF8ff // is a private range, se use the start of this range. static constexpr unsigned int escape_base = 0xe000; // encode bytes into wobbly utf8. // 'result' can be null. returns true if transform was needed. bool s3fs_wtf8_encode(const char *s, std::string *result) { bool invalid = false; // Pass valid utf8 code through for (; *s; s++) { const unsigned char c = *s; // single byte encoding if (c <= 0x7f) { if (result) { *result += c; } continue; } // otherwise, it must be one of the valid start bytes if ( c >= 0xc2 && c <= 0xf5 ) { // two byte encoding // don't need bounds check, std::string is zero terminated if ((c & 0xe0) == 0xc0 && (s[1] & 0xc0) == 0x80) { // all two byte encodings starting higher than c1 are valid if (result) { *result += c; *result += *(++s); } continue; } // three byte encoding if ((c & 0xf0) == 0xe0 && (s[1] & 0xc0) == 0x80 && (s[2] & 0xc0) == 0x80) { const unsigned code = ((c & 0x0f) << 12) | ((s[1] & 0x3f) << 6) | (s[2] & 0x3f); if (code >= 0x800 && ! (code >= 0xd800 && code <= 0xd8ff)) { // not overlong and not a surrogate pair if (result) { *result += c; *result += *(++s); *result += *(++s); } continue; } } // four byte encoding if ((c & 0xf8) == 0xf0 && (s[1] & 0xc0) == 0x80 && (s[2] & 0xc0) == 0x80 && (s[3] & 0xc0) == 0x80) { const unsigned code = ((c & 0x07) << 18) | ((s[1] & 0x3f) << 12) | ((s[2] & 0x3f) << 6) | (s[3] & 0x3f); if (code >= 0x10000 && code <= 0x10ffff) { // not overlong and in defined unicode space if (result) { *result += c; *result += *(++s); *result += *(++s); *result += *(++s); } continue; } } } // printf("invalid %02x at %d\n", c, i); // Invalid utf8 code. Convert it to a private two byte area of unicode // e.g. the e000 - f8ff area. This will be a three byte encoding invalid = true; if (result) { unsigned escape = escape_base + c; *result += static_cast<char>(0xe0 | ((escape >> 12) & 0x0f)); *result += static_cast<char>(0x80 | ((escape >> 06) & 0x3f)); *result += static_cast<char>(0x80 | ((escape >> 00) & 0x3f)); } } return invalid; } std::string s3fs_wtf8_encode(const std::string &s) { std::string result; s3fs_wtf8_encode(s.c_str(), &result); return result; } // The reverse operation, turn encoded bytes back into their original values // The code assumes that we map to a three-byte code point. bool s3fs_wtf8_decode(const char *s, std::string *result) { bool encoded = false; for (; *s; s++) { unsigned char c = *s; // look for a three byte tuple matching our encoding code if ((c & 0xf0) == 0xe0 && (s[1] & 0xc0) == 0x80 && (s[2] & 0xc0) == 0x80) { unsigned code = (c & 0x0f) << 12; code |= (s[1] & 0x3f) << 6; code |= (s[2] & 0x3f) << 0; if (code >= escape_base && code <= escape_base + 0xff) { // convert back encoded = true; if(result){ *result += static_cast<char>(code - escape_base); } s+=2; continue; } } if (result) { *result += c; } } return encoded; } std::string s3fs_wtf8_decode(const std::string &s) { std::string result; s3fs_wtf8_decode(s.c_str(), &result); return result; } // // Encode only CR('\r'=0x0D) and it also encodes the '%' character accordingly. // // The xmlReadMemory() function in libxml2 replaces CR code with LF code('\n'=0x0A) // due to the XML specification. // s3fs uses libxml2 to parse the S3 response, and this automatic substitution // of libxml2 may change the object name(file/dir name). Therefore, before passing // the response to the xmlReadMemory() function, we need the string encoded by // this function. // // [NOTE] // Normally the quotes included in the XML content data are HTML encoded("&quot;"). // Encoding for CR can also be HTML encoded as binary code (ex, "&#13;"), but // if the same string content(as file name) as this encoded string exists, the // original string cannot be distinguished whichever encoded or not encoded. // Therefore, CR is encoded in the same manner as URL encoding("%0A"). // And it is assumed that there is no CR code in the S3 response tag etc.(actually // it shouldn't exist) // std::string get_encoded_cr_code(const char* pbase) { std::string result; if(!pbase){ return result; } std::string strbase(pbase); size_t baselength = strbase.length(); size_t startpos = 0; size_t foundpos; while(startpos < baselength && std::string::npos != (foundpos = strbase.find_first_of("%\r", startpos))){ if(0 < (foundpos - startpos)){ result += strbase.substr(startpos, foundpos - startpos); } if('%' == strbase[foundpos]){ result += "%45"; }else if('\r' == strbase[foundpos]){ result += "%0D"; } startpos = foundpos + 1; } if(startpos < baselength){ result += strbase.substr(startpos); } return result; } // // Decode a string encoded with get_encoded_cr_code(). // std::string get_decoded_cr_code(const char* pencode) { std::string result; if(!pencode){ return result; } std::string strencode(pencode); size_t encodelength = strencode.length(); size_t startpos = 0; size_t foundpos; while(startpos < encodelength && std::string::npos != (foundpos = strencode.find('%', startpos))){ if(0 < (foundpos - startpos)){ result += strencode.substr(startpos, foundpos - startpos); } if((foundpos + 2) < encodelength && 0 == strencode.compare(foundpos, 3, "%45")){ result += '%'; startpos = foundpos + 3; }else if((foundpos + 2) < encodelength && 0 == strencode.compare(foundpos, 3, "%0D")){ result += '\r'; startpos = foundpos + 3; }else if((foundpos + 1) < encodelength && 0 == strencode.compare(foundpos, 2, "%%")){ result += '%'; startpos = foundpos + 2; }else{ result += '%'; startpos = foundpos + 1; } } if(startpos < encodelength){ result += strencode.substr(startpos); } return result; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
21,146
C++
.cpp
615
27.982114
175
0.533848
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,451
metaheader.cpp
s3fs-fuse_s3fs-fuse/src/metaheader.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <ctime> #include <string> #include <sys/stat.h> #include <unistd.h> #include "common.h" #include "metaheader.h" #include "string_util.h" static constexpr struct timespec DEFAULT_TIMESPEC = {-1, 0}; //------------------------------------------------------------------- // Utility functions for convert //------------------------------------------------------------------- static struct timespec cvt_string_to_time(const char *str) { // [NOTE] // In rclone, there are cases where ns is set to x-amz-meta-mtime // with floating point number. s3fs uses x-amz-meta-mtime by // truncating the floating point or less (in seconds or less) to // correspond to this. // std::string strmtime; long nsec = 0; if(str && '\0' != *str){ strmtime = str; std::string::size_type pos = strmtime.find('.', 0); if(std::string::npos != pos){ nsec = cvt_strtoofft(strmtime.substr(pos + 1).c_str(), /*base=*/ 10); strmtime.erase(pos); } } struct timespec ts = {static_cast<time_t>(cvt_strtoofft(strmtime.c_str(), /*base=*/ 10)), nsec}; return ts; } static struct timespec get_time(const headers_t& meta, const char *header) { headers_t::const_iterator iter; if(meta.cend() == (iter = meta.find(header))){ return DEFAULT_TIMESPEC; } return cvt_string_to_time((*iter).second.c_str()); } struct timespec get_mtime(const headers_t& meta, bool overcheck) { struct timespec t = get_time(meta, "x-amz-meta-mtime"); if(0 < t.tv_sec){ return t; } t = get_time(meta, "x-amz-meta-goog-reserved-file-mtime"); if(0 < t.tv_sec){ return t; } if(overcheck){ struct timespec ts = {get_lastmodified(meta), 0}; return ts; } return DEFAULT_TIMESPEC; } struct timespec get_ctime(const headers_t& meta, bool overcheck) { struct timespec t = get_time(meta, "x-amz-meta-ctime"); if(0 < t.tv_sec){ return t; } if(overcheck){ struct timespec ts = {get_lastmodified(meta), 0}; return ts; } return DEFAULT_TIMESPEC; } struct timespec get_atime(const headers_t& meta, bool overcheck) { struct timespec t = get_time(meta, "x-amz-meta-atime"); if(0 < t.tv_sec){ return t; } if(overcheck){ struct timespec ts = {get_lastmodified(meta), 0}; return ts; } return DEFAULT_TIMESPEC; } off_t get_size(const char *s) { return cvt_strtoofft(s, /*base=*/ 10); } off_t get_size(const headers_t& meta) { auto iter = meta.find("Content-Length"); if(meta.cend() == iter){ return 0; } return get_size((*iter).second.c_str()); } mode_t get_mode(const char *s, int base) { return static_cast<mode_t>(cvt_strtoofft(s, base)); } mode_t get_mode(const headers_t& meta, const std::string& strpath, bool checkdir, bool forcedir) { mode_t mode = 0; bool isS3sync = false; headers_t::const_iterator iter; if(meta.cend() != (iter = meta.find("x-amz-meta-mode"))){ mode = get_mode((*iter).second.c_str()); }else if(meta.cend() != (iter = meta.find("x-amz-meta-permissions"))){ // for s3sync mode = get_mode((*iter).second.c_str()); isS3sync = true; }else if(meta.cend() != (iter = meta.find("x-amz-meta-goog-reserved-posix-mode"))){ // for GCS mode = get_mode((*iter).second.c_str(), 8); }else{ // If another tool creates an object without permissions, default to owner // read-write and group readable. mode = (!strpath.empty() && '/' == *strpath.rbegin()) ? 0750 : 0640; } // 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.cend() != (iter = meta.find("Content-Type"))){ std::string strConType = (*iter).second; // Leave just the mime type, remove any optional parameters (eg charset) std::string::size_type pos = strConType.find(';'); if(std::string::npos != pos){ strConType.erase(pos); } if(strConType == "application/x-directory" || strConType == "httpd/unix-directory"){ // Nextcloud uses this MIME type for directory objects when mounting bucket as external Storage mode |= S_IFDIR; }else if(!strpath.empty() && '/' == *strpath.rbegin()){ if(strConType == "binary/octet-stream" || strConType == "application/octet-stream"){ mode |= S_IFDIR; }else{ if(complement_stat){ // If complement lack stat mode, when the object has '/' character at end of name // and content type is text/plain and the object's size is 0 or 1, it should be // directory. off_t size = get_size(meta); if(strConType == "text/plain" && (0 == size || 1 == size)){ mode |= S_IFDIR; }else{ mode |= S_IFREG; } }else{ mode |= S_IFREG; } } }else{ mode |= S_IFREG; } }else{ mode |= S_IFREG; } } } // If complement lack stat mode, when it's mode is not set any permission, // the object is added minimal mode only for read permission. if(complement_stat && 0 == (mode & (S_IRWXU | S_IRWXG | S_IRWXO))){ mode |= (S_IRUSR | (0 == (mode & S_IFDIR) ? 0 : S_IXUSR)); } }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<uid_t>(cvt_strtoofft(s, /*base=*/ 0)); } uid_t get_uid(const headers_t& meta) { headers_t::const_iterator iter; if(meta.cend() != (iter = meta.find("x-amz-meta-uid"))){ return get_uid((*iter).second.c_str()); }else if(meta.cend() != (iter = meta.find("x-amz-meta-owner"))){ // for s3sync return get_uid((*iter).second.c_str()); }else if(meta.cend() != (iter = meta.find("x-amz-meta-goog-reserved-posix-uid"))){ // for GCS return get_uid((*iter).second.c_str()); }else{ return geteuid(); } } gid_t get_gid(const char *s) { return static_cast<gid_t>(cvt_strtoofft(s, /*base=*/ 0)); } gid_t get_gid(const headers_t& meta) { headers_t::const_iterator iter; if(meta.cend() != (iter = meta.find("x-amz-meta-gid"))){ return get_gid((*iter).second.c_str()); }else if(meta.cend() != (iter = meta.find("x-amz-meta-group"))){ // for s3sync return get_gid((*iter).second.c_str()); }else if(meta.cend() != (iter = meta.find("x-amz-meta-goog-reserved-posix-gid"))){ // for GCS return get_gid((*iter).second.c_str()); }else{ return getegid(); } } blkcnt_t get_blocks(off_t size) { return (size / 512) + (0 == (size % 512) ? 0 : 1); } time_t cvtIAMExpireStringToTime(const char* s) { struct tm tm{}; if(!s){ return 0L; } s3fs_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 -1; } s3fs_strptime(s, "%a, %d %b %Y %H:%M:%S %Z", &tm); return timegm(&tm); // GMT } time_t get_lastmodified(const headers_t& meta) { auto iter = meta.find("Last-Modified"); if(meta.cend() == iter){ return -1; } 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(const 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.cend() != meta.find("x-amz-meta-mode") || meta.cend() != meta.find("x-amz-meta-mtime") || meta.cend() != meta.find("x-amz-meta-ctime") || meta.cend() != meta.find("x-amz-meta-atime") || meta.cend() != meta.find("x-amz-meta-uid") || meta.cend() != meta.find("x-amz-meta-gid") || meta.cend() != meta.find("x-amz-meta-owner") || meta.cend() != meta.find("x-amz-meta-group") || meta.cend() != 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.cend() == (iter = meta.find("Content-Type"))){ return false; } if("application/x-directory" == (*iter).second){ return false; } return true; } // [NOTE] // If add_noexist is false and the key does not exist, it will not be added. // bool merge_headers(headers_t& base, const headers_t& additional, bool add_noexist) { bool added = false; for(auto iter = additional.cbegin(); iter != additional.cend(); ++iter){ if(add_noexist || base.find(iter->first) != base.cend()){ base[iter->first] = iter->second; added = true; } } return added; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
11,267
C++
.cpp
313
28.191693
123
0.554722
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,452
s3fs_cred.cpp
s3fs-fuse_s3fs-fuse/src/s3fs_cred.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <cerrno> #include <unistd.h> #include <pwd.h> #include <sys/stat.h> #include <dlfcn.h> #include <fstream> #include <mutex> #include <sstream> #include <string> #include "common.h" #include "s3fs_cred.h" #include "s3fs_help.h" #include "s3fs_logger.h" #include "curl.h" #include "string_util.h" #include "metaheader.h" #include "threadpoolman.h" #include "s3fs_threadreqs.h" //------------------------------------------------------------------- // Symbols //------------------------------------------------------------------- static constexpr char DEFAULT_AWS_PROFILE_NAME[] = "default"; //------------------------------------------------------------------- // External Credential dummy function //------------------------------------------------------------------- // [NOTE] // This function expects the following values: // // detail=false ex. "Custom AWS Credential Library - v1.0.0" // detail=true ex. "Custom AWS Credential Library - v1.0.0 // s3fs-fuse credential I/F library for S3 compatible storage X. // Copyright(C) 2022 Foo" // const char* VersionS3fsCredential(bool detail) { static constexpr char version[] = "built-in"; static constexpr char detail_version[] = "s3fs-fuse built-in Credential I/F Function\n" "Copyright(C) 2007 s3fs-fuse\n"; if(detail){ return detail_version; }else{ return version; } } bool InitS3fsCredential(const char* popts, char** pperrstr) { if(popts && 0 < strlen(popts)){ S3FS_PRN_WARN("The external credential library does not have InitS3fsCredential function, but credlib_opts value is not empty(%s)", popts); } if(pperrstr){ *pperrstr = strdup("The external credential library does not have InitS3fsCredential function, so built-in function was called."); }else{ S3FS_PRN_INFO("The external credential library does not have InitS3fsCredential function, so built-in function was called."); } return true; } bool FreeS3fsCredential(char** pperrstr) { if(pperrstr){ *pperrstr = strdup("The external credential library does not have FreeS3fsCredential function, so built-in function was called."); }else{ S3FS_PRN_INFO("The external credential library does not have FreeS3fsCredential function, so built-in function was called."); } return true; } bool UpdateS3fsCredential(char** ppaccess_key_id, char** ppserect_access_key, char** ppaccess_token, long long* ptoken_expire, char** pperrstr) { S3FS_PRN_INFO("Parameters : ppaccess_key_id=%p, ppserect_access_key=%p, ppaccess_token=%p, ptoken_expire=%p", ppaccess_key_id, ppserect_access_key, ppaccess_token, ptoken_expire); if(pperrstr){ *pperrstr = strdup("Check why built-in function was called, the external credential library must have UpdateS3fsCredential function."); }else{ S3FS_PRN_CRIT("Check why built-in function was called, the external credential library must have UpdateS3fsCredential function."); } if(ppaccess_key_id){ *ppaccess_key_id = nullptr; } if(ppserect_access_key){ *ppserect_access_key = nullptr; } if(ppaccess_token){ *ppaccess_token = nullptr; } return false; // always false } //------------------------------------------------------------------- // Class Variables //------------------------------------------------------------------- constexpr char S3fsCred::ALLBUCKET_FIELDS_TYPE[]; constexpr char S3fsCred::KEYVAL_FIELDS_TYPE[]; constexpr char S3fsCred::AWS_ACCESSKEYID[]; constexpr char S3fsCred::AWS_SECRETKEY[]; constexpr char S3fsCred::ECS_IAM_ENV_VAR[]; constexpr char S3fsCred::IAMCRED_ACCESSKEYID[]; constexpr char S3fsCred::IAMCRED_SECRETACCESSKEY[]; constexpr char S3fsCred::IAMCRED_ROLEARN[]; constexpr char S3fsCred::IAMv2_token_url[]; constexpr char S3fsCred::IAMv2_token_ttl_hdr[]; constexpr char S3fsCred::IAMv2_token_hdr[]; std::string S3fsCred::bucket_name; //------------------------------------------------------------------- // Class Methods //------------------------------------------------------------------- bool S3fsCred::SetBucket(const std::string& bucket) { if(bucket.empty()){ return false; } S3fsCred::bucket_name = bucket; return true; } const std::string& S3fsCred::GetBucket() { return S3fsCred::bucket_name; } bool S3fsCred::ParseIAMRoleFromMetaDataResponse(const char* response, std::string& rolename) { if(!response){ return false; } // [NOTE] // expected following strings. // // myrolename // std::istringstream ssrole(response); std::string oneline; if (getline(ssrole, oneline, '\n')){ rolename = oneline; return !rolename.empty(); } return false; } //------------------------------------------------------------------- // Methods : Constructor / Destructor //------------------------------------------------------------------- S3fsCred::S3fsCred() : aws_profile(DEFAULT_AWS_PROFILE_NAME), load_iamrole(false), AWSAccessTokenExpire(0), is_ecs(false), is_use_session_token(false), is_ibm_iam_auth(false), IAM_cred_url("http://169.254.169.254/latest/meta-data/iam/security-credentials/"), IAM_api_version(2), IAM_field_count(4), IAM_token_field("Token"), IAM_expiry_field("Expiration"), set_builtin_cred_opts(false), hExtCredLib(nullptr), pFuncCredVersion(VersionS3fsCredential), pFuncCredInit(InitS3fsCredential), pFuncCredFree(FreeS3fsCredential), pFuncCredUpdate(UpdateS3fsCredential) { } S3fsCred::~S3fsCred() { UnloadExtCredLib(); } //------------------------------------------------------------------- // Methods : Access member variables //------------------------------------------------------------------- bool S3fsCred::SetS3fsPasswdFile(const char* file) { if(!file || strlen(file) == 0){ return false; } passwd_file = file; return true; } bool S3fsCred::IsSetPasswdFile() const { return !passwd_file.empty(); } bool S3fsCred::SetAwsProfileName(const char* name) { if(!name || strlen(name) == 0){ return false; } aws_profile = name; return true; } bool S3fsCred::SetIAMRoleMetadataType(bool flag) { bool old = load_iamrole; load_iamrole = flag; return old; } bool S3fsCred::SetAccessKey(const char* AccessKeyId, const char* SecretAccessKey) { if((!is_ibm_iam_auth && (!AccessKeyId || '\0' == AccessKeyId[0])) || !SecretAccessKey || '\0' == SecretAccessKey[0]){ return false; } AWSAccessKeyId = AccessKeyId; AWSSecretAccessKey = SecretAccessKey; return true; } bool S3fsCred::SetAccessKeyWithSessionToken(const char* AccessKeyId, const char* SecretAccessKey, const char * SessionToken) { bool access_key_is_empty = AccessKeyId == nullptr || '\0' == AccessKeyId[0]; bool secret_access_key_is_empty = SecretAccessKey == nullptr || '\0' == SecretAccessKey[0]; bool session_token_is_empty = SessionToken == nullptr || '\0' == SessionToken[0]; if((!is_ibm_iam_auth && access_key_is_empty) || secret_access_key_is_empty || session_token_is_empty){ return false; } AWSAccessKeyId = AccessKeyId; AWSSecretAccessKey = SecretAccessKey; AWSAccessToken = SessionToken; is_use_session_token= true; return true; } bool S3fsCred::IsSetAccessKeys() const { return IsSetIAMRole() || ((!AWSAccessKeyId.empty() || is_ibm_iam_auth) && !AWSSecretAccessKey.empty()); } bool S3fsCred::SetIsECS(bool flag) { bool old = is_ecs; is_ecs = flag; return old; } bool S3fsCred::SetIsUseSessionToken(bool flag) { bool old = is_use_session_token; is_use_session_token = flag; return old; } bool S3fsCred::SetIsIBMIAMAuth(bool flag) { bool old = is_ibm_iam_auth; is_ibm_iam_auth = flag; return old; } bool S3fsCred::SetIAMRole(const char* role) { IAM_role = role ? role : ""; return true; } const std::string& S3fsCred::GetIAMRoleHasLock() const { return IAM_role; } bool S3fsCred::IsSetIAMRole() const { return !IAM_role.empty(); } size_t S3fsCred::SetIAMFieldCount(size_t field_count) { size_t old = IAM_field_count; IAM_field_count = field_count; return old; } std::string S3fsCred::SetIAMCredentialsURL(const char* url) { std::string old = IAM_cred_url; IAM_cred_url = url ? url : ""; return old; } std::string S3fsCred::SetIAMTokenField(const char* token_field) { std::string old = IAM_token_field; IAM_token_field = token_field ? token_field : ""; return old; } std::string S3fsCred::SetIAMExpiryField(const char* expiry_field) { std::string old = IAM_expiry_field; IAM_expiry_field = expiry_field ? expiry_field : ""; return old; } bool S3fsCred::GetIAMCredentialsURL(std::string& url, bool check_iam_role) { // check if(check_iam_role && !is_ecs && !IsIBMIAMAuth()){ if(!IsSetIAMRole()) { S3FS_PRN_ERR("IAM role name is empty."); return false; } S3FS_PRN_INFO3("[IAM role=%s]", GetIAMRoleHasLock().c_str()); } if(is_ecs){ const char *env = std::getenv(S3fsCred::ECS_IAM_ENV_VAR); if(env == nullptr){ S3FS_PRN_ERR("%s is not set.", S3fsCred::ECS_IAM_ENV_VAR); return false; } url = IAM_cred_url + env; }else if(IsIBMIAMAuth()){ url = IAM_cred_url; }else{ // [NOTE] // To avoid deadlocking, do not manipulate the S3fsCred object // in the S3fsCurl::GetIAMv2ApiToken method (when retrying). // if(GetIMDSVersion() > 1){ std::string token; int result = get_iamv2api_token_request(std::string(S3fsCred::IAMv2_token_url), S3fsCred::IAMv2_token_ttl, std::string(S3fsCred::IAMv2_token_ttl_hdr), token); if(-ENOENT == result){ // If we get a 404 back when requesting the token service, // then it's highly likely we're running in an environment // that doesn't support the AWS IMDSv2 API, so we'll skip // the token retrieval in the future. SetIMDSVersionHasLock(1); }else if(result != 0){ // If we get an unexpected error when retrieving the API // token, log it but continue. Requirement for including // an API token with the metadata request may or may not // be required, so we should not abort here. S3FS_PRN_ERR("AWS IMDSv2 token retrieval failed: %d", result); }else{ // Set token if(!SetIAMv2APITokenHasLock(token)){ S3FS_PRN_ERR("Error storing IMDSv2 API token(%s).", token.c_str()); } } } if(check_iam_role){ url = IAM_cred_url + GetIAMRoleHasLock(); }else{ url = IAM_cred_url; } } return true; } int S3fsCred::SetIMDSVersionHasLock(int version) { int old = IAM_api_version; IAM_api_version = version; return old; } int S3fsCred::GetIMDSVersion() const { return IAM_api_version; } bool S3fsCred::SetIAMv2APITokenHasLock(const std::string& token) { S3FS_PRN_INFO3("Setting AWS IMDSv2 API token to %s", token.c_str()); if(token.empty()){ return false; } IAMv2_api_token = token; return true; } const std::string& S3fsCred::GetIAMv2APIToken() const { return IAMv2_api_token; } // [NOTE] // Currently, token_lock is always locked before calling this method, // and this method calls the S3fsCurl::GetIAMCredentials method. // Currently, when the request fails and retries in the process of // S3fsCurl::GetIAMCredentials, does not use the S3fsCred object in // retry logic. // Be careful not to deadlock whenever you change this logic. // bool S3fsCred::LoadIAMCredentials() { std::string url; std::string striamtoken; std::string stribmsecret; std::string cred; // get parameters(check iam role) if(!GetIAMCredentialsURL(url, true)){ return false; } if(GetIMDSVersion() > 1){ striamtoken = GetIAMv2APIToken(); } if(IsIBMIAMAuth()){ stribmsecret = AWSSecretAccessKey; } // Get IAM Credentials if(0 == get_iamcred_request(url, striamtoken, stribmsecret, cred)){ S3FS_PRN_DBG("Succeed to set IAM credentials"); }else{ S3FS_PRN_ERR("Something error occurred, could not set IAM credentials."); return false; } return true; } // // load IAM role name from http://169.254.169.254/latest/meta-data/iam/security-credentials // bool S3fsCred::LoadIAMRoleFromMetaData() { if(!load_iamrole){ // nothing to do return true; } std::string url; std::string iamtoken; { const std::lock_guard<std::mutex> lock(token_lock); // url(not check iam role) if(!GetIAMCredentialsURL(url, false)){ return false; } if(GetIMDSVersion() > 1){ iamtoken = GetIAMv2APIToken(); } } // Get IAM Role token std::string token; if(0 != get_iamrole_request(url, iamtoken, token)){ S3FS_PRN_ERR("failed to get IAM Role token from meta data."); return false; } // Set if(!SetIAMRoleFromMetaData(token.c_str())){ S3FS_PRN_ERR("Something error occurred, could not set IAM role name."); return false; } return true; } bool S3fsCred::SetIAMCredentials(const char* response) { const std::lock_guard<std::mutex> lock(token_lock); S3FS_PRN_INFO3("IAM credential response = \"%s\"", response); iamcredmap_t keyval; if(!ParseIAMCredentialResponse(response, keyval)){ return false; } if(IAM_field_count != keyval.size()){ return false; } AWSAccessToken = keyval[IAM_token_field]; if(is_ibm_iam_auth){ off_t tmp_expire = 0; if(!s3fs_strtoofft(&tmp_expire, keyval[IAM_expiry_field].c_str(), /*base=*/ 10)){ return false; } AWSAccessTokenExpire = static_cast<time_t>(tmp_expire); }else{ AWSAccessKeyId = keyval[S3fsCred::IAMCRED_ACCESSKEYID]; AWSSecretAccessKey = keyval[S3fsCred::IAMCRED_SECRETACCESSKEY]; AWSAccessTokenExpire = cvtIAMExpireStringToTime(keyval[IAM_expiry_field].c_str()); } return true; } bool S3fsCred::SetIAMRoleFromMetaData(const char* response) { const std::lock_guard<std::mutex> lock(token_lock); S3FS_PRN_INFO3("IAM role name response = \"%s\"", response ? response : "(null)"); std::string rolename; if(!S3fsCred::ParseIAMRoleFromMetaDataResponse(response, rolename)){ return false; } SetIAMRole(rolename.c_str()); return true; } //------------------------------------------------------------------- // Methods : for Credentials //------------------------------------------------------------------- // // Check passwd file readable // bool S3fsCred::IsReadableS3fsPasswdFile() const { if(passwd_file.empty()){ return false; } std::ifstream PF(passwd_file.c_str()); if(!PF.good()){ return false; } PF.close(); return true; } // // S3fsCred::CheckS3fsPasswdFilePerms // // 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 // bool S3fsCred::CheckS3fsPasswdFilePerms() { 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): %s", passwd_file.c_str(), strerror(errno)); return false; } // Check readable if(!IsReadableS3fsPasswdFile()){ S3FS_PRN_EXIT("S3fs passwd file \"%s\" is not readable.", passwd_file.c_str()); return false; } // 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 false; } // 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 false; } }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 false; } } 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 false; } return true; } // // Read and Parse passwd file // // The line of the password file is one of the following formats: // (1) "accesskey:secretkey" : AWS format for default(all) access key/secret key // (2) "bucket:accesskey:secretkey" : AWS format for bucket's access key/secret key // (3) "key=value" : Content-dependent KeyValue contents // // This function sets result into bucketkvmap_t, it bucket name and key&value mapping. // If bucket name is empty(1 or 3 format), bucket name for mapping is set "\t" or "". // // Return: true - Succeed parsing // false - Should shutdown immediately // bool S3fsCred::ParseS3fsPasswdFile(bucketkvmap_t& resmap) { std::string line; size_t first_pos; readline_t linelist; // open passwd file std::ifstream PF(passwd_file.c_str()); if(!PF.good()){ S3FS_PRN_EXIT("could not open passwd file : %s", passwd_file.c_str()); return false; } // read each line while(getline(PF, line)){ line = trim(line); if(line.empty()){ continue; } if('#' == line[0]){ continue; } if(std::string::npos != line.find_first_of(" \t")){ S3FS_PRN_EXIT("invalid line in passwd file, found whitespace character."); return false; } if('[' == line[0]){ S3FS_PRN_EXIT("invalid line in passwd file, found a bracket \"[\" character."); return false; } linelist.push_back(line); } // read '=' type kvmap_t kv; for(auto iter = linelist.cbegin(); iter != linelist.cend(); ++iter){ first_pos = iter->find_first_of('='); if(first_pos == std::string::npos){ continue; } // formatted by "key=val" std::string key = trim(iter->substr(0, first_pos)); std::string val = trim(iter->substr(first_pos + 1, std::string::npos)); if(key.empty()){ continue; } if(kv.cend() != kv.find(key)){ S3FS_PRN_WARN("same key name(%s) found in passwd file, skip this.", key.c_str()); continue; } kv[key] = val; } // set special key name resmap[S3fsCred::KEYVAL_FIELDS_TYPE] = kv; // read ':' type for(auto iter = linelist.cbegin(); iter != linelist.cend(); ++iter){ first_pos = iter->find_first_of(':'); size_t last_pos = iter->find_last_of(':'); if(first_pos == std::string::npos){ continue; } std::string bucketname; std::string accesskey; std::string secret; if(first_pos != last_pos){ // formatted by "bucket:accesskey:secretkey" bucketname= trim(iter->substr(0, first_pos)); accesskey = trim(iter->substr(first_pos + 1, last_pos - first_pos - 1)); secret = trim(iter->substr(last_pos + 1, std::string::npos)); }else{ // formatted by "accesskey:secretkey" bucketname= S3fsCred::ALLBUCKET_FIELDS_TYPE; accesskey = trim(iter->substr(0, first_pos)); secret = trim(iter->substr(first_pos + 1, std::string::npos)); } if(resmap.cend() != resmap.find(bucketname)){ S3FS_PRN_EXIT("there are multiple entries for the same bucket(%s) in the passwd file.", (bucketname.empty() ? "default" : bucketname.c_str())); return false; } kv.clear(); kv[S3fsCred::AWS_ACCESSKEYID] = accesskey; kv[S3fsCred::AWS_SECRETKEY] = secret; resmap[bucketname] = kv; } return true; } // // ReadS3fsPasswdFile // // 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 // bool S3fsCred::ReadS3fsPasswdFile() { bucketkvmap_t bucketmap; kvmap_t keyval; // if you got here, the password file // exists and is readable by the // current user, check for permissions if(!CheckS3fsPasswdFilePerms()){ return false; } // // parse passwd file // if(!ParseS3fsPasswdFile(bucketmap)){ return false; } // // check key=value type format. // auto it = bucketmap.find(S3fsCred::KEYVAL_FIELDS_TYPE); if(bucketmap.cend() != it){ // aws format std::string access_key_id; std::string secret_access_key; int result = CheckS3fsCredentialAwsFormat(it->second, access_key_id, secret_access_key); if(-1 == result){ return false; }else if(1 == result){ // found ascess(secret) keys if(!SetAccessKey(access_key_id.c_str(), secret_access_key.c_str())){ S3FS_PRN_EXIT("failed to set access key/secret key."); return false; } return true; } } std::string bucket_key = S3fsCred::ALLBUCKET_FIELDS_TYPE; if(!S3fsCred::bucket_name.empty() && bucketmap.cend() != bucketmap.find(S3fsCred::bucket_name)){ bucket_key = S3fsCred::bucket_name; } it = bucketmap.find(bucket_key); if(bucketmap.cend() == it){ S3FS_PRN_EXIT("Not found access key/secret key in passwd file."); return false; } keyval = it->second; auto aws_accesskeyid_it = keyval.find(S3fsCred::AWS_ACCESSKEYID); auto aws_secretkey_it = keyval.find(S3fsCred::AWS_SECRETKEY); if(keyval.cend() == aws_accesskeyid_it || keyval.end() == aws_secretkey_it){ S3FS_PRN_EXIT("Not found access key/secret key in passwd file."); return false; } if(!SetAccessKey(aws_accesskeyid_it->second.c_str(), aws_secretkey_it->second.c_str())){ S3FS_PRN_EXIT("failed to set internal data for access key/secret key from passwd file."); return false; } return true; } // // Return: 1 - OK(could read and set accesskey etc.) // 0 - NG(could not read) // -1 - Should shutdown immediately // int S3fsCred::CheckS3fsCredentialAwsFormat(const kvmap_t& kvmap, std::string& access_key_id, std::string& secret_access_key) { std::string str1(S3fsCred::AWS_ACCESSKEYID); std::string str2(S3fsCred::AWS_SECRETKEY); if(kvmap.empty()){ return 0; } auto str1_it = kvmap.find(str1); auto str2_it = kvmap.find(str2); if(kvmap.cend() == str1_it && kvmap.end() == str2_it){ return 0; } if(kvmap.cend() == str1_it || kvmap.end() == str2_it){ S3FS_PRN_EXIT("AWSAccesskey or AWSSecretkey is not specified."); return -1; } access_key_id = str1_it->second; secret_access_key = str2_it->second; return 1; } // // Read Aws Credential File // bool S3fsCred::ReadAwsCredentialFile(const std::string &filename) { // open passwd file std::ifstream PF(filename.c_str()); if(!PF.good()){ return false; } std::string profile; std::string accesskey; std::string secret; std::string session_token; // read each line std::string line; while(getline(PF, line)){ line = trim(line); if(line.empty()){ continue; } if('#' == line[0]){ continue; } if(line.size() > 2 && line[0] == '[' && line[line.size() - 1] == ']') { if(profile == aws_profile){ break; } profile = line.substr(1, line.size() - 2); accesskey.clear(); secret.clear(); session_token.clear(); } size_t pos = line.find_first_of('='); if(pos == std::string::npos){ continue; } std::string key = trim(line.substr(0, pos)); std::string value = trim(line.substr(pos + 1, std::string::npos)); if(key == "aws_access_key_id"){ accesskey = value; }else if(key == "aws_secret_access_key"){ secret = value; }else if(key == "aws_session_token"){ session_token = value; } } if(profile != aws_profile){ return false; } if(session_token.empty()){ if(is_use_session_token){ S3FS_PRN_EXIT("AWS session token was expected but wasn't provided in aws/credentials file for profile: %s.", aws_profile.c_str()); return false; } if(!SetAccessKey(accesskey.c_str(), secret.c_str())){ S3FS_PRN_EXIT("failed to set internal data for access key/secret key from aws credential file."); return false; } }else{ if(!SetAccessKeyWithSessionToken(accesskey.c_str(), secret.c_str(), session_token.c_str())){ S3FS_PRN_EXIT("session token is invalid."); return false; } } return true; } // // InitialS3fsCredentials // // 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 // 3a - from the AWS_CREDENTIAL_FILE environment variable // 3b - from ${HOME}/.aws/credentials // 4 - from the users ~/.passwd-s3fs // 5 - from /etc/passwd-s3fs // bool S3fsCred::InitialS3fsCredentials() { // should be redundant if(S3fsCurl::IsPublicBucket()){ return true; } // access key loading is deferred if(load_iamrole || IsSetExtCredLib() || is_ecs){ return true; } // 1 - keys specified on the command line if(IsSetAccessKeys()){ return true; } // 2 - was specified on the command line if(IsSetPasswdFile()){ if(!ReadS3fsPasswdFile()){ return false; } return true; } // 3 - environment variables const char* AWSACCESSKEYID = getenv("AWS_ACCESS_KEY_ID") ? getenv("AWS_ACCESS_KEY_ID") : getenv("AWSACCESSKEYID"); const char* AWSSECRETACCESSKEY = getenv("AWS_SECRET_ACCESS_KEY") ? getenv("AWS_SECRET_ACCESS_KEY") : getenv("AWSSECRETACCESSKEY"); const char* AWSSESSIONTOKEN = getenv("AWS_SESSION_TOKEN") ? getenv("AWS_SESSION_TOKEN") : getenv("AWSSESSIONTOKEN"); if(AWSACCESSKEYID != nullptr || AWSSECRETACCESSKEY != nullptr){ if( (AWSACCESSKEYID == nullptr && AWSSECRETACCESSKEY != nullptr) || (AWSACCESSKEYID != nullptr && AWSSECRETACCESSKEY == nullptr) ){ S3FS_PRN_EXIT("both environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY must be set together."); return false; } S3FS_PRN_INFO2("access key from env variables"); if(AWSSESSIONTOKEN != nullptr){ S3FS_PRN_INFO2("session token is available"); if(!SetAccessKeyWithSessionToken(AWSACCESSKEYID, AWSSECRETACCESSKEY, AWSSESSIONTOKEN)){ S3FS_PRN_EXIT("session token is invalid."); return false; } }else{ S3FS_PRN_INFO2("session token is not available"); if(is_use_session_token){ S3FS_PRN_EXIT("environment variable AWS_SESSION_TOKEN is expected to be set."); return false; } } if(!SetAccessKey(AWSACCESSKEYID, AWSSECRETACCESSKEY)){ S3FS_PRN_EXIT("if one access key is specified, both keys need to be specified."); return false; } return true; } // 3a - from the AWS_CREDENTIAL_FILE environment variable char* AWS_CREDENTIAL_FILE = getenv("AWS_CREDENTIAL_FILE"); if(AWS_CREDENTIAL_FILE != nullptr){ passwd_file = AWS_CREDENTIAL_FILE; if(IsSetPasswdFile()){ if(!IsReadableS3fsPasswdFile()){ S3FS_PRN_EXIT("AWS_CREDENTIAL_FILE: \"%s\" is not readable.", passwd_file.c_str()); return false; } if(!ReadS3fsPasswdFile()){ return false; } return true; } } // 3b - check ${HOME}/.aws/credentials std::string aws_credentials = std::string(getpwuid(getuid())->pw_dir) + "/.aws/credentials"; if(ReadAwsCredentialFile(aws_credentials)){ return true; }else if(aws_profile != DEFAULT_AWS_PROFILE_NAME){ S3FS_PRN_EXIT("Could not find profile: %s in file: %s", aws_profile.c_str(), aws_credentials.c_str()); return false; } // 4 - from the default location in the users home directory char* HOME = getenv("HOME"); if(HOME != nullptr){ passwd_file = HOME; passwd_file += "/.passwd-s3fs"; if(IsReadableS3fsPasswdFile()){ if(!ReadS3fsPasswdFile()){ return false; } // 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(IsSetAccessKeys()){ return true; } } } // 5 - from the system default location passwd_file = "/etc/passwd-s3fs"; if(IsReadableS3fsPasswdFile()){ if(!ReadS3fsPasswdFile()){ return false; } return true; } S3FS_PRN_EXIT("could not determine how to establish security credentials."); return false; } //------------------------------------------------------------------- // Methods : for IAM //------------------------------------------------------------------- bool S3fsCred::ParseIAMCredentialResponse(const char* response, iamcredmap_t& keyval) { if(!response){ return false; } std::istringstream sscred(response); std::string oneline; keyval.clear(); while(getline(sscred, oneline, ',')){ std::string::size_type pos; std::string key; std::string val; if(std::string::npos != (pos = oneline.find(S3fsCred::IAMCRED_ACCESSKEYID))){ key = S3fsCred::IAMCRED_ACCESSKEYID; }else if(std::string::npos != (pos = oneline.find(S3fsCred::IAMCRED_SECRETACCESSKEY))){ key = S3fsCred::IAMCRED_SECRETACCESSKEY; }else if(std::string::npos != (pos = oneline.find(IAM_token_field))){ key = IAM_token_field; }else if(std::string::npos != (pos = oneline.find(IAM_expiry_field))){ key = IAM_expiry_field; }else if(std::string::npos != (pos = oneline.find(S3fsCred::IAMCRED_ROLEARN))){ key = S3fsCred::IAMCRED_ROLEARN; }else{ continue; } if(std::string::npos == (pos = oneline.find(':', pos + key.length()))){ continue; } if(is_ibm_iam_auth && key == IAM_expiry_field){ // parse integer value if(std::string::npos == (pos = oneline.find_first_of("0123456789", pos))){ continue; } oneline.erase(0, pos); if(std::string::npos == (pos = oneline.find_last_of("0123456789"))){ continue; } val = oneline.substr(0, pos+1); }else{ // parse std::string value (starts and ends with quotes) if(std::string::npos == (pos = oneline.find('\"', pos))){ continue; } oneline.erase(0, pos+1); if(std::string::npos == (pos = oneline.find('\"'))){ continue; } val = oneline.substr(0, pos); } keyval[key] = val; } return true; } bool S3fsCred::CheckIAMCredentialUpdate(std::string* access_key_id, std::string* secret_access_key, std::string* access_token) { const std::lock_guard<std::mutex> lock(token_lock); if(IsIBMIAMAuth() || IsSetExtCredLib() || is_ecs || IsSetIAMRole()){ if(AWSAccessTokenExpire < (time(nullptr) + S3fsCred::IAM_EXPIRE_MERGING)){ S3FS_PRN_INFO("IAM Access Token refreshing..."); // update if(!IsSetExtCredLib()){ if(!LoadIAMCredentials()){ S3FS_PRN_ERR("Access Token refresh by built-in failed"); return false; } }else{ if(!UpdateExtCredentials()){ S3FS_PRN_ERR("Access Token refresh by %s(external credential library) failed", credlib.c_str()); return false; } } S3FS_PRN_INFO("IAM Access Token refreshed"); } } // set if(access_key_id){ *access_key_id = AWSAccessKeyId; } if(secret_access_key){ *secret_access_key = AWSSecretAccessKey; } if(access_token){ if(IsIBMIAMAuth() || IsSetExtCredLib() || is_ecs || is_use_session_token || IsSetIAMRole()){ *access_token = AWSAccessToken; }else{ access_token->clear(); } } return true; } const char* S3fsCred::GetCredFuncVersion(bool detail) const { static constexpr char errVersion[] = "unknown"; if(!pFuncCredVersion){ return errVersion; } return (*pFuncCredVersion)(detail); } //------------------------------------------------------------------- // Methods : External Credential Library //------------------------------------------------------------------- bool S3fsCred::SetExtCredLib(const char* arg) { if(!arg || strlen(arg) == 0){ return false; } credlib = arg; return true; } bool S3fsCred::IsSetExtCredLib() const { return !credlib.empty(); } bool S3fsCred::SetExtCredLibOpts(const char* args) { if(!args || strlen(args) == 0){ return false; } credlib_opts = args; return true; } bool S3fsCred::IsSetExtCredLibOpts() const { return !credlib_opts.empty(); } bool S3fsCred::InitExtCredLib() { if(!LoadExtCredLib()){ return false; } // Initialize library if(!pFuncCredInit){ S3FS_PRN_CRIT("\"InitS3fsCredential\" function pointer is nullptr, why?"); UnloadExtCredLib(); return false; } const char* popts = credlib_opts.empty() ? nullptr : credlib_opts.c_str(); char* perrstr = nullptr; if(!(*pFuncCredInit)(popts, &perrstr)){ S3FS_PRN_ERR("Could not initialize %s(external credential library) by \"InitS3fsCredential\" function : %s", credlib.c_str(), perrstr ? perrstr : "unknown"); // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(perrstr){ free(perrstr); } UnloadExtCredLib(); return false; } // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(perrstr){ free(perrstr); } return true; } bool S3fsCred::LoadExtCredLib() { if(credlib.empty()){ return false; } UnloadExtCredLib(); S3FS_PRN_INFO("Load External Credential Library : %s", credlib.c_str()); // Open Library // // Search Library: (RPATH ->) LD_LIBRARY_PATH -> (RUNPATH ->) /etc/ld.so.cache -> /lib -> /usr/lib // if(nullptr == (hExtCredLib = dlopen(credlib.c_str(), RTLD_LAZY))){ const char* preason = dlerror(); S3FS_PRN_ERR("Could not load %s(external credential library) by error : %s", credlib.c_str(), preason ? preason : "unknown"); return false; } // Set function pointers if(nullptr == (pFuncCredVersion = reinterpret_cast<fp_VersionS3fsCredential>(dlsym(hExtCredLib, "VersionS3fsCredential")))){ S3FS_PRN_ERR("%s(external credential library) does not have \"VersionS3fsCredential\" function which is required.", credlib.c_str()); UnloadExtCredLib(); return false; } if(nullptr == (pFuncCredUpdate = reinterpret_cast<fp_UpdateS3fsCredential>(dlsym(hExtCredLib, "UpdateS3fsCredential")))){ S3FS_PRN_ERR("%s(external credential library) does not have \"UpdateS3fsCredential\" function which is required.", credlib.c_str()); UnloadExtCredLib(); return false; } if(nullptr == (pFuncCredInit = reinterpret_cast<fp_InitS3fsCredential>(dlsym(hExtCredLib, "InitS3fsCredential")))){ S3FS_PRN_INFO("%s(external credential library) does not have \"InitS3fsCredential\" function which is optional.", credlib.c_str()); pFuncCredInit = InitS3fsCredential; // set built-in function } if(nullptr == (pFuncCredFree = reinterpret_cast<fp_FreeS3fsCredential>(dlsym(hExtCredLib, "FreeS3fsCredential")))){ S3FS_PRN_INFO("%s(external credential library) does not have \"FreeS3fsCredential\" function which is optional.", credlib.c_str()); pFuncCredFree = FreeS3fsCredential; // set built-in function } S3FS_PRN_INFO("Succeed loading External Credential Library : %s", credlib.c_str()); return true; } bool S3fsCred::UnloadExtCredLib() { if(hExtCredLib){ S3FS_PRN_INFO("Unload External Credential Library : %s", credlib.c_str()); // Uninitialize library if(!pFuncCredFree){ S3FS_PRN_CRIT("\"FreeS3fsCredential\" function pointer is nullptr, why?"); }else{ char* perrstr = nullptr; if(!(*pFuncCredFree)(&perrstr)){ S3FS_PRN_ERR("Could not uninitialize by \"FreeS3fsCredential\" function : %s", perrstr ? perrstr : "unknown"); } // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(perrstr){ free(perrstr); } } // reset pFuncCredVersion = VersionS3fsCredential; pFuncCredInit = InitS3fsCredential; pFuncCredFree = FreeS3fsCredential; pFuncCredUpdate = UpdateS3fsCredential; // close dlclose(hExtCredLib); hExtCredLib = nullptr; } return true; } bool S3fsCred::UpdateExtCredentials() { if(!hExtCredLib){ S3FS_PRN_CRIT("External Credential Library is not loaded, why?"); return false; } char* paccess_key_id = nullptr; char* pserect_access_key = nullptr; char* paccess_token = nullptr; char* perrstr = nullptr; long long token_expire = 0; bool result = (*pFuncCredUpdate)(&paccess_key_id, &pserect_access_key, &paccess_token, &token_expire, &perrstr); if(!result){ // error occurred S3FS_PRN_ERR("Could not update credential by \"UpdateS3fsCredential\" function : %s", perrstr ? perrstr : "unknown"); // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse }else if(!paccess_key_id || !pserect_access_key || !paccess_token || token_expire <= 0){ // some variables are wrong S3FS_PRN_ERR("After updating credential by \"UpdateS3fsCredential\" function, but some variables are wrong : paccess_key_id=%p, pserect_access_key=%p, paccess_token=%p, token_expire=%lld", paccess_key_id, pserect_access_key, paccess_token, token_expire); result = false; }else{ // succeed updating AWSAccessKeyId = paccess_key_id; AWSSecretAccessKey = pserect_access_key; AWSAccessToken = paccess_token; AWSAccessTokenExpire = token_expire; } // clean // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(paccess_key_id){ free(paccess_key_id); } // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(pserect_access_key){ free(pserect_access_key); } // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(paccess_token){ free(paccess_token); } // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(perrstr){ free(perrstr); } return result; } //------------------------------------------------------------------- // Methods: Option detection //------------------------------------------------------------------- // return value: 1 = Not processed as it is not a option for this class // 0 = The option was detected and processed appropriately // -1 = Processing cannot be continued because a fatal error was detected // int S3fsCred::DetectParam(const char* arg) { const std::lock_guard<std::mutex> lock(token_lock); if(!arg){ S3FS_PRN_EXIT("parameter arg is empty(null)"); return -1; } if(is_prefix(arg, "passwd_file=")){ SetS3fsPasswdFile(strchr(arg, '=') + sizeof(char)); set_builtin_cred_opts = true; return 0; } if(0 == strcmp(arg, "ibm_iam_auth")){ SetIsIBMIAMAuth(true); SetIAMCredentialsURL("https://iam.cloud.ibm.com/identity/token"); SetIAMTokenField("\"access_token\""); SetIAMExpiryField("\"expiration\""); SetIAMFieldCount(2); SetIMDSVersionHasLock(1); set_builtin_cred_opts = true; return 0; } if(0 == strcmp(arg, "use_session_token")){ SetIsUseSessionToken(true); set_builtin_cred_opts = true; return 0; } if(is_prefix(arg, "ibm_iam_endpoint=")){ std::string endpoint_url; const char* iam_endpoint = strchr(arg, '=') + sizeof(char); // Check url for http / https protocol std::string if(!is_prefix(iam_endpoint, "https://") && !is_prefix(iam_endpoint, "http://")){ S3FS_PRN_EXIT("option ibm_iam_endpoint has invalid format, missing http / https protocol"); return -1; } endpoint_url = std::string(iam_endpoint) + "/identity/token"; SetIAMCredentialsURL(endpoint_url.c_str()); set_builtin_cred_opts = true; return 0; } if(0 == strcmp(arg, "imdsv1only")){ SetIMDSVersionHasLock(1); set_builtin_cred_opts = true; return 0; } if(0 == strcmp(arg, "ecs")){ if(IsIBMIAMAuth()){ S3FS_PRN_EXIT("option ecs cannot be used in conjunction with ibm"); return -1; } SetIsECS(true); SetIMDSVersionHasLock(1); SetIAMCredentialsURL("http://169.254.170.2"); SetIAMFieldCount(5); set_builtin_cred_opts = true; return 0; } if(is_prefix(arg, "iam_role")){ if(is_ecs || IsIBMIAMAuth()){ S3FS_PRN_EXIT("option iam_role cannot be used in conjunction with ecs or ibm"); return -1; } if(0 == strcmp(arg, "iam_role") || 0 == strcmp(arg, "iam_role=auto")){ // loading IAM role name in s3fs_init(), because we need to wait initializing curl. // SetIAMRoleMetadataType(true); set_builtin_cred_opts = true; return 0; }else if(is_prefix(arg, "iam_role=")){ const char* role = strchr(arg, '=') + sizeof(char); SetIAMRole(role); SetIAMRoleMetadataType(false); set_builtin_cred_opts = true; return 0; } } if(is_prefix(arg, "profile=")){ SetAwsProfileName(strchr(arg, '=') + sizeof(char)); set_builtin_cred_opts = true; return 0; } if(is_prefix(arg, "credlib=")){ if(!SetExtCredLib(strchr(arg, '=') + sizeof(char))){ S3FS_PRN_EXIT("failed to set credlib option : %s", (strchr(arg, '=') + sizeof(char))); return -1; } return 0; } if(is_prefix(arg, "credlib_opts=")){ if(!SetExtCredLibOpts(strchr(arg, '=') + sizeof(char))){ S3FS_PRN_EXIT("failed to set credlib_opts option : %s", (strchr(arg, '=') + sizeof(char))); return -1; } return 0; } return 1; } //------------------------------------------------------------------- // Methods : check parameters //------------------------------------------------------------------- // // Checking forbidden parameters for bucket // bool S3fsCred::CheckForbiddenBucketParams() { // The first plain argument is the bucket if(bucket_name.empty()){ S3FS_PRN_EXIT("missing BUCKET argument."); show_usage(); return false; } // bucket names cannot contain upper case characters in virtual-hosted style if(!pathrequeststyle && (lower(bucket_name) != bucket_name)){ S3FS_PRN_EXIT("BUCKET %s, name not compatible with virtual-hosted style.", bucket_name.c_str()); return false; } // check bucket name for illegal characters size_t found = bucket_name.find_first_of("/:\\;!@#$%^&*?|+="); if(found != std::string::npos){ S3FS_PRN_EXIT("BUCKET %s -- bucket name contains an illegal character: '%c' at position %zu", bucket_name.c_str(), bucket_name[found], found); return false; } if(!pathrequeststyle && is_prefix(s3host.c_str(), "https://") && bucket_name.find_first_of('.') != std::string::npos) { S3FS_PRN_EXIT("BUCKET %s -- cannot mount bucket with . while using HTTPS without use_path_request_style", bucket_name.c_str()); return false; } return true; } // // Check the combination of parameters // bool S3fsCred::CheckAllParams() { const std::lock_guard<std::mutex> lock(token_lock); // // Checking forbidden parameters for bucket // if(!CheckForbiddenBucketParams()){ return false; } // error checking of command line arguments for compatibility if(S3fsCurl::IsPublicBucket() && IsSetAccessKeys()){ S3FS_PRN_EXIT("specifying both public_bucket and the access keys options is invalid."); return false; } if(IsSetPasswdFile() && IsSetAccessKeys()){ S3FS_PRN_EXIT("specifying both passwd_file and the access keys options is invalid."); return false; } if(!S3fsCurl::IsPublicBucket() && !load_iamrole && !is_ecs && !IsSetExtCredLib()){ if(!InitialS3fsCredentials()){ return false; } if(!IsSetAccessKeys()){ S3FS_PRN_EXIT("could not establish security credentials, check documentation."); return false; } // More error checking on the access key pair can be done // like checking for appropriate lengths and characters } // check IBM IAM requirements if(IsIBMIAMAuth()){ // check that default ACL is either public-read or private acl_t defaultACL = S3fsCurl::GetDefaultAcl(); if(defaultACL != acl_t::PRIVATE && defaultACL != acl_t::PUBLIC_READ){ S3FS_PRN_EXIT("can only use 'public-read' or 'private' ACL while using ibm_iam_auth"); return false; } } // check External Credential Library // // [NOTE] // If credlib(_opts) option (for External Credential Library) is specified, // no other Credential related options can be specified. It is exclusive. // if(set_builtin_cred_opts && (IsSetExtCredLib() || IsSetExtCredLibOpts())){ S3FS_PRN_EXIT("The \"credlib\" or \"credlib_opts\" option and other credential-related options(passwd_file, iam_role, profile, use_session_token, ecs, imdsv1only, ibm_iam_auth, ibm_iam_endpoint, etc) cannot be specified together."); return false; } // Load and Initialize external credential library if(IsSetExtCredLib() || IsSetExtCredLibOpts()){ if(!IsSetExtCredLib()){ S3FS_PRN_EXIT("The \"credlib_opts\"(%s) is specified but \"credlib\" option is not specified.", credlib_opts.c_str()); return false; } if(!InitExtCredLib()){ S3FS_PRN_EXIT("failed to load the library specified by the option credlib(%s, %s).", credlib.c_str(), credlib_opts.c_str()); return false; } S3FS_PRN_INFO("Loaded External Credential Library:\n%s", GetCredFuncVersion(true)); } return true; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
50,366
C++
.cpp
1,407
29.404407
262
0.606092
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,453
fdcache_stat.cpp
s3fs-fuse_s3fs-fuse/src/fdcache_stat.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <cerrno> #include <unistd.h> #include <string> #include <sys/file.h> #include <sys/stat.h> #include "s3fs_logger.h" #include "fdcache_stat.h" #include "fdcache.h" #include "s3fs_util.h" #include "s3fs_cred.h" #include "string_util.h" //------------------------------------------------ // CacheFileStat class methods //------------------------------------------------ std::string CacheFileStat::GetCacheFileStatTopDir() { std::string top_path; if(!FdManager::IsCacheDir() || S3fsCred::GetBucket().empty()){ return top_path; } // stat top dir( "/<cache_dir>/.<bucket_name>.stat" ) top_path += FdManager::GetCacheDir(); top_path += "/."; top_path += S3fsCred::GetBucket(); top_path += ".stat"; return top_path; } int CacheFileStat::MakeCacheFileStatPath(const char* path, std::string& sfile_path, bool is_create_dir) { std::string top_path = CacheFileStat::GetCacheFileStatTopDir(); if(top_path.empty()){ S3FS_PRN_ERR("The path to cache top dir is empty."); return -EIO; } 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 result; } } if(!path || '\0' == path[0]){ sfile_path = top_path; }else{ sfile_path = top_path + SAFESTRPTR(path); } return 0; } bool CacheFileStat::CheckCacheFileStatTopDir() { std::string top_path = CacheFileStat::GetCacheFileStatTopDir(); if(top_path.empty()){ S3FS_PRN_INFO("The path to cache top dir is empty, thus not need to check permission."); return true; } return check_exist_dir_permission(top_path.c_str()); } int CacheFileStat::DeleteCacheFileStat(const char* path) { if(!path || '\0' == path[0]){ return -EINVAL; } // stat path std::string sfile_path; int result; if(0 != (result = CacheFileStat::MakeCacheFileStatPath(path, sfile_path, false))){ S3FS_PRN_ERR("failed to create cache stat file path(%s)", path); return result; } if(0 != unlink(sfile_path.c_str())){ result = -errno; if(-ENOENT == result){ S3FS_PRN_DBG("failed to delete file(%s): errno=%d", path, result); }else{ S3FS_PRN_ERR("failed to delete file(%s): errno=%d", path, result); } return result; } return 0; } // [NOTE] // If remove stat file directory, it should do before removing // file cache directory. // bool CacheFileStat::DeleteCacheFileStatDirectory() { std::string top_path = CacheFileStat::GetCacheFileStatTopDir(); if(top_path.empty()){ S3FS_PRN_INFO("The path to cache top dir is empty, thus not need to remove it."); return true; } return delete_files_in_dir(top_path.c_str(), true); } bool CacheFileStat::RenameCacheFileStat(const char* oldpath, const char* newpath) { if(!oldpath || '\0' == oldpath[0] || !newpath || '\0' == newpath[0]){ return false; } // stat path std::string old_filestat; std::string new_filestat; if(0 != CacheFileStat::MakeCacheFileStatPath(oldpath, old_filestat, false) || 0 != CacheFileStat::MakeCacheFileStatPath(newpath, new_filestat, false)){ return false; } // check new stat path struct stat st; if(0 == stat(new_filestat.c_str(), &st)){ // new stat path is existed, then unlink it. if(-1 == unlink(new_filestat.c_str())){ S3FS_PRN_ERR("failed to unlink new cache file stat path(%s) by errno(%d).", new_filestat.c_str(), errno); return false; } } // check old stat path if(0 != stat(old_filestat.c_str(), &st)){ // old stat path is not existed, then nothing to do any more. return true; } // link and unlink if(-1 == link(old_filestat.c_str(), new_filestat.c_str())){ S3FS_PRN_ERR("failed to link old cache file stat path(%s) to new cache file stat path(%s) by errno(%d).", old_filestat.c_str(), new_filestat.c_str(), errno); return false; } if(-1 == unlink(old_filestat.c_str())){ S3FS_PRN_ERR("failed to unlink old cache file stat path(%s) by errno(%d).", old_filestat.c_str(), errno); return false; } return true; } //------------------------------------------------ // CacheFileStat methods //------------------------------------------------ CacheFileStat::CacheFileStat(const char* tpath) : 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; } path = tpath; if(!is_open){ return true; } return Open(); } bool CacheFileStat::RawOpen(bool readonly) { if(path.empty()){ return false; } if(-1 != fd){ // already opened return true; } // stat path std::string sfile_path; if(0 != 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 int tmpfd; if(readonly){ if(-1 == (tmpfd = open(sfile_path.c_str(), O_RDONLY))){ S3FS_PRN_ERR("failed to read only open cache stat file path(%s) - errno(%d)", path.c_str(), errno); return false; } }else{ if(-1 == (tmpfd = 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; } } scope_guard guard([&]() { close(tmpfd); }); // lock if(-1 == flock(tmpfd, LOCK_EX)){ S3FS_PRN_ERR("failed to lock cache stat file(%s) - errno(%d)", path.c_str(), errno); return false; } // seek top if(0 != lseek(tmpfd, 0, SEEK_SET)){ S3FS_PRN_ERR("failed to lseek cache stat file(%s) - errno(%d)", path.c_str(), errno); flock(tmpfd, LOCK_UN); return false; } S3FS_PRN_DBG("file locked(%s - %s)", path.c_str(), sfile_path.c_str()); guard.dismiss(); fd = tmpfd; return true; } bool CacheFileStat::Open() { return RawOpen(false); } bool CacheFileStat::ReadOnlyOpen() { return RawOpen(true); } bool CacheFileStat::Release() { 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; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
8,024
C++
.cpp
256
26.382813
165
0.604961
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
18,454
curl_multi.cpp
s3fs-fuse_s3fs-fuse/src/curl_multi.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <cstdio> #include <cstdlib> #include <cerrno> #include <future> #include <mutex> #include <thread> #include <utility> #include <vector> #include "s3fs.h" #include "s3fs_logger.h" #include "curl_multi.h" #include "curl.h" #include "psemaphore.h" //------------------------------------------------------------------- // Class S3fsMultiCurl //------------------------------------------------------------------- S3fsMultiCurl::S3fsMultiCurl(int maxParallelism, bool not_abort) : maxParallelism(maxParallelism), not_abort(not_abort), SuccessCallback(nullptr), NotFoundCallback(nullptr), RetryCallback(nullptr), pSuccessCallbackParam(nullptr), pNotFoundCallbackParam(nullptr) { } S3fsMultiCurl::~S3fsMultiCurl() { Clear(); } bool S3fsMultiCurl::ClearEx(bool is_all) { s3fscurllist_t::const_iterator iter; for(iter = clist_req.cbegin(); iter != clist_req.cend(); ++iter){ S3fsCurl* s3fscurl = iter->get(); if(s3fscurl){ s3fscurl->DestroyCurlHandle(); } } clist_req.clear(); if(is_all){ for(iter = clist_all.cbegin(); iter != clist_all.cend(); ++iter){ S3fsCurl* s3fscurl = iter->get(); s3fscurl->DestroyCurlHandle(); } clist_all.clear(); } S3FS_MALLOCTRIM(0); return true; } S3fsMultiSuccessCallback S3fsMultiCurl::SetSuccessCallback(S3fsMultiSuccessCallback function) { S3fsMultiSuccessCallback old = SuccessCallback; SuccessCallback = function; return old; } S3fsMultiNotFoundCallback S3fsMultiCurl::SetNotFoundCallback(S3fsMultiNotFoundCallback function) { S3fsMultiNotFoundCallback old = NotFoundCallback; NotFoundCallback = function; return old; } S3fsMultiRetryCallback S3fsMultiCurl::SetRetryCallback(S3fsMultiRetryCallback function) { S3fsMultiRetryCallback old = RetryCallback; RetryCallback = function; return old; } void* S3fsMultiCurl::SetSuccessCallbackParam(void* param) { void* old = pSuccessCallbackParam; pSuccessCallbackParam = param; return old; } void* S3fsMultiCurl::SetNotFoundCallbackParam(void* param) { void* old = pNotFoundCallbackParam; pNotFoundCallbackParam = param; return old; } bool S3fsMultiCurl::SetS3fsCurlObject(std::unique_ptr<S3fsCurl> s3fscurl) { if(!s3fscurl){ return false; } clist_all.push_back(std::move(s3fscurl)); return true; } int S3fsMultiCurl::MultiPerform() { std::map<std::thread::id, std::pair<std::thread, std::future<int>>> threads; int result = 0; bool isMultiHead = false; int semCount = GetMaxParallelism(); Semaphore sem(semCount); for(auto iter = clist_req.cbegin(); iter != clist_req.cend(); ++iter) { S3fsCurl* s3fscurl = iter->get(); if(!s3fscurl){ continue; } sem.acquire(); { const std::lock_guard<std::mutex> lock(completed_tids_lock); for(const auto &thread_id : completed_tids){ auto it = threads.find(thread_id); it->second.first.join(); long int int_retval = it->second.second.get(); if (int_retval && !(int_retval == -ENOENT && isMultiHead)) { S3FS_PRN_WARN("thread terminated with non-zero return code: %ld", int_retval); } threads.erase(it); } completed_tids.clear(); } s3fscurl->sem = &sem; s3fscurl->completed_tids_lock = &completed_tids_lock; s3fscurl->completed_tids = &completed_tids; isMultiHead |= s3fscurl->GetOp() == "HEAD"; std::promise<int> promise; std::future<int> future = promise.get_future(); std::thread thread(S3fsMultiCurl::RequestPerformWrapper, s3fscurl, std::move(promise)); auto thread_id = thread.get_id(); threads.emplace(std::piecewise_construct, std::forward_as_tuple(thread_id), std::forward_as_tuple(std::move(thread), std::move(future))); } for(int i = 0; i < semCount; ++i){ sem.acquire(); } const std::lock_guard<std::mutex> lock(completed_tids_lock); for(const auto &thread_id : completed_tids){ auto it = threads.find(thread_id); it->second.first.join(); auto int_retval = it->second.second.get(); // [NOTE] // For multipart HEAD requests(ex. readdir), we need to consider the // cases where you may get ENOENT and EPERM. // For example, we will get ENOENT when sending a HEAD request to a // directory of an object whose path contains a directory uploaded // from a client other than s3fs. // We will also get EPERM if you try to read an encrypted object // (such as KMS) without specifying SSE or with a different KMS key. // In these cases, if we end this method with that error result, // the caller will not be able to continue processing.(readdir will // fail.) // Therefore, if those conditions are met here, avoid setting it to // result. // if(!isMultiHead || (-ENOENT != int_retval && -EPERM != int_retval)){ S3FS_PRN_WARN("thread terminated with non-zero return code: %d", int_retval); result = int_retval; } threads.erase(it); } completed_tids.clear(); return result; } int S3fsMultiCurl::MultiRead() { int result = 0; for(auto iter = clist_req.begin(); iter != clist_req.end(); ){ std::unique_ptr<S3fsCurl> s3fscurl(std::move(*iter)); bool isRetry = false; bool isPostpone = false; bool isNeedResetOffset = true; long responseCode = S3fsCurl::S3FSCURL_RESPONSECODE_NOTSET; CURLcode curlCode = s3fscurl->GetCurlCode(); if(s3fscurl->GetResponseCode(responseCode, false) && curlCode == CURLE_OK){ if(S3fsCurl::S3FSCURL_RESPONSECODE_NOTSET == responseCode){ // This is a case where the processing result has not yet been updated (should be very rare). isPostpone = true; }else if(400 > responseCode){ // add into stat cache // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownPointerToBool if(SuccessCallback && !SuccessCallback(s3fscurl.get(), pSuccessCallbackParam)){ S3FS_PRN_WARN("error from success 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 // HEAD requests on readdir_multi_head can return 404 if(s3fscurl->GetOp() != "HEAD"){ S3FS_PRN_WARN("failed a request(%ld: %s)", responseCode, s3fscurl->url.c_str()); } // Call callback function // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownPointerToBool if(NotFoundCallback && !NotFoundCallback(s3fscurl.get(), pNotFoundCallbackParam)){ S3FS_PRN_WARN("error from not found callback function(%s).", 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 response code: %s)", s3fscurl->url.c_str()); // Reuse particular file switch(curlCode){ case CURLE_OPERATION_TIMEDOUT: isRetry = true; isNeedResetOffset = false; break; case CURLE_PARTIAL_FILE: isRetry = true; isNeedResetOffset = false; break; default: S3FS_PRN_ERR("###curlCode: %d msg: %s", curlCode, curl_easy_strerror(curlCode)); isRetry = true; break; } } if(isPostpone){ clist_req.erase(iter); clist_req.push_back(std::move(s3fscurl)); // Re-evaluate at the end iter = clist_req.begin(); }else{ if(!isRetry || (!not_abort && 0 != result)){ // If an EIO error has already occurred, it will be terminated // immediately even if retry processing is required. s3fscurl->DestroyCurlHandle(); }else{ // Reset offset if(isNeedResetOffset){ S3fsCurl::ResetOffset(s3fscurl.get()); } // For retry std::unique_ptr<S3fsCurl> retrycurl; const S3fsCurl* retrycurl_ptr = retrycurl.get(); // save this due to std::move below if(RetryCallback){ retrycurl = RetryCallback(s3fscurl.get()); if(nullptr != retrycurl){ clist_all.push_back(std::move(retrycurl)); }else{ // set EIO and wait for other parts. result = -EIO; } } // cppcheck-suppress mismatchingContainers if(s3fscurl.get() != retrycurl_ptr){ s3fscurl->DestroyCurlHandle(); } } iter = clist_req.erase(iter); } } clist_req.clear(); if(!not_abort && 0 != result){ // If an EIO error has already occurred, clear all retry objects. for(auto iter = clist_all.cbegin(); iter != clist_all.cend(); ++iter){ S3fsCurl* s3fscurl = iter->get(); s3fscurl->DestroyCurlHandle(); } clist_all.clear(); } return result; } int S3fsMultiCurl::Request() { S3FS_PRN_INFO3("[count=%zu]", clist_all.size()); // Make request list. // // Send multi request loop( with retry ) // (When many request is sends, sometimes gets "Couldn't connect to server") // while(!clist_all.empty()){ // set curl handle to multi handle int result; for(auto iter = clist_all.begin(); iter != clist_all.end(); ++iter){ clist_req.push_back(std::move(*iter)); } clist_all.clear(); // 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; } // // thread function for performing an S3fsCurl request // void S3fsMultiCurl::RequestPerformWrapper(S3fsCurl* s3fscurl, std::promise<int> promise) { int result = 0; if(!s3fscurl){ // this doesn't signal completion but also never happens promise.set_value(-EIO); return; } if(s3fscurl->fpLazySetup){ if(!s3fscurl->fpLazySetup(s3fscurl)){ S3FS_PRN_ERR("Failed to lazy setup, then respond EIO."); result = -EIO; } } if(!result){ result = s3fscurl->RequestPerform(); s3fscurl->DestroyCurlHandle(false); } const std::lock_guard<std::mutex> lock(*s3fscurl->completed_tids_lock); s3fscurl->completed_tids->push_back(std::this_thread::get_id()); s3fscurl->sem->release(); promise.set_value(result); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
13,209
C++
.cpp
342
29.850877
261
0.588006
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,455
fdcache_fdinfo.cpp
s3fs-fuse_s3fs-fuse/src/fdcache_fdinfo.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <algorithm> #include <cerrno> #include <cstdio> #include <cstdlib> #include <memory> #include <mutex> #include <string> #include <sys/stat.h> #include <unistd.h> #include "common.h" #include "s3fs.h" #include "s3fs_logger.h" #include "s3fs_util.h" #include "fdcache_fdinfo.h" #include "fdcache_pseudofd.h" #include "fdcache_entity.h" #include "curl.h" #include "string_util.h" #include "threadpoolman.h" #include "s3fs_threadreqs.h" //------------------------------------------------ // Structure of parameters to pass to thread //------------------------------------------------ // [NOTE] // The processing related to this is currently temporarily implemented // in this file, but will be moved to a separate file at a later. // struct pseudofdinfo_mpupload_thparam { PseudoFdInfo* ppseudofdinfo = nullptr; std::string path; std::string upload_id; int upload_fd = -1; off_t start = 0; off_t size = 0; bool is_copy = false; int part_num = -1; etagpair* petag = nullptr; }; //------------------------------------------------ // PseudoFdInfo class methods //------------------------------------------------ // // Thread Worker function for uploading // void* PseudoFdInfo::MultipartUploadThreadWorker(void* arg) { std::unique_ptr<pseudofdinfo_mpupload_thparam> pthparam(static_cast<pseudofdinfo_mpupload_thparam*>(arg)); if(!pthparam || !(pthparam->ppseudofdinfo)){ return reinterpret_cast<void*>(-EIO); } S3FS_PRN_INFO3("Upload Part Thread [tpath=%s][start=%lld][size=%lld][part=%d]", pthparam->path.c_str(), static_cast<long long>(pthparam->start), static_cast<long long>(pthparam->size), pthparam->part_num); int result; { const std::lock_guard<std::mutex> lock(pthparam->ppseudofdinfo->upload_list_lock); if(0 != (result = pthparam->ppseudofdinfo->last_result)){ S3FS_PRN_DBG("Already occurred error, thus this thread worker is exiting."); if(!pthparam->ppseudofdinfo->CompleteInstruction(result)){ // result will be overwritten with the same value. result = -EIO; } return reinterpret_cast<void*>(result); } } // setup and make curl object std::unique_ptr<S3fsCurl> s3fscurl(S3fsCurl::CreateParallelS3fsCurl(pthparam->path.c_str(), pthparam->upload_fd, pthparam->start, pthparam->size, pthparam->part_num, pthparam->is_copy, pthparam->petag, pthparam->upload_id, result)); if(nullptr == s3fscurl){ S3FS_PRN_ERR("failed creating s3fs curl object for uploading [path=%s][start=%lld][size=%lld][part=%d]", pthparam->path.c_str(), static_cast<long long>(pthparam->start), static_cast<long long>(pthparam->size), pthparam->part_num); // set result for exiting const std::lock_guard<std::mutex> lock(pthparam->ppseudofdinfo->upload_list_lock); if(!pthparam->ppseudofdinfo->CompleteInstruction(result)){ result = -EIO; } return reinterpret_cast<void*>(result); } // Send request and get result if(0 == (result = s3fscurl->RequestPerform())){ S3FS_PRN_DBG("succeed uploading [path=%s][start=%lld][size=%lld][part=%d]", pthparam->path.c_str(), static_cast<long long>(pthparam->start), static_cast<long long>(pthparam->size), pthparam->part_num); if(!s3fscurl->MixMultipartUploadComplete()){ S3FS_PRN_ERR("failed completion uploading [path=%s][start=%lld][size=%lld][part=%d]", pthparam->path.c_str(), static_cast<long long>(pthparam->start), static_cast<long long>(pthparam->size), pthparam->part_num); result = -EIO; } }else{ S3FS_PRN_ERR("failed uploading with error(%d) [path=%s][start=%lld][size=%lld][part=%d]", result, pthparam->path.c_str(), static_cast<long long>(pthparam->start), static_cast<long long>(pthparam->size), pthparam->part_num); } s3fscurl->DestroyCurlHandle(false); // set result const std::lock_guard<std::mutex> lock(pthparam->ppseudofdinfo->upload_list_lock); if(!pthparam->ppseudofdinfo->CompleteInstruction(result)){ S3FS_PRN_WARN("This thread worker is about to end, so it doesn't return an EIO here and runs to the end."); } return reinterpret_cast<void*>(result); } //------------------------------------------------ // PseudoFdInfo methods //------------------------------------------------ PseudoFdInfo::PseudoFdInfo(int fd, int open_flags) : pseudo_fd(-1), physical_fd(fd), flags(0), upload_fd(-1), instruct_count(0), completed_count(0), last_result(0), uploaded_sem(0) { if(-1 != physical_fd){ pseudo_fd = PseudoFdManager::Get(); flags = open_flags; } } PseudoFdInfo::~PseudoFdInfo() { Clear(); // call before destroying the mutex } bool PseudoFdInfo::Clear() { // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(!CancelAllThreads()){ return false; } { const std::lock_guard<std::mutex> lock(upload_list_lock); // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(!ResetUploadInfo()){ return false; } } CloseUploadFd(); if(-1 != pseudo_fd){ PseudoFdManager::Release(pseudo_fd); } pseudo_fd = -1; physical_fd = -1; return true; } bool PseudoFdInfo::IsUploadingHasLock() const { return !upload_id.empty(); } bool PseudoFdInfo::IsUploading() const { const std::lock_guard<std::mutex> lock(upload_list_lock); return IsUploadingHasLock(); } void PseudoFdInfo::CloseUploadFd() { const std::lock_guard<std::mutex> lock(upload_list_lock); if(-1 != upload_fd){ close(upload_fd); } } bool PseudoFdInfo::OpenUploadFd() { const std::lock_guard<std::mutex> lock(upload_list_lock); if(-1 != upload_fd){ // already initialized return true; } if(-1 == physical_fd){ S3FS_PRN_ERR("physical_fd is not initialized yet."); return false; } // duplicate fd int fd; if(-1 == (fd = dup(physical_fd))){ S3FS_PRN_ERR("Could not duplicate physical file descriptor(errno=%d)", errno); return false; } scope_guard guard([&]() { close(fd); }); if(0 != lseek(fd, 0, SEEK_SET)){ S3FS_PRN_ERR("Could not seek physical file descriptor(errno=%d)", errno); return false; } struct stat st; if(-1 == fstat(fd, &st)){ S3FS_PRN_ERR("Invalid file descriptor for uploading(errno=%d)", errno); return false; } guard.dismiss(); upload_fd = fd; return true; } bool PseudoFdInfo::Set(int fd, int open_flags) { if(-1 == fd){ return false; } Clear(); physical_fd = fd; pseudo_fd = PseudoFdManager::Get(); flags = open_flags; return true; } bool PseudoFdInfo::Writable() const { if(-1 == pseudo_fd){ return false; } if(0 == (flags & (O_WRONLY | O_RDWR))){ return false; } return true; } bool PseudoFdInfo::Readable() const { if(-1 == pseudo_fd){ return false; } // O_RDONLY is 0x00, it means any pattern is readable. return true; } bool PseudoFdInfo::ClearUploadInfo(bool is_cancel_mp) { if(is_cancel_mp){ // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(!CancelAllThreads()){ return false; } } const std::lock_guard<std::mutex> lock(upload_list_lock); return ResetUploadInfo(); } bool PseudoFdInfo::ResetUploadInfo() { upload_id.clear(); upload_list.clear(); instruct_count = 0; completed_count = 0; last_result = 0; return true; } bool PseudoFdInfo::RowInitialUploadInfo(const std::string& id, bool is_cancel_mp) { if(is_cancel_mp){ // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(!ClearUploadInfo(is_cancel_mp)){ return false; } }else{ const std::lock_guard<std::mutex> lock(upload_list_lock); // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(!ResetUploadInfo()){ return false; } } const std::lock_guard<std::mutex> lock(upload_list_lock); upload_id = id; return true; } void PseudoFdInfo::IncreaseInstructionCount() { const std::lock_guard<std::mutex> lock(upload_list_lock); ++instruct_count; } bool PseudoFdInfo::CompleteInstruction(int result) { if(0 != result){ last_result = result; } if(0 >= instruct_count){ S3FS_PRN_ERR("Internal error: instruct_count caused an underflow."); return false; } --instruct_count; ++completed_count; return true; } bool PseudoFdInfo::GetUploadInfo(std::string& id, int& fd) const { const std::lock_guard<std::mutex> lock(upload_list_lock); if(!IsUploadingHasLock()){ S3FS_PRN_ERR("Multipart Upload has not started yet."); return false; } id = upload_id; fd = upload_fd; return true; } bool PseudoFdInfo::GetUploadId(std::string& id) const { int fd = -1; return GetUploadInfo(id, fd); } bool PseudoFdInfo::GetEtaglist(etaglist_t& list) const { const std::lock_guard<std::mutex> lock(upload_list_lock); if(!IsUploadingHasLock()){ S3FS_PRN_ERR("Multipart Upload has not started yet."); return false; } list.clear(); for(auto iter = upload_list.cbegin(); iter != upload_list.cend(); ++iter){ if(iter->petag){ list.push_back(*(iter->petag)); }else{ S3FS_PRN_ERR("The pointer to the etag string is null(internal error)."); return false; } } return !list.empty(); } // [NOTE] // This method adds a part for a multipart upload. // The added new part must be an area that is exactly continuous with the // immediately preceding part. // An error will occur if it is discontinuous or if it overlaps with an // existing area. // bool PseudoFdInfo::AppendUploadPart(off_t start, off_t size, bool is_copy, etagpair** ppetag) { const std::lock_guard<std::mutex> lock(upload_list_lock); if(!IsUploadingHasLock()){ S3FS_PRN_ERR("Multipart Upload has not started yet."); return false; } off_t next_start_pos = 0; if(!upload_list.empty()){ next_start_pos = upload_list.back().startpos + upload_list.back().size; } if(start != next_start_pos){ S3FS_PRN_ERR("The expected starting position for the next part is %lld, but %lld was specified.", static_cast<long long int>(next_start_pos), static_cast<long long int>(start)); return false; } // make part number int partnumber = static_cast<int>(upload_list.size()) + 1; // add new part etagpair* petag_entity = etag_entities.add(etagpair(nullptr, partnumber)); // [NOTE] Create the etag entity and register it in the list. upload_list.emplace_back(false, physical_fd, start, size, is_copy, petag_entity); // set etag pointer if(ppetag){ *ppetag = petag_entity; } return true; } // // Utility for sorting upload list // static bool filepart_partnum_compare(const filepart& src1, const filepart& src2) { return src1.get_part_number() < src2.get_part_number(); } bool PseudoFdInfo::InsertUploadPart(off_t start, off_t size, int part_num, bool is_copy, etagpair** ppetag) { const std::lock_guard<std::mutex> lock(upload_list_lock); //S3FS_PRN_DBG("[start=%lld][size=%lld][part_num=%d][is_copy=%s]", static_cast<long long int>(start), static_cast<long long int>(size), part_num, (is_copy ? "true" : "false")); if(!IsUploadingHasLock()){ S3FS_PRN_ERR("Multipart Upload has not started yet."); return false; } if(start < 0 || size <= 0 || part_num < 0 || !ppetag){ S3FS_PRN_ERR("Parameters are wrong."); return false; } // insert new part etagpair* petag_entity = etag_entities.add(etagpair(nullptr, part_num)); upload_list.emplace_back(false, physical_fd, start, size, is_copy, petag_entity); // sort by part number std::sort(upload_list.begin(), upload_list.end(), filepart_partnum_compare); // set etag pointer *ppetag = petag_entity; return true; } // [NOTE] // This method only launches the upload thread. // Check the maximum number of threads before calling. // bool PseudoFdInfo::ParallelMultipartUpload(const char* path, const mp_part_list_t& mplist, bool is_copy) { //S3FS_PRN_DBG("[path=%s][mplist(%zu)]", SAFESTRPTR(path), mplist.size()); if(mplist.empty()){ // nothing to do return true; } if(!OpenUploadFd()){ return false; } // Get upload id/fd before loop std::string tmp_upload_id; int tmp_upload_fd = -1; if(!GetUploadInfo(tmp_upload_id, tmp_upload_fd)){ return false; } for(auto iter = mplist.cbegin(); iter != mplist.cend(); ++iter){ // Insert upload part etagpair* petag = nullptr; if(!InsertUploadPart(iter->start, iter->size, iter->part_num, is_copy, &petag)){ S3FS_PRN_ERR("Failed to insert insert upload part(path=%s, start=%lld, size=%lld, part=%d, copy=%s) to mplist", SAFESTRPTR(path), static_cast<long long int>(iter->start), static_cast<long long int>(iter->size), iter->part_num, (is_copy ? "true" : "false")); return false; } // make parameter for my thread auto* thargs = new pseudofdinfo_mpupload_thparam; thargs->ppseudofdinfo = this; thargs->path = SAFESTRPTR(path); thargs->upload_id = tmp_upload_id; thargs->upload_fd = tmp_upload_fd; thargs->start = iter->start; thargs->size = iter->size; thargs->is_copy = is_copy; thargs->part_num = iter->part_num; thargs->petag = petag; // make parameter for thread pool thpoolman_param ppoolparam; ppoolparam.args = thargs; ppoolparam.psem = &uploaded_sem; ppoolparam.pfunc = PseudoFdInfo::MultipartUploadThreadWorker; // setup instruction if(!ThreadPoolMan::Instruct(ppoolparam)){ S3FS_PRN_ERR("failed setup instruction for uploading."); delete thargs; return false; } IncreaseInstructionCount(); } return true; } bool PseudoFdInfo::ParallelMultipartUploadAll(const char* path, const mp_part_list_t& to_upload_list, const mp_part_list_t& copy_list, int& result) { S3FS_PRN_DBG("[path=%s][to_upload_list(%zu)][copy_list(%zu)]", SAFESTRPTR(path), to_upload_list.size(), copy_list.size()); result = 0; if(!OpenUploadFd()){ return false; } if(!ParallelMultipartUpload(path, to_upload_list, false) || !ParallelMultipartUpload(path, copy_list, true)){ S3FS_PRN_ERR("Failed setup instruction for uploading(path=%s, to_upload_list=%zu, copy_list=%zu).", SAFESTRPTR(path), to_upload_list.size(), copy_list.size()); return false; } // Wait for all thread exiting result = WaitAllThreadsExit(); return true; } // // Common method that calls S3fsCurl::PreMultipartUploadRequest via pre_multipart_upload_request // // [NOTE] // If the request is successful, initialize upload_id. // bool PseudoFdInfo::PreMultipartUploadRequest(const std::string& strpath, const headers_t& meta) { // get upload_id std::string new_upload_id; if(0 != pre_multipart_upload_request(strpath, meta, new_upload_id)){ return false; } // reset upload_id if(!RowInitialUploadInfo(new_upload_id, false/* not need to cancel */)){ S3FS_PRN_ERR("failed to setup multipart upload(set upload id to object)"); return false; } S3FS_PRN_DBG("succeed to setup multipart upload(set upload id to object)"); return true; } // // Upload the last updated Untreated area // // [Overview] // Uploads untreated areas with the maximum multipart upload size as the // boundary. // // * The starting position of the untreated area is aligned with the maximum // multipart upload size as the boundary. // * If there is an uploaded area that overlaps with the aligned untreated // area, that uploaded area is canceled and absorbed by the untreated area. // * Upload only when the aligned untreated area exceeds the maximum multipart // upload size. // * When the start position of the untreated area is changed to boundary // alignment(to backward), and if that gap area is remained, that area is // rest to untreated area. // ssize_t PseudoFdInfo::UploadBoundaryLastUntreatedArea(const char* path, headers_t& meta, FdEntity* pfdent) { S3FS_PRN_DBG("[path=%s][pseudo_fd=%d][physical_fd=%d]", SAFESTRPTR(path), pseudo_fd, physical_fd); if(!path || -1 == physical_fd || -1 == pseudo_fd || !pfdent){ S3FS_PRN_ERR("pseudo_fd(%d) to physical_fd(%d) for path(%s) is not opened or not writable, or pfdent is nullptr.", pseudo_fd, physical_fd, path); return -EBADF; } // // Get last update untreated area // off_t last_untreated_start = 0; off_t last_untreated_size = 0; if(!pfdent->GetLastUpdateUntreatedPart(last_untreated_start, last_untreated_size) || last_untreated_start < 0 || last_untreated_size <= 0){ S3FS_PRN_WARN("Not found last update untreated area or it is empty, thus return without any error."); return 0; } // // Aligns the start position of the last updated raw area with the boundary // // * Align the last updated raw space with the maximum upload size boundary. // * The remaining size of the part before the boundary is will not be uploaded. // off_t max_mp_size = S3fsCurl::GetMultipartSize(); off_t aligned_start = ((last_untreated_start / max_mp_size) + (0 < (last_untreated_start % max_mp_size) ? 1 : 0)) * max_mp_size; if((last_untreated_start + last_untreated_size) <= aligned_start){ S3FS_PRN_INFO("After the untreated area(start=%lld, size=%lld) is aligned with the boundary, the aligned start(%lld) exceeds the untreated area, so there is nothing to do.", static_cast<long long int>(last_untreated_start), static_cast<long long int>(last_untreated_size), static_cast<long long int>(aligned_start)); return 0; } off_t aligned_size = (((last_untreated_start + last_untreated_size) - aligned_start) / max_mp_size) * max_mp_size; if(0 == aligned_size){ S3FS_PRN_DBG("After the untreated area(start=%lld, size=%lld) is aligned with the boundary(start is %lld), the aligned size is empty, so nothing to do.", static_cast<long long int>(last_untreated_start), static_cast<long long int>(last_untreated_size), static_cast<long long int>(aligned_start)); return 0; } off_t front_rem_start = last_untreated_start; // start of the remainder untreated area in front of the boundary off_t front_rem_size = aligned_start - last_untreated_start; // size of the remainder untreated area in front of the boundary // // Get the area for uploading, if last update treated area can be uploaded. // // [NOTE] // * Create the updoad area list, if the untreated area aligned with the boundary // exceeds the maximum upload size. // * If it overlaps with an area that has already been uploaded(unloaded list), // that area is added to the cancellation list and included in the untreated area. // mp_part_list_t to_upload_list; filepart_list_t cancel_uploaded_list; if(!ExtractUploadPartsFromUntreatedArea(aligned_start, aligned_size, to_upload_list, cancel_uploaded_list, S3fsCurl::GetMultipartSize())){ S3FS_PRN_ERR("Failed to extract upload parts from last untreated area."); return -EIO; } if(to_upload_list.empty()){ S3FS_PRN_INFO("There is nothing to upload. In most cases, the untreated area does not meet the upload size."); return 0; } // // Has multipart uploading already started? // if(!IsUploading()){ std::string strpath = SAFESTRPTR(path); if(!PreMultipartUploadRequest(strpath, meta)){ return -EIO; } } // // Output debug level information // // When canceling(overwriting) a part that has already been uploaded, output it. // if(S3fsLog::IsS3fsLogDbg()){ for(auto cancel_iter = cancel_uploaded_list.cbegin(); cancel_iter != cancel_uploaded_list.cend(); ++cancel_iter){ S3FS_PRN_DBG("Cancel uploaded: start(%lld), size(%lld), part number(%d)", static_cast<long long int>(cancel_iter->startpos), static_cast<long long int>(cancel_iter->size), (cancel_iter->petag ? cancel_iter->petag->part_num : -1)); } } // // Upload Multipart parts // if(!ParallelMultipartUpload(path, to_upload_list, false)){ S3FS_PRN_ERR("Failed to upload multipart parts."); return -EIO; } // // Exclude the uploaded Untreated area and update the last Untreated area. // off_t behind_rem_start = aligned_start + aligned_size; off_t behind_rem_size = (last_untreated_start + last_untreated_size) - behind_rem_start; if(!pfdent->ReplaceLastUpdateUntreatedPart(front_rem_start, front_rem_size, behind_rem_start, behind_rem_size)){ S3FS_PRN_WARN("The last untreated area could not be detected and the uploaded area could not be excluded from it, but continue because it does not affect the overall processing."); } return 0; } int PseudoFdInfo::WaitAllThreadsExit() { int result; bool is_loop = true; { const std::lock_guard<std::mutex> lock(upload_list_lock); if(0 == instruct_count && 0 == completed_count){ result = last_result; is_loop = false; } } while(is_loop){ // need to wait the worker exiting uploaded_sem.acquire(); { const std::lock_guard<std::mutex> lock(upload_list_lock); if(0 < completed_count){ --completed_count; } if(0 == instruct_count && 0 == completed_count){ // break loop result = last_result; is_loop = false; } } } return result; } bool PseudoFdInfo::CancelAllThreads() { bool need_cancel = false; { const std::lock_guard<std::mutex> lock(upload_list_lock); if(0 < instruct_count && 0 < completed_count){ S3FS_PRN_INFO("The upload thread is running, so cancel them and wait for the end."); need_cancel = true; last_result = -ECANCELED; // to stop thread running } } if(need_cancel){ WaitAllThreadsExit(); } return true; } // // Extract the list for multipart upload from the Unteated Area // // The untreated_start parameter must be set aligning it with the boundaries // of the maximum multipart upload size. This method expects it to be bounded. // // This method creates the upload area aligned from the untreated area by // maximum size and creates the required list. // If it overlaps with an area that has already been uploaded, the overlapped // upload area will be canceled and absorbed by the untreated area. // If the list creation process is complete and areas smaller than the maximum // size remain, those area will be reset to untreated_start and untreated_size // and returned to the caller. // If the called untreated area is smaller than the maximum size of the // multipart upload, no list will be created. // // [NOTE] // Maximum multipart upload size must be uploading boundary. // bool PseudoFdInfo::ExtractUploadPartsFromUntreatedArea(off_t untreated_start, off_t untreated_size, mp_part_list_t& to_upload_list, filepart_list_t& cancel_upload_list, off_t max_mp_size) { if(untreated_start < 0 || untreated_size <= 0){ S3FS_PRN_ERR("Parameters are wrong(untreated_start=%lld, untreated_size=%lld).", static_cast<long long int>(untreated_start), static_cast<long long int>(untreated_size)); return false; } // Initialize lists to_upload_list.clear(); cancel_upload_list.clear(); // // Align start position with maximum multipart upload boundaries // off_t aligned_start = (untreated_start / max_mp_size) * max_mp_size; off_t aligned_size = untreated_size + (untreated_start - aligned_start); // // Check aligned untreated size // if(aligned_size < max_mp_size){ S3FS_PRN_INFO("untreated area(start=%lld, size=%lld) to aligned boundary(start=%lld, size=%lld) is smaller than max mp size(%lld), so nothing to do.", static_cast<long long int>(untreated_start), static_cast<long long int>(untreated_size), static_cast<long long int>(aligned_start), static_cast<long long int>(aligned_size), static_cast<long long int>(max_mp_size)); return true; // successful termination } // // Check each unloaded area in list // // [NOTE] // The uploaded area must be to be aligned by boundary. // Also, it is assumed that it must not be a copy area. // So if the areas overlap, include uploaded area as an untreated area. // { const std::lock_guard<std::mutex> lock(upload_list_lock); for(auto cur_iter = upload_list.begin(); cur_iter != upload_list.end(); /* ++cur_iter */){ // Check overlap if((cur_iter->startpos + cur_iter->size - 1) < aligned_start || (aligned_start + aligned_size - 1) < cur_iter->startpos){ // Areas do not overlap ++cur_iter; }else{ // The areas overlap // // Since the start position of the uploaded area is aligned with the boundary, // it is not necessary to check the start position. // If the uploaded area exceeds the untreated area, expand the untreated area. // if((aligned_start + aligned_size - 1) < (cur_iter->startpos + cur_iter->size - 1)){ aligned_size += (cur_iter->startpos + cur_iter->size) - (aligned_start + aligned_size); } // // Add this to cancel list // cancel_upload_list.push_back(*cur_iter); // Copy and Push to cancel list cur_iter = upload_list.erase(cur_iter); } } } // // Add upload area to the list // while(max_mp_size <= aligned_size){ int part_num = static_cast<int>((aligned_start / max_mp_size) + 1); to_upload_list.emplace_back(aligned_start, max_mp_size, part_num); aligned_start += max_mp_size; aligned_size -= max_mp_size; } return true; } // // Extract the area lists to be uploaded/downloaded for the entire file. // // [Parameters] // to_upload_list : A list of areas to upload in multipart upload. // to_copy_list : A list of areas for copy upload in multipart upload. // to_download_list : A list of areas that must be downloaded before multipart upload. // cancel_upload_list : A list of areas that have already been uploaded and will be canceled(overwritten). // wait_upload_complete : If cancellation areas exist, this flag is set to true when it is necessary to wait until the upload of those cancellation areas is complete. // file_size : The size of the upload file. // use_copy : Specify true if copy multipart upload is available. // // [NOTE] // The untreated_list in fdentity does not change, but upload_list is changed. // (If you want to restore it, you can use cancel_upload_list.) // bool PseudoFdInfo::ExtractUploadPartsFromAllArea(UntreatedParts& untreated_list, mp_part_list_t& to_upload_list, mp_part_list_t& to_copy_list, mp_part_list_t& to_download_list, filepart_list_t& cancel_upload_list, bool& wait_upload_complete, off_t max_mp_size, off_t file_size, bool use_copy) { const std::lock_guard<std::mutex> lock(upload_list_lock); // Initialize lists to_upload_list.clear(); to_copy_list.clear(); to_download_list.clear(); cancel_upload_list.clear(); wait_upload_complete = false; // Duplicate untreated list untreated_list_t dup_untreated_list; untreated_list.Duplicate(dup_untreated_list); // Initialize the iterator of each list first auto dup_untreated_iter = dup_untreated_list.begin(); auto uploaded_iter = upload_list.begin(); // // Loop to extract areas to upload and download // // Check at the boundary of the maximum upload size from the beginning of the file // for(off_t cur_start = 0, cur_size = 0; cur_start < file_size; cur_start += cur_size){ // // Set part size // (To avoid confusion, the area to be checked is called the "current area".) // cur_size = ((cur_start + max_mp_size) <= file_size ? max_mp_size : (file_size - cur_start)); // // Extract the untreated erea that overlaps this current area. // (The extracted area is deleted from dup_untreated_list.) // untreated_list_t cur_untreated_list; for(cur_untreated_list.clear(); dup_untreated_iter != dup_untreated_list.end(); ){ if((dup_untreated_iter->start < (cur_start + cur_size)) && (cur_start < (dup_untreated_iter->start + dup_untreated_iter->size))){ // this untreated area is overlap off_t tmp_untreated_start; off_t tmp_untreated_size; if(dup_untreated_iter->start < cur_start){ // [NOTE] // This untreated area overlaps with the current area, but starts // in front of the target area. // This state should not be possible, but if this state is detected, // the part before the target area will be deleted. // tmp_untreated_start = cur_start; tmp_untreated_size = dup_untreated_iter->size - (cur_start - dup_untreated_iter->start); }else{ tmp_untreated_start = dup_untreated_iter->start; tmp_untreated_size = dup_untreated_iter->size; } // // Check the end of the overlapping untreated area. // if((tmp_untreated_start + tmp_untreated_size) <= (cur_start + cur_size)){ // // All of untreated areas are within the current area // // - Add this untreated area to cur_untreated_list // - Delete this from dup_untreated_list // cur_untreated_list.emplace_back(tmp_untreated_start, tmp_untreated_size); dup_untreated_iter = dup_untreated_list.erase(dup_untreated_iter); }else{ // // The untreated area exceeds the end of the current area // // Adjust untreated area tmp_untreated_size = (cur_start + cur_size) - tmp_untreated_start; // Add adjusted untreated area to cur_untreated_list cur_untreated_list.emplace_back(tmp_untreated_start, tmp_untreated_size); // Remove this adjusted untreated area from the area pointed // to by dup_untreated_iter. dup_untreated_iter->size = (dup_untreated_iter->start + dup_untreated_iter->size) - (cur_start + cur_size); dup_untreated_iter->start = tmp_untreated_start + tmp_untreated_size; } }else if((cur_start + cur_size - 1) < dup_untreated_iter->start){ // this untreated area is over the current area, thus break loop. break; }else{ ++dup_untreated_iter; } } // // Check uploaded area // // [NOTE] // The uploaded area should be aligned with the maximum upload size boundary. // It also assumes that each size of uploaded area must be a maximum upload // size. // auto overlap_uploaded_iter = upload_list.end(); for(; uploaded_iter != upload_list.end(); ++uploaded_iter){ if((cur_start < (uploaded_iter->startpos + uploaded_iter->size)) && (uploaded_iter->startpos < (cur_start + cur_size))){ if(overlap_uploaded_iter != upload_list.end()){ // // Something wrong in this unloaded area. // // This area is not aligned with the boundary, then this condition // is unrecoverable and return failure. // S3FS_PRN_ERR("The uploaded list may not be the boundary for the maximum multipart upload size. No further processing is possible."); return false; } // Set this iterator to overlap iter overlap_uploaded_iter = uploaded_iter; }else if((cur_start + cur_size - 1) < uploaded_iter->startpos){ break; } } // // Create upload/download/cancel/copy list for this current area // int part_num = static_cast<int>((cur_start / max_mp_size) + 1); if(cur_untreated_list.empty()){ // // No untreated area was detected in this current area // if(overlap_uploaded_iter != upload_list.end()){ // // This current area already uploaded, then nothing to add to lists. // S3FS_PRN_DBG("Already uploaded: start=%lld, size=%lld", static_cast<long long int>(cur_start), static_cast<long long int>(cur_size)); }else{ // // This current area has not been uploaded // (neither an uploaded area nor an untreated area.) // if(use_copy){ // // Copy multipart upload available // S3FS_PRN_DBG("To copy: start=%lld, size=%lld", static_cast<long long int>(cur_start), static_cast<long long int>(cur_size)); to_copy_list.emplace_back(cur_start, cur_size, part_num); }else{ // // This current area needs to be downloaded and uploaded // S3FS_PRN_DBG("To download and upload: start=%lld, size=%lld", static_cast<long long int>(cur_start), static_cast<long long int>(cur_size)); to_download_list.emplace_back(cur_start, cur_size); to_upload_list.emplace_back(cur_start, cur_size, part_num); } } }else{ // // Found untreated area in this current area // if(overlap_uploaded_iter != upload_list.end()){ // // This current area is also the uploaded area // // [NOTE] // The uploaded area is aligned with boundary, there are all data in // this current area locally(which includes all data of untreated area). // So this current area only needs to be uploaded again. // S3FS_PRN_DBG("Cancel upload: start=%lld, size=%lld", static_cast<long long int>(overlap_uploaded_iter->startpos), static_cast<long long int>(overlap_uploaded_iter->size)); if(!overlap_uploaded_iter->uploaded){ S3FS_PRN_DBG("This cancel upload area is still uploading, so you must wait for it to complete before starting any Stream uploads."); wait_upload_complete = true; } cancel_upload_list.push_back(*overlap_uploaded_iter); // add this uploaded area to cancel_upload_list uploaded_iter = upload_list.erase(overlap_uploaded_iter); // remove it from upload_list S3FS_PRN_DBG("To upload: start=%lld, size=%lld", static_cast<long long int>(cur_start), static_cast<long long int>(cur_size)); to_upload_list.emplace_back(cur_start, cur_size, part_num); // add new uploading area to list }else{ // // No uploaded area overlap this current area // (Areas other than the untreated area must be downloaded.) // // [NOTE] // Need to consider the case where there is a gap between the start // of the current area and the untreated area. // This gap is the area that should normally be downloaded. // But it is the area that can be copied if we can use copy multipart // upload. Then If we can use copy multipart upload and the previous // area is used copy multipart upload, this gap will be absorbed by // the previous area. // Unifying the copy multipart upload area can reduce the number of // upload requests. // off_t tmp_cur_start = cur_start; off_t tmp_cur_size = cur_size; off_t changed_start = cur_start; off_t changed_size = cur_size; bool first_area = true; for(auto tmp_cur_untreated_iter = cur_untreated_list.cbegin(); tmp_cur_untreated_iter != cur_untreated_list.cend(); ++tmp_cur_untreated_iter, first_area = false){ if(tmp_cur_start < tmp_cur_untreated_iter->start){ // // Detected a gap at the start of area // bool include_prev_copy_part = false; if(first_area && use_copy && !to_copy_list.empty()){ // // Make sure that the area of the last item in to_copy_list // is contiguous with this current area. // // [NOTE] // Areas can be unified if the total size of the areas is // within 5GB and the remaining area after unification is // larger than the minimum multipart upload size. // auto copy_riter = to_copy_list.rbegin(); if( (copy_riter->start + copy_riter->size) == tmp_cur_start && (copy_riter->size + (tmp_cur_untreated_iter->start - tmp_cur_start)) <= FIVE_GB && ((tmp_cur_start + tmp_cur_size) - tmp_cur_untreated_iter->start) >= MIN_MULTIPART_SIZE ) { // // Unify to this area to previous copy area. // copy_riter->size += tmp_cur_untreated_iter->start - tmp_cur_start; S3FS_PRN_DBG("Resize to copy: start=%lld, size=%lld", static_cast<long long int>(copy_riter->start), static_cast<long long int>(copy_riter->size)); changed_size -= (tmp_cur_untreated_iter->start - changed_start); changed_start = tmp_cur_untreated_iter->start; include_prev_copy_part = true; } } if(!include_prev_copy_part){ // // If this area is not unified, need to download this area // S3FS_PRN_DBG("To download: start=%lld, size=%lld", static_cast<long long int>(tmp_cur_start), static_cast<long long int>(tmp_cur_untreated_iter->start - tmp_cur_start)); to_download_list.emplace_back(tmp_cur_start, tmp_cur_untreated_iter->start - tmp_cur_start); } } // // Set next start position // tmp_cur_size = (tmp_cur_start + tmp_cur_size) - (tmp_cur_untreated_iter->start + tmp_cur_untreated_iter->size); tmp_cur_start = tmp_cur_untreated_iter->start + tmp_cur_untreated_iter->size; } // // Add download area to list, if remaining size // if(0 < tmp_cur_size){ S3FS_PRN_DBG("To download: start=%lld, size=%lld", static_cast<long long int>(tmp_cur_start), static_cast<long long int>(tmp_cur_size)); to_download_list.emplace_back(tmp_cur_start, tmp_cur_size); } // // Set upload area(whole of area) to list // S3FS_PRN_DBG("To upload: start=%lld, size=%lld", static_cast<long long int>(changed_start), static_cast<long long int>(changed_size)); to_upload_list.emplace_back(changed_start, changed_size, part_num); } } } return true; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
42,906
C++
.cpp
972
35.658436
374
0.606013
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,456
openssl_auth.cpp
s3fs-fuse_s3fs-fuse/src/openssl_auth.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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. */ #ifdef __clang__ #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif #include <cstdio> #include <cstdlib> #include <cerrno> #include <mutex> #include <unistd.h> #include <sys/stat.h> #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/md5.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <thread> #include "s3fs_auth.h" #include "s3fs_logger.h" //------------------------------------------------------------------- // Utility Function for version //------------------------------------------------------------------- const char* s3fs_crypt_lib_name() { static constexpr char version[] = "OpenSSL"; return version; } //------------------------------------------------------------------- // Utility Function for global init //------------------------------------------------------------------- bool s3fs_init_global_ssl() { ERR_load_crypto_strings(); // [NOTE] // OpenSSL 3.0 loads error strings automatically so these functions are not needed. // #ifndef USE_OPENSSL_30 ERR_load_BIO_strings(); #endif OpenSSL_add_all_algorithms(); return true; } bool s3fs_destroy_global_ssl() { EVP_cleanup(); ERR_free_strings(); return true; } //------------------------------------------------------------------- // Utility Function for crypt lock //------------------------------------------------------------------- // internal use struct for openssl struct CRYPTO_dynlock_value { std::mutex dyn_mutex; }; static std::unique_ptr<std::mutex[]> s3fs_crypt_mutex; static void s3fs_crypt_mutex_lock(int mode, int pos, const char* file, int line) __attribute__ ((unused)) NO_THREAD_SAFETY_ANALYSIS; static void s3fs_crypt_mutex_lock(int mode, int pos, const char* file, int line) { if(s3fs_crypt_mutex){ if(mode & CRYPTO_LOCK){ s3fs_crypt_mutex[pos].lock(); }else{ s3fs_crypt_mutex[pos].unlock(); } } } static unsigned long s3fs_crypt_get_threadid() __attribute__ ((unused)); static unsigned long s3fs_crypt_get_threadid() { return static_cast<unsigned long>(std::hash<std::thread::id>()(std::this_thread::get_id())); } static struct CRYPTO_dynlock_value* s3fs_dyn_crypt_mutex(const char* file, int line) __attribute__ ((unused)); static struct CRYPTO_dynlock_value* s3fs_dyn_crypt_mutex(const char* file, int line) { return new CRYPTO_dynlock_value(); } static void s3fs_dyn_crypt_mutex_lock(int mode, struct CRYPTO_dynlock_value* dyndata, const char* file, int line) __attribute__ ((unused)) NO_THREAD_SAFETY_ANALYSIS; 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){ dyndata->dyn_mutex.lock(); }else{ dyndata->dyn_mutex.unlock(); } } } static void s3fs_destroy_dyn_crypt_mutex(struct CRYPTO_dynlock_value* dyndata, const char* file, int line) __attribute__ ((unused)); static void s3fs_destroy_dyn_crypt_mutex(struct CRYPTO_dynlock_value* dyndata, const char* file, int line) { delete dyndata; } bool s3fs_init_crypt_mutex() { if(s3fs_crypt_mutex){ S3FS_PRN_DBG("s3fs_crypt_mutex is not nullptr, destroy it."); // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(!s3fs_destroy_crypt_mutex()){ S3FS_PRN_ERR("Failed to s3fs_crypt_mutex"); return false; } } s3fs_crypt_mutex.reset(new std::mutex[CRYPTO_num_locks()]); // 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() { if(!s3fs_crypt_mutex){ return true; } CRYPTO_set_dynlock_destroy_callback(nullptr); CRYPTO_set_dynlock_lock_callback(nullptr); CRYPTO_set_dynlock_create_callback(nullptr); CRYPTO_set_id_callback(nullptr); CRYPTO_set_locking_callback(nullptr); CRYPTO_cleanup_all_ex_data(); s3fs_crypt_mutex.reset(); return true; } //------------------------------------------------------------------- // Utility Function for HMAC //------------------------------------------------------------------- static std::unique_ptr<unsigned char[]> s3fs_HMAC_RAW(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned int* digestlen, bool is_sha256) { if(!key || !data || !digestlen){ return nullptr; } (*digestlen) = EVP_MAX_MD_SIZE * sizeof(unsigned char); std::unique_ptr<unsigned char[]> digest(new unsigned char[*digestlen]); if(is_sha256){ HMAC(EVP_sha256(), key, static_cast<int>(keylen), data, datalen, digest.get(), digestlen); }else{ HMAC(EVP_sha1(), key, static_cast<int>(keylen), data, datalen, digest.get(), digestlen); } return digest; } std::unique_ptr<unsigned char[]> s3fs_HMAC(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned int* digestlen) { return s3fs_HMAC_RAW(key, keylen, data, datalen, digestlen, false); } std::unique_ptr<unsigned char[]> s3fs_HMAC256(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned int* digestlen) { return s3fs_HMAC_RAW(key, keylen, data, datalen, digestlen, true); } #ifdef USE_OPENSSL_30 //------------------------------------------------------------------- // Utility Function for MD5 (OpenSSL >= 3.0) //------------------------------------------------------------------- // [NOTE] // OpenSSL 3.0 deprecated the MD5_*** low-level encryption functions, // so we should use the high-level EVP API instead. // bool s3fs_md5(const unsigned char* data, size_t datalen, md5_t* digest) { auto digestlen = static_cast<unsigned int>(digest->size()); const EVP_MD* md = EVP_get_digestbyname("md5"); EVP_MD_CTX* mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, nullptr); EVP_DigestUpdate(mdctx, data, datalen); EVP_DigestFinal_ex(mdctx, digest->data(), &digestlen); EVP_MD_CTX_destroy(mdctx); return true; } bool s3fs_md5_fd(int fd, off_t start, off_t size, md5_t* result) { auto md5_digest_len = static_cast<unsigned int>(result->size()); off_t bytes; if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ return false; } size = st.st_size; } // instead of MD5_Init std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> mdctx(EVP_MD_CTX_new(), EVP_MD_CTX_free); EVP_DigestInit_ex(mdctx.get(), EVP_md5(), nullptr); for(off_t total = 0; total < size; total += bytes){ std::array<char, 512> buf; bytes = std::min(static_cast<off_t>(buf.size()), (size - total)); bytes = pread(fd, buf.data(), bytes, start + total); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); return false; } // instead of MD5_Update EVP_DigestUpdate(mdctx.get(), buf.data(), bytes); } // instead of MD5_Final EVP_DigestFinal_ex(mdctx.get(), result->data(), &md5_digest_len); return true; } #else //------------------------------------------------------------------- // Utility Function for MD5 (OpenSSL < 3.0) //------------------------------------------------------------------- // TODO: Does this fail on OpenSSL < 3.0 and we need to use MD5_CTX functions? bool s3fs_md5(const unsigned char* data, size_t datalen, md5_t* digest) { unsigned int digestlen = digest->size(); const EVP_MD* md = EVP_get_digestbyname("md5"); EVP_MD_CTX* mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, nullptr); EVP_DigestUpdate(mdctx, data, datalen); EVP_DigestFinal_ex(mdctx, digest->data(), &digestlen); EVP_MD_CTX_destroy(mdctx); return true; } bool s3fs_md5_fd(int fd, off_t start, off_t size, md5_t* result) { MD5_CTX md5ctx; off_t bytes; if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ return false; } size = st.st_size; } MD5_Init(&md5ctx); for(off_t total = 0; total < size; total += bytes){ std::array<char, 512> buf; bytes = std::min(static_cast<off_t>(buf.size()), (size - total)); bytes = pread(fd, buf.data(), bytes, start + total); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); return false; } MD5_Update(&md5ctx, buf.data(), bytes); } MD5_Final(result->data(), &md5ctx); return true; } #endif //------------------------------------------------------------------- // Utility Function for SHA256 //------------------------------------------------------------------- bool s3fs_sha256(const unsigned char* data, size_t datalen, sha256_t* digest) { const EVP_MD* md = EVP_get_digestbyname("sha256"); EVP_MD_CTX* mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, nullptr); EVP_DigestUpdate(mdctx, data, datalen); auto digestlen = static_cast<unsigned int>(digest->size()); EVP_DigestFinal_ex(mdctx, digest->data(), &digestlen); EVP_MD_CTX_destroy(mdctx); return true; } bool s3fs_sha256_fd(int fd, off_t start, off_t size, sha256_t* result) { const EVP_MD* md = EVP_get_digestbyname("sha256"); EVP_MD_CTX* sha256ctx; off_t bytes; if(-1 == fd){ return false; } if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ S3FS_PRN_ERR("fstat error(%d)", errno); return false; } size = st.st_size; } sha256ctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(sha256ctx, md, nullptr); for(off_t total = 0; total < size; total += bytes){ std::array<char, 512> buf; bytes = std::min(static_cast<off_t>(buf.size()), (size - total)); bytes = pread(fd, buf.data(), bytes, start + total); 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 false; } EVP_DigestUpdate(sha256ctx, buf.data(), bytes); } EVP_DigestFinal_ex(sha256ctx, result->data(), nullptr); EVP_MD_CTX_destroy(sha256ctx); return true; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
11,827
C++
.cpp
328
31.29878
169
0.596382
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,457
threadpoolman.cpp
s3fs-fuse_s3fs-fuse/src/threadpoolman.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <cerrno> #include <cstdio> #include <cstdlib> #include <future> #include <mutex> #include <thread> #include <utility> #include "s3fs_logger.h" #include "threadpoolman.h" //------------------------------------------------ // ThreadPoolMan class variables //------------------------------------------------ std::unique_ptr<ThreadPoolMan> ThreadPoolMan::singleton; //------------------------------------------------ // ThreadPoolMan class methods //------------------------------------------------ bool ThreadPoolMan::Initialize(int count) { if(ThreadPoolMan::singleton){ S3FS_PRN_CRIT("Already singleton for Thread Manager exists."); abort(); } ThreadPoolMan::singleton.reset(new ThreadPoolMan(count)); return true; } void ThreadPoolMan::Destroy() { ThreadPoolMan::singleton.reset(); } bool ThreadPoolMan::Instruct(const thpoolman_param& param) { if(!ThreadPoolMan::singleton){ S3FS_PRN_WARN("The singleton object is not initialized yet."); return false; } if(!param.psem){ S3FS_PRN_ERR("Thread parameter Semaphore is null."); return false; } ThreadPoolMan::singleton->SetInstruction(param); return true; } bool ThreadPoolMan::AwaitInstruct(const thpoolman_param& param) { if(!ThreadPoolMan::singleton){ S3FS_PRN_WARN("The singleton object is not initialized yet."); return false; } if(param.psem){ S3FS_PRN_ERR("Thread parameter Semaphore must be null."); return false; } // Setup local thpoolman_param structure with local Semaphore thpoolman_param local_param; Semaphore await_sem(0); local_param.args = param.args; local_param.psem = &await_sem; local_param.pfunc = param.pfunc; // Set parameters and run thread worker ThreadPoolMan::singleton->SetInstruction(local_param); // wait until the thread is complete await_sem.acquire(); return true; } // // Thread worker // void ThreadPoolMan::Worker(ThreadPoolMan* psingleton, std::promise<int> promise) { if(!psingleton){ S3FS_PRN_ERR("The parameter for worker thread is invalid."); promise.set_value(-EIO); return; } S3FS_PRN_INFO3("Start worker thread in ThreadPoolMan."); while(!psingleton->IsExit()){ // wait psingleton->thpoolman_sem.acquire(); if(psingleton->IsExit()){ break; } // get instruction thpoolman_param param; { const std::lock_guard<std::mutex> lock(psingleton->thread_list_lock); if(psingleton->instruction_list.empty()){ S3FS_PRN_DBG("Got a semaphore, but the instruction is empty."); continue; }else{ param = psingleton->instruction_list.front(); psingleton->instruction_list.pop_front(); } } void* retval = param.pfunc(param.args); if(nullptr != retval){ S3FS_PRN_WARN("The instruction function returned with something error code(%ld).", reinterpret_cast<long>(retval)); } if(param.psem){ param.psem->release(); } } promise.set_value(0); } //------------------------------------------------ // ThreadPoolMan methods //------------------------------------------------ ThreadPoolMan::ThreadPoolMan(int count) : is_exit(false), thpoolman_sem(0) { if(count < 1){ S3FS_PRN_CRIT("Failed to creating singleton for Thread Manager, because thread count(%d) is under 1.", count); abort(); } if(ThreadPoolMan::singleton){ S3FS_PRN_CRIT("Already singleton for Thread Manager exists."); abort(); } // create threads if(!StartThreads(count)){ S3FS_PRN_ERR("Failed starting threads at initializing."); abort(); } } ThreadPoolMan::~ThreadPoolMan() { StopThreads(); } bool ThreadPoolMan::IsExit() const { return is_exit; } void ThreadPoolMan::SetExitFlag(bool exit_flag) { is_exit = exit_flag; } bool ThreadPoolMan::StopThreads() { const std::lock_guard<std::mutex> lock(thread_list_lock); if(thread_list.empty()){ S3FS_PRN_INFO("Any threads are running now, then nothing to do."); return true; } // all threads to exit SetExitFlag(true); for(size_t waitcnt = thread_list.size(); 0 < waitcnt; --waitcnt){ thpoolman_sem.release(); } // wait for threads exiting for(auto& pair : thread_list){ pair.first.join(); long retval = pair.second.get(); S3FS_PRN_DBG("join succeeded - return code(%ld)", reinterpret_cast<long>(retval)); } thread_list.clear(); // reset semaphore(to zero) while(thpoolman_sem.try_acquire()){ } return true; } bool ThreadPoolMan::StartThreads(int count) { if(count < 1){ S3FS_PRN_ERR("Failed to creating threads, because thread count(%d) is under 1.", count); return false; } // stop all thread if they are running. // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(!StopThreads()){ S3FS_PRN_ERR("Failed to stop existed threads."); return false; } // create all threads SetExitFlag(false); for(int cnt = 0; cnt < count; ++cnt){ // run thread std::promise<int> promise; std::future<int> future = promise.get_future(); std::thread thread(ThreadPoolMan::Worker, this, std::move(promise)); const std::lock_guard<std::mutex> lock(thread_list_lock); thread_list.emplace_back(std::move(thread), std::move(future)); } return true; } void ThreadPoolMan::SetInstruction(const thpoolman_param& param) { // set parameter to list { const std::lock_guard<std::mutex> lock(thread_list_lock); instruction_list.push_back(param); } // run thread thpoolman_sem.release(); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
6,943
C++
.cpp
220
26.477273
127
0.635412
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,458
curl.cpp
s3fs-fuse_s3fs-fuse/src/curl.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <algorithm> #include <cerrno> #include <cstdio> #include <cstdlib> #include <ctime> #include <fstream> #include <memory> #include <mutex> #include <sstream> #include <string> #include <unistd.h> #include <utility> #include "common.h" #include "s3fs.h" #include "s3fs_logger.h" #include "curl.h" #include "curl_multi.h" #include "curl_util.h" #include "s3fs_auth.h" #include "s3fs_cred.h" #include "s3fs_util.h" #include "string_util.h" #include "addhead.h" #include "s3fs_threadreqs.h" //------------------------------------------------------------------- // Symbols //------------------------------------------------------------------- static constexpr char EMPTY_PAYLOAD_HASH[] = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; static constexpr char EMPTY_MD5_BASE64_HASH[] = "1B2M2Y8AsgTpgAmY7PhCfg=="; //------------------------------------------------------------------- // Class S3fsCurl //------------------------------------------------------------------- static constexpr int MULTIPART_SIZE = 10 * 1024 * 1024; static constexpr int GET_OBJECT_RESPONSE_LIMIT = 1024; // [NOTE] about default mime.types file // If no mime.types file is specified in the mime option, s3fs // will look for /etc/mime.types on all operating systems and // load mime information. // However, in the case of macOS, when this file does not exist, // it tries to detect the /etc/apache2/mime.types file. // The reason for this is that apache2 is preinstalled on macOS, // and the mime.types file is expected to exist in this path. // If the mime.types file is not found, s3fs will exit with an // error. // static constexpr char DEFAULT_MIME_FILE[] = "/etc/mime.types"; static constexpr char SPECIAL_DARWIN_MIME_FILE[] = "/etc/apache2/mime.types"; // [NOTICE] // This symbol is for libcurl under 7.23.0 #ifndef CURLSHE_NOT_BUILT_IN #define CURLSHE_NOT_BUILT_IN 5 #endif #if LIBCURL_VERSION_NUM >= 0x073100 #define S3FS_CURLOPT_XFERINFOFUNCTION CURLOPT_XFERINFOFUNCTION #else #define S3FS_CURLOPT_XFERINFOFUNCTION CURLOPT_PROGRESSFUNCTION #endif // Wrappers to pass std::unique_ptr to raw pointer functions. Undefine curl_easy_setopt to work around curl variadic argument macro. #undef curl_easy_setopt template<typename Arg> CURLcode curl_easy_setopt(const CurlUniquePtr& handle, CURLoption option, Arg arg) { return curl_easy_setopt(handle.get(), option, arg); } template<typename Arg> CURLcode curl_easy_getinfo(const CurlUniquePtr& handle, CURLINFO info, Arg arg) { return curl_easy_getinfo(handle.get(), info, arg); } //------------------------------------------------------------------- // Class S3fsCurl //------------------------------------------------------------------- constexpr char S3fsCurl::S3FS_SSL_PRIVKEY_PASSWORD[]; std::mutex S3fsCurl::curl_handles_lock; S3fsCurl::callback_locks_t S3fsCurl::callback_locks; bool S3fsCurl::is_initglobal_done = false; CURLSH* S3fsCurl::hCurlShare = nullptr; bool S3fsCurl::is_cert_check = true; // default bool S3fsCurl::is_dns_cache = true; // default bool S3fsCurl::is_ssl_session_cache= false;// default(This turns OFF now, but turns ON again last PR) long S3fsCurl::connect_timeout = 300; // default time_t S3fsCurl::readwrite_timeout = 120; // default int S3fsCurl::retries = 5; // default bool S3fsCurl::is_public_bucket = false; acl_t S3fsCurl::default_acl = acl_t::PRIVATE; std::string S3fsCurl::storage_class = "STANDARD"; sseckeylist_t S3fsCurl::sseckeys; std::string S3fsCurl::ssekmsid; sse_type_t S3fsCurl::ssetype = sse_type_t::SSE_DISABLE; bool S3fsCurl::is_content_md5 = false; bool S3fsCurl::is_verbose = false; bool S3fsCurl::is_dump_body = false; S3fsCred* S3fsCurl::ps3fscred = nullptr; long S3fsCurl::ssl_verify_hostname = 1; // default(original code...) // SSL client cert options std::string S3fsCurl::client_cert; std::string S3fsCurl::client_cert_type; std::string S3fsCurl::client_priv_key; std::string S3fsCurl::client_priv_key_type; std::string S3fsCurl::client_key_password; std::atomic<bool> S3fsCurl::curl_warnings_once(false); // protected by curl_handles_lock std::map<const CURL*, curlprogress> S3fsCurl::curl_progress; std::string S3fsCurl::curl_ca_bundle; mimes_t S3fsCurl::mimeTypes; std::string S3fsCurl::userAgent; int S3fsCurl::max_parallel_cnt = 5; // default int S3fsCurl::max_multireq = 20; // default off_t S3fsCurl::multipart_size = MULTIPART_SIZE; // default off_t S3fsCurl::multipart_copy_size = 512 * 1024 * 1024; // default signature_type_t S3fsCurl::signature_type = signature_type_t::V2_OR_V4; // default bool S3fsCurl::is_unsigned_payload = false; // default bool S3fsCurl::is_ua = true; // default bool S3fsCurl::listobjectsv2 = false; // default bool S3fsCurl::requester_pays = false; // default std::string S3fsCurl::proxy_url; bool S3fsCurl::proxy_http = false; std::string S3fsCurl::proxy_userpwd; long S3fsCurl::ipresolve_type = CURL_IPRESOLVE_WHATEVER; //------------------------------------------------------------------- // Class methods for S3fsCurl //------------------------------------------------------------------- bool S3fsCurl::InitS3fsCurl() { if(!S3fsCurl::InitGlobalCurl()){ return false; } if(!S3fsCurl::InitShareCurl()){ return false; } if(!S3fsCurl::InitCryptMutex()){ return false; } return true; } bool S3fsCurl::DestroyS3fsCurl() { bool result = true; if(!S3fsCurl::DestroyCryptMutex()){ result = false; } if(!S3fsCurl::DestroyShareCurl()){ result = false; } if(!S3fsCurl::DestroyGlobalCurl()){ result = false; } return result; } bool S3fsCurl::InitGlobalCurl() { 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() { if(!S3fsCurl::is_initglobal_done){ return false; } curl_global_cleanup(); S3fsCurl::is_initglobal_done = false; return true; } bool S3fsCurl::InitShareCurl() { 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(nullptr == (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, &S3fsCurl::callback_locks))){ S3FS_PRN_ERR("curl_share_setopt(USERDATA) returns %d(%s)", nSHCode, curl_share_strerror(nSHCode)); return false; } return true; } bool S3fsCurl::DestroyShareCurl() { 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 = nullptr; return true; } void S3fsCurl::LockCurlShare(CURL* handle, curl_lock_data nLockData, curl_lock_access laccess, void* useptr) { if(!hCurlShare){ return; } auto* locks = static_cast<S3fsCurl::callback_locks_t*>(useptr); if(CURL_LOCK_DATA_DNS == nLockData){ locks->dns.lock(); }else if(CURL_LOCK_DATA_SSL_SESSION == nLockData){ locks->ssl_session.lock(); } } void S3fsCurl::UnlockCurlShare(CURL* handle, curl_lock_data nLockData, void* useptr) { if(!hCurlShare){ return; } auto* locks = static_cast<S3fsCurl::callback_locks_t*>(useptr); if(CURL_LOCK_DATA_DNS == nLockData){ locks->dns.unlock(); }else if(CURL_LOCK_DATA_SSL_SESSION == nLockData){ locks->ssl_session.unlock(); } } bool S3fsCurl::InitCryptMutex() { return s3fs_init_crypt_mutex(); } bool S3fsCurl::DestroyCryptMutex() { 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<CURL*>(clientp); time_t now = time(nullptr); const std::lock_guard<std::mutex> lock(S3fsCurl::curl_handles_lock); // any progress? auto& value = S3fsCurl::curl_progress[curl]; if(value.dl_progress != dlnow || value.ul_progress != ulnow){ // yes! value = {now, dlnow, ulnow}; }else{ // timeout? if(now - value.time > readwrite_timeout){ S3FS_PRN_ERR("timeout now: %lld, curl_times[curl]: %lld, readwrite_timeout: %lld", static_cast<long long>(now), static_cast<long long>((value.time)), static_cast<long long>(readwrite_timeout)); return CURLE_ABORTED_BY_CALLBACK; } } return 0; } bool S3fsCurl::InitCredentialObject(S3fsCred* pcredobj) { // Set the only Credential object if(!pcredobj || S3fsCurl::ps3fscred){ S3FS_PRN_ERR("Unable to set the only Credential object."); return false; } S3fsCurl::ps3fscred = pcredobj; return true; } bool S3fsCurl::InitMimeType(const std::string& strFile) { std::string MimeFile; if(!strFile.empty()){ MimeFile = strFile; }else{ // search default mime.types std::string errPaths = DEFAULT_MIME_FILE; struct stat st; if(0 == stat(DEFAULT_MIME_FILE, &st)){ MimeFile = DEFAULT_MIME_FILE; }else if(compare_sysname("Darwin")){ // for macOS, search another default file. if(0 == stat(SPECIAL_DARWIN_MIME_FILE, &st)){ MimeFile = SPECIAL_DARWIN_MIME_FILE; }else{ errPaths += " and "; errPaths += SPECIAL_DARWIN_MIME_FILE; } } if(MimeFile.empty()){ S3FS_PRN_WARN("Could not find mime.types files, you have to create file(%s) or specify mime option for existing mime.types file.", errPaths.c_str()); return false; } } S3FS_PRN_DBG("Try to load mime types from %s file.", MimeFile.c_str()); std::ifstream MT(MimeFile.c_str()); if(MT.good()){ S3FS_PRN_DBG("The old mime types are cleared to load new mime types."); S3fsCurl::mimeTypes.clear(); std::string line; while(getline(MT, line)){ if(line.empty()){ continue; } if(line[0]=='#'){ continue; } std::istringstream tmp(line); std::string mimeType; tmp >> mimeType; std::string ext; while(tmp >> ext){ S3fsCurl::mimeTypes[ext] = mimeType; } } S3FS_PRN_INIT_INFO("Loaded mime information from %s", MimeFile.c_str()); }else{ S3FS_PRN_WARN("Could not load mime types from %s, please check the existence and permissions of this file.", MimeFile.c_str()); return false; } return true; } void S3fsCurl::InitUserAgent() { if(S3fsCurl::userAgent.empty()){ S3fsCurl::userAgent = "s3fs/"; S3fsCurl::userAgent += VERSION; S3fsCurl::userAgent += " (commit hash "; S3fsCurl::userAgent += COMMIT_HASH_VAL; S3fsCurl::userAgent += "; "; S3fsCurl::userAgent += s3fs_crypt_lib_name(); S3fsCurl::userAgent += ")"; S3fsCurl::userAgent += instance_name; } } // // @param s e.g., "index.html" // @return e.g., "text/html" // std::string S3fsCurl::LookupMimeType(const std::string& name) { if(!name.empty() && name[name.size() - 1] == '/'){ return "application/x-directory"; } std::string result("application/octet-stream"); std::string::size_type last_pos = name.find_last_of('.'); std::string::size_type first_pos = name.find_first_of('.'); std::string prefix, ext, ext2; // No dots in name, just return if(last_pos == std::string::npos){ return result; } // extract the last extension ext = name.substr(1+last_pos, std::string::npos); if (last_pos != std::string::npos) { // one dot was found, now look for another if (first_pos != std::string::npos && first_pos < last_pos) { prefix = name.substr(0, last_pos); // Now get the second to last file extension std::string::size_type next_pos = prefix.find_last_of('.'); if (next_pos != std::string::npos) { ext2 = prefix.substr(1+next_pos, std::string::npos); } } } // if we get here, then we have an extension (ext) auto iter = S3fsCurl::mimeTypes.find(ext); // if the last extension matches a mimeType, then return // that mime type if (iter != S3fsCurl::mimeTypes.cend()) { 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.cend()) { 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() { // 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 if(S3fsCurl::curl_ca_bundle.empty()){ char* CURL_CA_BUNDLE = getenv("CURL_CA_BUNDLE"); if(CURL_CA_BUNDLE != nullptr) { // check for existence and readability of the file std::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 = CURL_CA_BUNDLE; return true; } }else{ // Already set ca bundle variable return true; } // not set via environment variable, look in likely locations /////////////////////////////////////////// // following comment 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 /////////////////////////////////////////// // Within CURL the above path should have been checked // according to the OS. Thus, although we do not need // to check files here, we will only examine some files. // std::ifstream BF("/etc/pki/tls/certs/ca-bundle.crt"); if(BF.good()){ BF.close(); S3fsCurl::curl_ca_bundle = "/etc/pki/tls/certs/ca-bundle.crt"; }else{ BF.open("/etc/ssl/certs/ca-certificates.crt"); if(BF.good()){ BF.close(); S3fsCurl::curl_ca_bundle = "/etc/ssl/certs/ca-certificates.crt"; }else{ BF.open("/usr/share/ssl/certs/ca-bundle.crt"); if(BF.good()){ BF.close(); S3fsCurl::curl_ca_bundle = "/usr/share/ssl/certs/ca-bundle.crt"; }else{ BF.open("/usr/local/share/certs/ca-root.crt"); if(BF.good()){ BF.close(); S3fsCurl::curl_ca_bundle = "/usr/share/ssl/certs/ca-bundle.crt"; }else{ S3FS_PRN_ERR("%s: /.../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) { auto* body = static_cast<std::string*>(data); body->append(static_cast<const char*>(ptr), blockSize * numBlocks); return (blockSize * numBlocks); } size_t S3fsCurl::ReadCallback(void* ptr, size_t size, size_t nmemb, void* userp) { auto* pCurl = static_cast<S3fsCurl*>(userp); if(1 > (size * nmemb)){ return 0; } if(0 >= pCurl->postdata_remaining){ return 0; } size_t copysize = std::min(static_cast<off_t>(size * nmemb), pCurl->postdata_remaining); memcpy(ptr, pCurl->postdata, copysize); pCurl->postdata_remaining = (pCurl->postdata_remaining > static_cast<off_t>(copysize) ? (pCurl->postdata_remaining - copysize) : 0); pCurl->postdata += copysize; return copysize; } size_t S3fsCurl::HeaderCallback(void* data, size_t blockSize, size_t numBlocks, void* userPtr) { auto* headers = static_cast<headers_t*>(userPtr); std::string header(static_cast<char*>(data), blockSize * numBlocks); std::string key; std::istringstream ss(header); if(getline(ss, key, ':')){ // Force to lower, only "x-amz" std::string lkey = lower(key); if(is_prefix(lkey.c_str(), "x-amz")){ key = lkey; } std::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) { auto* pCurl = static_cast<S3fsCurl*>(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; totalread < copysize; totalread += readbytes){ readbytes = pread(pCurl->partdata.fd, &(static_cast<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) { auto* pCurl = static_cast<S3fsCurl*>(userp); if(1 > (size * nmemb)){ return 0; } if(-1 == pCurl->partdata.fd || 0 >= pCurl->partdata.size){ return 0; } // Buffer initial bytes in case it is an XML error response. if(pCurl->bodydata.size() < GET_OBJECT_RESPONSE_LIMIT){ pCurl->bodydata.append(static_cast<const char*>(ptr), std::min(size * nmemb, GET_OBJECT_RESPONSE_LIMIT - pCurl->bodydata.size())); } // 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; totalwrite < copysize; totalwrite += writebytes){ writebytes = pwrite(pCurl->partdata.fd, &(static_cast<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; } void S3fsCurl::ResetOffset(S3fsCurl* pCurl) { pCurl->partdata.startpos = pCurl->b_partdata_startpos; pCurl->partdata.size = pCurl->b_partdata_size; } 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; } int S3fsCurl::GetRetries() { return S3fsCurl::retries; } bool S3fsCurl::SetPublicBucket(bool flag) { bool old = S3fsCurl::is_public_bucket; S3fsCurl::is_public_bucket = flag; return old; } acl_t S3fsCurl::SetDefaultAcl(acl_t acl) { acl_t old = S3fsCurl::default_acl; S3fsCurl::default_acl = acl; return old; } acl_t S3fsCurl::GetDefaultAcl() { return S3fsCurl::default_acl; } std::string S3fsCurl::SetStorageClass(const std::string& storage_class) { std::string old = S3fsCurl::storage_class; // AWS requires uppercase storage class values S3fsCurl::storage_class = upper(storage_class); return old; } bool S3fsCurl::PushbackSseKeys(const std::string& input) { std::string onekey = trim(input); if(onekey.empty()){ return false; } if('#' == onekey[0]){ return false; } // make base64 if the key is short enough, otherwise assume it is already so std::string base64_key; std::string raw_key; if(onekey.length() > 256 / 8){ std::string p_key(s3fs_decode64(onekey.c_str(), onekey.size())); raw_key = p_key; base64_key = onekey; } else { base64_key = s3fs_base64(reinterpret_cast<const unsigned char*>(onekey.c_str()), onekey.length()); raw_key = onekey; } // make MD5 std::string strMd5; if(!make_md5_from_binary(raw_key.c_str(), raw_key.length(), strMd5)){ S3FS_PRN_ERR("Could not make MD5 from SSE-C keys(%s).", raw_key.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(); std::ifstream ssefs(filepath); if(!ssefs.good()){ S3FS_PRN_ERR("Could not open SSE-C keys file(%s).", filepath); return false; } std::string line; while(getline(ssefs, line)){ S3fsCurl::PushbackSseKeys(line); } if(S3fsCurl::sseckeys.empty()){ 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() { switch(S3fsCurl::ssetype){ case sse_type_t::SSE_DISABLE: S3fsCurl::ssekmsid.clear(); return true; case sse_type_t::SSE_S3: S3fsCurl::ssekmsid.clear(); return true; case sse_type_t::SSE_C: if(S3fsCurl::sseckeys.empty()){ S3FS_PRN_ERR("sse type is SSE-C, but there is no custom key."); return false; } S3fsCurl::ssekmsid.clear(); return true; case sse_type_t::SSE_KMS: if(S3fsCurl::ssekmsid.empty()){ S3FS_PRN_ERR("sse type is SSE-KMS, but there is no specified kms id."); return false; } if(S3fsCurl::GetSignatureType() == signature_type_t::V2_ONLY){ S3FS_PRN_ERR("sse type is SSE-KMS, but signature type is not v4. SSE-KMS require signature v4."); return false; } // SSL/TLS is required for KMS // if(!is_prefix(s3host.c_str(), "https://")){ S3FS_PRN_ERR("The sse type is SSE-KMS, but it is not configured to use SSL/TLS. SSE-KMS requires SSL/TLS communication."); return false; } return true; } S3FS_PRN_ERR("sse type is unknown(%d).", static_cast<int>(S3fsCurl::ssetype)); return false; } bool S3fsCurl::LoadEnvSseCKeys() { char* envkeys = getenv("AWSSSECKEYS"); if(nullptr == envkeys){ // nothing to do return true; } S3fsCurl::sseckeys.clear(); std::istringstream fullkeys(envkeys); std::string onekey; while(getline(fullkeys, onekey, ':')){ S3fsCurl::PushbackSseKeys(onekey); } // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse if(S3fsCurl::sseckeys.empty()){ S3FS_PRN_ERR("There is no SSE Key in environment(AWSSSECKEYS=%s).", envkeys); return false; } return true; } bool S3fsCurl::LoadEnvSseKmsid() { const char* envkmsid = getenv("AWSSSEKMSID"); if(nullptr == envkmsid){ // nothing to do return true; } return S3fsCurl::SetSseKmsid(envkmsid); } // // If md5 is empty, returns first(current) sse key. // bool S3fsCurl::GetSseKey(std::string& md5, std::string& ssekey) { for(auto iter = S3fsCurl::sseckeys.cbegin(); iter != S3fsCurl::sseckeys.cend(); ++iter){ if(md5.empty() || md5 == (*iter).cbegin()->first){ md5 = iter->begin()->first; ssekey = iter->begin()->second; return true; } } return false; } bool S3fsCurl::GetSseKeyMd5(size_t pos, std::string& md5) { if(S3fsCurl::sseckeys.size() <= pos){ return false; } size_t cnt = 0; for(auto iter = S3fsCurl::sseckeys.cbegin(); iter != S3fsCurl::sseckeys.cend(); ++iter, ++cnt){ if(pos == cnt){ md5 = iter->begin()->first; return true; } } return false; } size_t S3fsCurl::GetSseKeyCount() { 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::SetDumpBody(bool flag) { bool old = S3fsCurl::is_dump_body; S3fsCurl::is_dump_body = flag; return old; } 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; } bool S3fsCurl::SetSSLClientCertOptions(const std::string& values) { // Parse values: // <values> = "<SSL Client Cert>:<SSL Cert Type>:<SSL Cert Private Key>:<SSL Cert Private Type>:<Key Password>" // if(values.empty()){ return false; } std::list<std::string> valarr; std::string::size_type start_pos = 0; std::string::size_type pos; do{ if(std::string::npos == (pos = values.find(':', start_pos))){ valarr.push_back(values.substr(start_pos)); start_pos = pos; }else{ if(0 < (pos - start_pos)){ valarr.push_back(values.substr(start_pos, (pos - start_pos))); }else{ valarr.emplace_back(""); } start_pos = ++pos; } }while(std::string::npos != start_pos); // set client cert if(!valarr.empty() && !valarr.front().empty()){ S3fsCurl::client_cert = valarr.front(); valarr.pop_front(); // set client cert type if(!valarr.empty()){ S3fsCurl::client_cert_type = valarr.front(); // allow empty(default: PEM) valarr.pop_front(); // set client private key if(!valarr.empty()){ S3fsCurl::client_priv_key = valarr.front(); // allow empty valarr.pop_front(); // set client private key type if(!valarr.empty()){ S3fsCurl::client_priv_key_type = valarr.front(); // allow empty(default: PEM) valarr.pop_front(); // set key password if(!valarr.empty()){ S3fsCurl::client_key_password = valarr.front(); // allow empty } } } } } // [NOTE] // If the private key is set but the password is not set, // check the environment variables. // if(!S3fsCurl::client_priv_key.empty() && S3fsCurl::client_key_password.empty()){ const char* pass = std::getenv(S3fsCurl::S3FS_SSL_PRIVKEY_PASSWORD); if(pass != nullptr){ S3fsCurl::client_key_password = pass; } } return true; } bool S3fsCurl::SetMultipartSize(off_t size) { size = size * 1024 * 1024; if(size < MIN_MULTIPART_SIZE){ return false; } S3fsCurl::multipart_size = size; return true; } bool S3fsCurl::SetMultipartCopySize(off_t size) { size = size * 1024 * 1024; if(size < MIN_MULTIPART_SIZE){ return false; } S3fsCurl::multipart_copy_size = size; return true; } int S3fsCurl::SetMaxParallelCount(int value) { int old = S3fsCurl::max_parallel_cnt; S3fsCurl::max_parallel_cnt = value; return old; } int S3fsCurl::SetMaxMultiRequest(int max) { int old = S3fsCurl::max_multireq; S3fsCurl::max_multireq = max; return old; } // [NOTE] // This proxy setting is as same as the "--proxy" option of the curl command, // and equivalent to the "CURLOPT_PROXY" option of the curl_easy_setopt() // function. // However, currently s3fs does not provide another option to set the schema // and port, so you need to specify these it in this function. (Other than // this function, there is no means of specifying the schema and port.) // Therefore, it should be specified "url" as "[<schema>://]<fqdn>[:<port>]". // s3fs passes this string to curl_easy_setopt() function with "CURLOPT_PROXY". // If no "schema" is specified, "http" will be used as default, and if no port // is specified, "443" will be used for "HTTPS" and "1080" otherwise. // (See the description of "CURLOPT_PROXY" in libcurl document.) // bool S3fsCurl::SetProxy(const char* url) { if(!url || '\0' == url[0]){ return false; } std::string tmpurl = url; // check schema bool is_http = true; size_t pos = 0; if(std::string::npos != (pos = tmpurl.find("://", pos))){ if(0 == pos){ // no schema string before "://" return false; } pos += strlen("://"); // Check if it is other than "http://" if(0 != tmpurl.find("http://", 0)){ is_http = false; } }else{ // not have schema string pos = 0; } // check fqdn and port number string if(std::string::npos != (pos = tmpurl.find(':', pos))){ // specify port if(0 == pos){ // no fqdn(hostname) string before ":" return false; } pos += strlen(":"); if(std::string::npos != tmpurl.find(':', pos)){ // found wrong separator return false; } } S3fsCurl::proxy_url = tmpurl; S3fsCurl::proxy_http = is_http; return true; } // [NOTE] // This function loads proxy credentials(username and passphrase) // from a file. // The loaded values is set to "CURLOPT_PROXYUSERPWD" in the // curl_easy_setopt() function. (But only used if the proxy is HTTP // schema.) // // The file is expected to contain only one valid line: // ------------------------ // # comment line // <username>:<passphrase> // ------------------------ // Lines starting with a '#' character are treated as comments. // Lines with only space characters and blank lines are ignored. // If the user name contains spaces, it must be url encoded(ex. %20). // bool S3fsCurl::SetProxyUserPwd(const char* file) { if(!file || '\0' == file[0]){ return false; } if(!S3fsCurl::proxy_userpwd.empty()){ S3FS_PRN_WARN("Already set username and passphrase for proxy."); return false; } std::ifstream credFileStream(file); if(!credFileStream.good()){ S3FS_PRN_WARN("Could not load username and passphrase for proxy from %s.", file); return false; } std::string userpwd; std::string line; while(getline(credFileStream, line)){ line = trim(line); if(line.empty()){ continue; } if(line[0]=='#'){ continue; } if(!userpwd.empty()){ S3FS_PRN_WARN("Multiple valid username and passphrase found in %s file. Should specify only one pair.", file); return false; } // check separator for username and passphrase size_t pos = 0; if(std::string::npos == (pos = line.find(':', pos))){ S3FS_PRN_WARN("Found string for username and passphrase in %s file does not have separator ':'.", file); return false; } if(0 == pos || (pos + 1) == line.length()){ S3FS_PRN_WARN("Found string for username or passphrase in %s file is empty.", file); return false; } if(std::string::npos != line.find(':', ++pos)){ S3FS_PRN_WARN("Found string for username and passphrase in %s file has multiple separator ':'.", file); return false; } userpwd = line; } if(userpwd.empty()){ S3FS_PRN_WARN("No valid username and passphrase found in %s.", file); return false; } S3fsCurl::proxy_userpwd = userpwd; return true; } bool S3fsCurl::SetIPResolveType(const char* value) { if(!value){ return false; } if(0 == strcasecmp(value, "ipv4")){ S3fsCurl::ipresolve_type = CURL_IPRESOLVE_V4; }else if(0 == strcasecmp(value, "ipv6")){ S3fsCurl::ipresolve_type = CURL_IPRESOLVE_V6; }else if(0 == strcasecmp(value, "whatever")){ // = default type S3fsCurl::ipresolve_type = CURL_IPRESOLVE_WHATEVER; }else{ return false; } return true; } // cppcheck-suppress unmatchedSuppression // cppcheck-suppress constParameter // cppcheck-suppress constParameterCallback bool S3fsCurl::MultipartUploadPartCallback(S3fsCurl* s3fscurl, void* param) { if(!s3fscurl || param){ // this callback does not need a parameter return false; } return s3fscurl->MultipartUploadPartComplete(); } // cppcheck-suppress unmatchedSuppression // cppcheck-suppress constParameter // cppcheck-suppress constParameterCallback bool S3fsCurl::MixMultipartUploadCallback(S3fsCurl* s3fscurl, void* param) { if(!s3fscurl || param){ // this callback does not need a parameter return false; } return s3fscurl->MixMultipartUploadComplete(); } std::unique_ptr<S3fsCurl> S3fsCurl::MultipartUploadPartRetryCallback(S3fsCurl* s3fscurl) { if(!s3fscurl){ return nullptr; } // parse and get part_num, upload_id. std::string upload_id; std::string part_num_str; int part_num; off_t tmp_part_num = 0; if(!get_keyword_value(s3fscurl->url, "uploadId", upload_id)){ return nullptr; } upload_id = urlDecode(upload_id); // decode if(!get_keyword_value(s3fscurl->url, "partNumber", part_num_str)){ return nullptr; } if(!s3fs_strtoofft(&tmp_part_num, part_num_str.c_str(), /*base=*/ 10)){ return nullptr; } part_num = static_cast<int>(tmp_part_num); 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 nullptr; } // duplicate request std::unique_ptr<S3fsCurl> newcurl(new S3fsCurl(s3fscurl->IsUseAhbe())); newcurl->partdata.petag = s3fscurl->partdata.petag; 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; newcurl->op = s3fscurl->op; newcurl->type = s3fscurl->type; // setup new curl object if(0 != newcurl->MultipartUploadPartSetup(s3fscurl->path.c_str(), part_num, upload_id)){ S3FS_PRN_ERR("Could not duplicate curl object(%s:%d).", s3fscurl->path.c_str(), part_num); return nullptr; } return newcurl; } std::unique_ptr<S3fsCurl> S3fsCurl::CopyMultipartUploadRetryCallback(S3fsCurl* s3fscurl) { if(!s3fscurl){ return nullptr; } // parse and get part_num, upload_id. std::string upload_id; std::string part_num_str; int part_num; off_t tmp_part_num = 0; if(!get_keyword_value(s3fscurl->url, "uploadId", upload_id)){ return nullptr; } upload_id = urlDecode(upload_id); // decode if(!get_keyword_value(s3fscurl->url, "partNumber", part_num_str)){ return nullptr; } if(!s3fs_strtoofft(&tmp_part_num, part_num_str.c_str(), /*base=*/ 10)){ return nullptr; } part_num = static_cast<int>(tmp_part_num); 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 nullptr; } // duplicate request std::unique_ptr<S3fsCurl> newcurl(new S3fsCurl(s3fscurl->IsUseAhbe())); newcurl->partdata.petag = s3fscurl->partdata.petag; newcurl->b_from = s3fscurl->b_from; newcurl->b_meta = s3fscurl->b_meta; newcurl->retry_count = s3fscurl->retry_count + 1; newcurl->op = s3fscurl->op; newcurl->type = s3fscurl->type; // setup new curl object if(0 != newcurl->CopyMultipartUploadSetup(s3fscurl->b_from.c_str(), s3fscurl->path.c_str(), part_num, upload_id, s3fscurl->b_meta)){ S3FS_PRN_ERR("Could not duplicate curl object(%s:%d).", s3fscurl->path.c_str(), part_num); return nullptr; } return newcurl; } std::unique_ptr<S3fsCurl> S3fsCurl::MixMultipartUploadRetryCallback(S3fsCurl* s3fscurl) { if(!s3fscurl){ return nullptr; } if(-1 == s3fscurl->partdata.fd){ return S3fsCurl::CopyMultipartUploadRetryCallback(s3fscurl); }else{ return S3fsCurl::MultipartUploadPartRetryCallback(s3fscurl); } } int S3fsCurl::MapPutErrorResponse(int result) { if(result != 0){ return result; } // PUT returns 200 status code with something error, thus // we need to check body. // // example error body: // <?xml version="1.0" encoding="UTF-8"?> // <Error> // <Code>AccessDenied</Code> // <Message>Access Denied</Message> // <RequestId>E4CA6F6767D6685C</RequestId> // <HostId>BHzLOATeDuvN8Es1wI8IcERq4kl4dc2A9tOB8Yqr39Ys6fl7N4EJ8sjGiVvu6wLP</HostId> // </Error> // const char* pstrbody = bodydata.c_str(); std::string code; if(simple_parse_xml(pstrbody, bodydata.size(), "Code", code)){ S3FS_PRN_ERR("Put request get 200 status response, but it included error body(or nullptr). The request failed during copying the object in S3. Code: %s", code.c_str()); // TODO: parse more specific error from <Code> result = -EIO; } return result; } // [NOTE] // It is a factory method as utility because it requires an S3fsCurl object // initialized for multipart upload from outside this class. // std::unique_ptr<S3fsCurl> S3fsCurl::CreateParallelS3fsCurl(const char* tpath, int fd, off_t start, off_t size, int part_num, bool is_copy, etagpair* petag, const std::string& upload_id, int& result) { // duplicate fd if(!tpath || -1 == fd || start < 0 || size <= 0 || !petag){ S3FS_PRN_ERR("Parameters are wrong: tpath(%s), fd(%d), start(%lld), size(%lld), petag(%s)", SAFESTRPTR(tpath), fd, static_cast<long long int>(start), static_cast<long long int>(size), (petag ? "not null" : "null")); result = -EIO; return nullptr; } result = 0; std::unique_ptr<S3fsCurl> s3fscurl(new S3fsCurl(true)); if(!is_copy){ s3fscurl->partdata.fd = fd; s3fscurl->partdata.startpos = start; s3fscurl->partdata.size = size; s3fscurl->partdata.is_copy = is_copy; s3fscurl->partdata.petag = petag; // [NOTE] be careful, the value is set directly s3fscurl->b_partdata_startpos = s3fscurl->partdata.startpos; s3fscurl->b_partdata_size = s3fscurl->partdata.size; S3FS_PRN_INFO3("Upload Part [tpath=%s][start=%lld][size=%lld][part=%d]", SAFESTRPTR(tpath), static_cast<long long>(start), static_cast<long long>(size), part_num); if(0 != (result = s3fscurl->MultipartUploadPartSetup(tpath, part_num, upload_id))){ S3FS_PRN_ERR("failed uploading part setup(%d)", result); return nullptr; } }else{ headers_t meta; std::string srcresource; std::string srcurl; MakeUrlResource(get_realpath(tpath).c_str(), srcresource, srcurl); meta["x-amz-copy-source"] = srcresource; std::ostringstream strrange; strrange << "bytes=" << start << "-" << (start + size - 1); meta["x-amz-copy-source-range"] = strrange.str(); s3fscurl->b_from = SAFESTRPTR(tpath); s3fscurl->b_meta = meta; s3fscurl->partdata.petag = petag; // [NOTE] be careful, the value is set directly S3FS_PRN_INFO3("Copy Part [tpath=%s][start=%lld][size=%lld][part=%d]", SAFESTRPTR(tpath), static_cast<long long>(start), static_cast<long long>(size), part_num); if(0 != (result = s3fscurl->CopyMultipartUploadSetup(tpath, tpath, part_num, upload_id, meta))){ S3FS_PRN_ERR("failed uploading part setup(%d)", result); return nullptr; } } // Call lazy function if(!s3fscurl->fpLazySetup || !s3fscurl->fpLazySetup(s3fscurl.get())){ S3FS_PRN_ERR("failed lazy function setup for uploading part"); result = -EIO; return nullptr; } return s3fscurl; } int S3fsCurl::ParallelMultipartUploadRequest(const char* tpath, const headers_t& meta, int fd) { int result; std::string upload_id; struct stat st; etaglist_t list; off_t remaining_bytes; S3FS_PRN_INFO3("[tpath=%s][fd=%d]", SAFESTRPTR(tpath), fd); if(-1 == fstat(fd, &st)){ S3FS_PRN_ERR("Invalid file descriptor(errno=%d)", errno); return -errno; } if(0 != (result = pre_multipart_upload_request(std::string(tpath), meta, upload_id))){ return result; } // Initialize S3fsMultiCurl S3fsMultiCurl curlmulti(GetMaxParallelCount()); curlmulti.SetSuccessCallback(S3fsCurl::MultipartUploadPartCallback); curlmulti.SetRetryCallback(S3fsCurl::MultipartUploadPartRetryCallback); // cycle through open fd, pulling off 10MB chunks at a time for(remaining_bytes = st.st_size; 0 < remaining_bytes; ){ off_t chunk = remaining_bytes > S3fsCurl::multipart_size ? S3fsCurl::multipart_size : remaining_bytes; // s3fscurl sub object std::unique_ptr<S3fsCurl> s3fscurl_para(new S3fsCurl(true)); s3fscurl_para->partdata.fd = fd; 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->MultipartUploadPartSetup(tpath, s3fscurl_para->partdata.get_part_number(), upload_id))){ S3FS_PRN_ERR("failed uploading part setup(%d)", result); return result; } // set into parallel object if(!curlmulti.SetS3fsCurlObject(std::move(s3fscurl_para))){ S3FS_PRN_ERR("Could not make curl object into multi curl(%s).", tpath); return -EIO; } remaining_bytes -= chunk; } // Multi request if(0 != (result = curlmulti.Request())){ S3FS_PRN_ERR("error occurred in multi request(errno=%d).", result); int result2; if(0 != (result2 = abort_multipart_upload_request(std::string(tpath), upload_id))){ S3FS_PRN_ERR("error aborting multipart upload(errno=%d).", result2); } return result; } if(0 != (result = complete_multipart_upload_request(std::string(tpath), upload_id, list))){ return result; } return 0; } int S3fsCurl::ParallelMixMultipartUploadRequest(const char* tpath, headers_t& meta, int fd, const fdpage_list_t& mixuppages) { int result; std::string upload_id; struct stat st; etaglist_t list; S3FS_PRN_INFO3("[tpath=%s][fd=%d]", SAFESTRPTR(tpath), fd); if(-1 == fstat(fd, &st)){ S3FS_PRN_ERR("Invalid file descriptor(errno=%d)", errno); return -errno; } if(0 != (result = pre_multipart_upload_request(std::string(tpath), meta, upload_id))){ return result; } // for copy multipart std::string srcresource; std::string srcurl; MakeUrlResource(get_realpath(tpath).c_str(), srcresource, srcurl); meta["Content-Type"] = S3fsCurl::LookupMimeType(tpath); meta["x-amz-copy-source"] = srcresource; // Initialize S3fsMultiCurl S3fsMultiCurl curlmulti(GetMaxParallelCount()); curlmulti.SetSuccessCallback(S3fsCurl::MixMultipartUploadCallback); curlmulti.SetRetryCallback(S3fsCurl::MixMultipartUploadRetryCallback); for(auto iter = mixuppages.cbegin(); iter != mixuppages.cend(); ++iter){ if(iter->modified){ // Multipart upload std::unique_ptr<S3fsCurl> s3fscurl_para(new S3fsCurl(true)); s3fscurl_para->partdata.fd = fd; s3fscurl_para->partdata.startpos = iter->offset; s3fscurl_para->partdata.size = iter->bytes; 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); S3FS_PRN_INFO3("Upload Part [tpath=%s][start=%lld][size=%lld][part=%d]", SAFESTRPTR(tpath), static_cast<long long>(iter->offset), static_cast<long long>(iter->bytes), s3fscurl_para->partdata.get_part_number()); // initiate upload part for parallel if(0 != (result = s3fscurl_para->MultipartUploadPartSetup(tpath, s3fscurl_para->partdata.get_part_number(), upload_id))){ S3FS_PRN_ERR("failed uploading part setup(%d)", result); return result; } // set into parallel object if(!curlmulti.SetS3fsCurlObject(std::move(s3fscurl_para))){ S3FS_PRN_ERR("Could not make curl object into multi curl(%s).", tpath); return -EIO; } }else{ // Multipart copy for(off_t i = 0, bytes = 0; i < iter->bytes; i += bytes){ std::unique_ptr<S3fsCurl> s3fscurl_para(new S3fsCurl(true)); bytes = std::min(GetMultipartCopySize(), iter->bytes - i); /* every part should be larger than MIN_MULTIPART_SIZE and smaller than FIVE_GB */ off_t remain_bytes = iter->bytes - i - bytes; if ((MIN_MULTIPART_SIZE > remain_bytes) && (0 < remain_bytes)){ if(FIVE_GB < (bytes + remain_bytes)){ bytes = (bytes + remain_bytes)/2; } else{ bytes += remain_bytes; } } std::ostringstream strrange; strrange << "bytes=" << (iter->offset + i) << "-" << (iter->offset + i + bytes - 1); meta["x-amz-copy-source-range"] = strrange.str(); s3fscurl_para->b_from = SAFESTRPTR(tpath); s3fscurl_para->b_meta = meta; s3fscurl_para->partdata.add_etag_list(list); S3FS_PRN_INFO3("Copy Part [tpath=%s][start=%lld][size=%lld][part=%d]", SAFESTRPTR(tpath), static_cast<long long>(iter->offset + i), static_cast<long long>(bytes), s3fscurl_para->partdata.get_part_number()); // initiate upload part for parallel if(0 != (result = s3fscurl_para->CopyMultipartUploadSetup(tpath, tpath, s3fscurl_para->partdata.get_part_number(), upload_id, meta))){ S3FS_PRN_ERR("failed uploading part setup(%d)", result); return result; } // set into parallel object if(!curlmulti.SetS3fsCurlObject(std::move(s3fscurl_para))){ S3FS_PRN_ERR("Could not make curl object into multi curl(%s).", tpath); return -EIO; } } } } // Multi request if(0 != (result = curlmulti.Request())){ S3FS_PRN_ERR("error occurred in multi request(errno=%d).", result); int result2; if(0 != (result2 = abort_multipart_upload_request(std::string(tpath), upload_id))){ S3FS_PRN_ERR("error aborting multipart upload(errno=%d).", result2); } return result; } if(0 != (result = complete_multipart_upload_request(std::string(tpath), upload_id, list))){ return result; } return 0; } std::unique_ptr<S3fsCurl> S3fsCurl::ParallelGetObjectRetryCallback(S3fsCurl* s3fscurl) { int result; if(!s3fscurl){ return nullptr; } if(s3fscurl->retry_count >= S3fsCurl::retries){ S3FS_PRN_ERR("Over retry count(%d) limit(%s).", s3fscurl->retry_count, s3fscurl->path.c_str()); return nullptr; } // duplicate request(setup new curl object) std::unique_ptr<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); return nullptr; } newcurl->retry_count = s3fscurl->retry_count + 1; return newcurl; } int S3fsCurl::ParallelGetObjectRequest(const char* tpath, int fd, off_t start, off_t size) { S3FS_PRN_INFO3("[tpath=%s][fd=%d]", SAFESTRPTR(tpath), fd); sse_type_t ssetype = sse_type_t::SSE_DISABLE; std::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; off_t remaining_bytes; // cycle through open fd, pulling off 10MB chunks at a time for(remaining_bytes = size; 0 < remaining_bytes; ){ S3fsMultiCurl curlmulti(GetMaxParallelCount()); int para_cnt; off_t chunk; // Initialize S3fsMultiCurl //curlmulti.SetSuccessCallback(nullptr); // 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 std::unique_ptr<S3fsCurl> s3fscurl_para(new S3fsCurl(true)); if(0 != (result = s3fscurl_para->PreGetObjectRequest(tpath, fd, (start + size - remaining_bytes), chunk, ssetype, ssevalue))){ S3FS_PRN_ERR("failed downloading part setup(%d)", result); return result; } // set into parallel object if(!curlmulti.SetS3fsCurlObject(std::move(s3fscurl_para))){ S3FS_PRN_ERR("Could not make curl object into multi curl(%s).", tpath); return -EIO; } } // Multi request if(0 != (result = curlmulti.Request())){ S3FS_PRN_ERR("error occurred in multi request(errno=%d).", result); break; } // reinit for loop. curlmulti.Clear(); } return result; } bool S3fsCurl::MultipartUploadPartSetCurlOpts(S3fsCurl* s3fscurl) { if(!s3fscurl){ return false; } if(!s3fscurl->CreateCurlHandle()){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_URL, s3fscurl->url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_UPLOAD, true)){ // HTTP PUT return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&s3fscurl->bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_HEADERDATA, reinterpret_cast<void*>(&s3fscurl->responseHeaders))){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_HEADERFUNCTION, HeaderCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_INFILESIZE_LARGE, static_cast<curl_off_t>(s3fscurl->partdata.size))){ // Content-Length return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_READFUNCTION, UploadReadCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_READDATA, reinterpret_cast<void*>(s3fscurl))){ return false; } if(!S3fsCurl::AddUserAgent(s3fscurl->hCurl)){ // put User-Agent return false; } return true; } bool S3fsCurl::CopyMultipartUploadSetCurlOpts(S3fsCurl* s3fscurl) { if(!s3fscurl){ return false; } if(!s3fscurl->CreateCurlHandle()){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_URL, s3fscurl->url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_UPLOAD, true)){ // HTTP PUT return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&s3fscurl->bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_HEADERDATA, reinterpret_cast<void*>(&s3fscurl->headdata))){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_HEADERFUNCTION, WriteMemoryCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_INFILESIZE, 0)){ // Content-Length return false; } if(!S3fsCurl::AddUserAgent(s3fscurl->hCurl)){ // put User-Agent return false; } return true; } bool S3fsCurl::PreGetObjectRequestSetCurlOpts(S3fsCurl* s3fscurl) { if(!s3fscurl){ return false; } if(!s3fscurl->CreateCurlHandle()){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_URL, s3fscurl->url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_WRITEFUNCTION, DownloadWriteCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(s3fscurl))){ return false; } if(!S3fsCurl::AddUserAgent(s3fscurl->hCurl)){ // put User-Agent return false; } return true; } bool S3fsCurl::PreHeadRequestSetCurlOpts(S3fsCurl* s3fscurl) { if(!s3fscurl){ return false; } if(!s3fscurl->CreateCurlHandle()){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_URL, s3fscurl->url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_NOBODY, true)){ // HEAD return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_FILETIME, true)){ // Last-Modified return false; } // responseHeaders if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_HEADERDATA, reinterpret_cast<void*>(&s3fscurl->responseHeaders))){ return false; } if(CURLE_OK != curl_easy_setopt(s3fscurl->hCurl, CURLOPT_HEADERFUNCTION, HeaderCallback)){ return false; } if(!S3fsCurl::AddUserAgent(s3fscurl->hCurl)){ // put User-Agent return false; } return true; } bool S3fsCurl::AddUserAgent(const CurlUniquePtr& hCurl) { if(!hCurl){ return false; } if(S3fsCurl::IsUserAgentFlag()){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_USERAGENT, S3fsCurl::userAgent.c_str())){ return false; } } return true; } int S3fsCurl::CurlDebugFunc(const CURL* hcurl, curl_infotype type, char* data, size_t size, void* userptr) { return S3fsCurl::RawCurlDebugFunc(hcurl, type, data, size, userptr, CURLINFO_END); } int S3fsCurl::CurlDebugBodyInFunc(const CURL* hcurl, curl_infotype type, char* data, size_t size, void* userptr) { return S3fsCurl::RawCurlDebugFunc(hcurl, type, data, size, userptr, CURLINFO_DATA_IN); } int S3fsCurl::CurlDebugBodyOutFunc(const CURL* hcurl, curl_infotype type, char* data, size_t size, void* userptr) { return S3fsCurl::RawCurlDebugFunc(hcurl, type, data, size, userptr, CURLINFO_DATA_OUT); } int S3fsCurl::RawCurlDebugFunc(const CURL* hcurl, curl_infotype type, char* data, size_t size, void* userptr, curl_infotype datatype) { if(!hcurl){ // something wrong... return 0; } switch(type){ case CURLINFO_TEXT: // Swap tab indentation with spaces so it stays pretty in syslog int indent; indent = 0; while (*data == '\t' && size > 0) { indent += 4; size--; data++; } if(foreground && 0 < size && '\n' == data[size - 1]){ size--; } S3FS_PRN_CURL("* %*s%.*s", indent, "", (int)size, data); break; case CURLINFO_DATA_IN: case CURLINFO_DATA_OUT: if(type != datatype || !S3fsCurl::is_dump_body){ // not put break; } case CURLINFO_HEADER_IN: case CURLINFO_HEADER_OUT: size_t remaining; char* p; // Print each line individually for tidy output remaining = size; p = data; do { char* eol = reinterpret_cast<char*>(memchr(p, '\n', remaining)); int newline = 0; if (eol == nullptr) { eol = reinterpret_cast<char*>(memchr(p, '\r', remaining)); if (eol == nullptr) { // No newlines, just emit entire line. eol = p + remaining; } } else { if (eol > p && *(eol - 1) == '\r') { newline++; } newline++; eol++; } size_t length = eol - p; S3FS_PRN_CURL("%s %.*s", getCurlDebugHead(type), (int)length - newline, p); remaining -= length; p = eol; } while (p != nullptr && remaining > 0); break; 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) : type(REQTYPE::UNSET), requestHeaders(nullptr), LastResponseCode(S3FSCURL_RESPONSECODE_NOTSET), postdata(nullptr), postdata_remaining(0), is_use_ahbe(ahbe), retry_count(0), b_postdata(nullptr), b_postdata_remaining(0), b_partdata_startpos(0), b_partdata_size(0), b_ssekey_pos(-1), b_ssetype(sse_type_t::SSE_DISABLE), sem(nullptr), completed_tids_lock(nullptr), completed_tids(nullptr), fpLazySetup(nullptr), curlCode(CURLE_OK) { if(!S3fsCurl::ps3fscred){ S3FS_PRN_CRIT("The object of S3fs Credential class is not initialized."); abort(); } } S3fsCurl::~S3fsCurl() { DestroyCurlHandle(); } bool S3fsCurl::ResetHandle() { bool run_once = curl_warnings_once.exchange(true); curl_easy_reset(hCurl.get()); if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_NOSIGNAL, 1)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_FOLLOWLOCATION, true)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_CONNECTTIMEOUT, S3fsCurl::connect_timeout)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_NOPROGRESS, 0)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, S3FS_CURLOPT_XFERINFOFUNCTION, S3fsCurl::CurlProgress)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_PROGRESSDATA, hCurl.get())){ return false; } // curl_easy_setopt(hCurl, CURLOPT_FORBID_REUSE, 1); if(CURLE_OK != curl_easy_setopt(hCurl, S3FS_CURLOPT_TCP_KEEPALIVE, 1) && !run_once){ S3FS_PRN_WARN("The CURLOPT_TCP_KEEPALIVE option could not be set. For maximize performance you need to enable this option and you should use libcurl 7.25.0 or later."); } if(CURLE_OK != curl_easy_setopt(hCurl, S3FS_CURLOPT_SSL_ENABLE_ALPN, 0) && !run_once){ S3FS_PRN_WARN("The CURLOPT_SSL_ENABLE_ALPN option could not be unset. S3 server does not support ALPN, then this option should be disabled to maximize performance. you need to use libcurl 7.36.0 or later."); } if(CURLE_OK != curl_easy_setopt(hCurl, S3FS_CURLOPT_KEEP_SENDING_ON_ERROR, 1) && !run_once){ S3FS_PRN_WARN("The S3FS_CURLOPT_KEEP_SENDING_ON_ERROR option could not be set. For maximize performance you need to enable this option and you should use libcurl 7.51.0 or later."); } if(CURL_IPRESOLVE_WHATEVER != S3fsCurl::ipresolve_type){ // CURL_IPRESOLVE_WHATEVER is default, so not need to set. if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_IPRESOLVE, S3fsCurl::ipresolve_type)){ return false; } } if(type != REQTYPE::IAMCRED && type != REQTYPE::IAMROLE){ // REQTYPE::IAMCRED and REQTYPE::IAMROLE are always HTTP if(0 == S3fsCurl::ssl_verify_hostname){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_SSL_VERIFYHOST, 0)){ return false; } } if(!S3fsCurl::curl_ca_bundle.empty()){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_CAINFO, S3fsCurl::curl_ca_bundle.c_str())){ return false; } } } // SSL Client Cert if(!S3fsCurl::client_cert.empty()){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_SSLCERT, S3fsCurl::client_cert.c_str())){ return false; } if(!S3fsCurl::client_cert_type.empty() && 0 != strcasecmp(S3fsCurl::client_cert_type.c_str(), "PEM")){ // "PEM" is default if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_SSLCERTTYPE, S3fsCurl::client_cert_type.c_str())){ return false; } } // Private key if(!S3fsCurl::client_priv_key.empty()){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_SSLKEY, S3fsCurl::client_priv_key.c_str())){ return false; } if(!S3fsCurl::client_priv_key_type.empty() && 0 != strcasecmp(S3fsCurl::client_priv_key_type.c_str(), "PEM")){ // "PEM" is default if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_SSLKEYTYPE, S3fsCurl::client_priv_key_type.c_str())){ return false; } } // Password if(!S3fsCurl::client_key_password.empty()){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_KEYPASSWD, S3fsCurl::client_key_password.c_str())){ return false; } } } } if((S3fsCurl::is_dns_cache || S3fsCurl::is_ssl_session_cache) && S3fsCurl::hCurlShare){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_SHARE, S3fsCurl::hCurlShare)){ return false; } } 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."); if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_SSL_VERIFYPEER, false)){ return false; } } if(S3fsCurl::is_verbose){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_VERBOSE, true)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_DEBUGFUNCTION, S3fsCurl::CurlDebugFunc)){ return false; } } if(!cipher_suites.empty()) { if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_SSL_CIPHER_LIST, cipher_suites.c_str())){ return false; } } if(!S3fsCurl::proxy_url.empty()){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_PROXY, S3fsCurl::proxy_url.c_str())){ return false; } if(S3fsCurl::proxy_http){ if(!S3fsCurl::proxy_userpwd.empty()){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_PROXYUSERPWD, S3fsCurl::proxy_userpwd.c_str())){ return false; } } }else if(!S3fsCurl::proxy_userpwd.empty()){ S3FS_PRN_DBG("Username and passphrase are specified even though proxy is not 'http' scheme, so skip to set those."); } } S3fsCurl::curl_progress[hCurl.get()] = {time(nullptr), -1, -1}; return true; } bool S3fsCurl::CreateCurlHandle(bool remake) { const std::lock_guard<std::mutex> lock(S3fsCurl::curl_handles_lock); if(hCurl && remake){ if(!DestroyCurlHandleHasLock(true)){ S3FS_PRN_ERR("could not destroy handle."); return false; } S3FS_PRN_INFO3("already has handle, so destroyed it or restored it to pool."); } if(!hCurl){ hCurl.reset(curl_easy_init()); if(!hCurl){ S3FS_PRN_ERR("Failed to create handle."); return false; } } ResetHandle(); return true; } bool S3fsCurl::DestroyCurlHandle(bool clear_internal_data) { const std::lock_guard<std::mutex> lock(S3fsCurl::curl_handles_lock); return DestroyCurlHandleHasLock(clear_internal_data); } bool S3fsCurl::DestroyCurlHandleHasLock(bool clear_internal_data) { // [NOTE] // If type is REQTYPE::IAMCRED or REQTYPE::IAMROLE, do not clear type. // Because that type only uses HTTP protocol, then the special // logic in ResetHandle function. // if(type != REQTYPE::IAMCRED && type != REQTYPE::IAMROLE){ type = REQTYPE::UNSET; } if(clear_internal_data){ ClearInternalData(); } if(hCurl){ S3fsCurl::curl_progress.erase(hCurl.get()); hCurl.reset(); }else{ return false; } return true; } bool S3fsCurl::ClearInternalData() { // Always clear internal data // type = REQTYPE::UNSET; path = ""; url = ""; op = ""; query_string= ""; if(requestHeaders){ curl_slist_free_all(requestHeaders); requestHeaders = nullptr; } responseHeaders.clear(); bodydata.clear(); headdata.clear(); postdata = nullptr; postdata_remaining = 0; retry_count = 0; b_infile.reset(); b_postdata = nullptr; b_postdata_remaining = 0; b_partdata_startpos = 0; b_partdata_size = 0; partdata.clear(); fpLazySetup = nullptr; 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, bool from_curl_handle) const { responseCode = -1; if(!from_curl_handle){ responseCode = LastResponseCode; }else{ if(!hCurl){ return false; } 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() { S3FS_PRN_INFO3("Retry request. [type=%d][url=%s][path=%s]", static_cast<int>(type), url.c_str(), path.c_str()); if(REQTYPE::UNSET == type){ return false; } // rewind file struct stat st; if(b_infile){ if(-1 == fseek(b_infile.get(), 0, SEEK_SET)){ S3FS_PRN_WARN("Could not reset position(fd=%d)", fileno(b_infile.get())); return false; } if(-1 == fstat(fileno(b_infile.get()), &st)){ S3FS_PRN_WARN("Could not get file stat(fd=%d)", fileno(b_infile.get())); return false; } } // reinitialize internal data requestHeaders = curl_slist_remove(requestHeaders, "Authorization"); responseHeaders.clear(); bodydata.clear(); headdata.clear(); LastResponseCode = S3FSCURL_RESPONSECODE_NOTSET; // 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 { const std::lock_guard<std::mutex> lock(S3fsCurl::curl_handles_lock); ResetHandle(); } // set options switch(type){ case REQTYPE::DELETE: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_CUSTOMREQUEST, "DELETE")){ return false; } break; case REQTYPE::HEAD: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_NOBODY, true)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_FILETIME, true)){ return false; } // responseHeaders if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_HEADERDATA, reinterpret_cast<void*>(&responseHeaders))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_HEADERFUNCTION, HeaderCallback)){ return false; } break; case REQTYPE::PUTHEAD: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_INFILESIZE, 0)){ return false; } break; case REQTYPE::PUT: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } if(b_infile){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_INFILESIZE_LARGE, static_cast<curl_off_t>(st.st_size))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_INFILE, b_infile.get())){ return false; } }else{ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_INFILESIZE, 0)){ return false; } } break; case REQTYPE::GET: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, S3fsCurl::DownloadWriteCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(this))){ return false; } break; case REQTYPE::CHKBUCKET: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } break; case REQTYPE::LISTBUCKET: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } break; case REQTYPE::PREMULTIPOST: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_POST, true)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_POSTFIELDSIZE, 0)){ return false; } break; case REQTYPE::COMPLETEMULTIPOST: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_POST, true)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_POSTFIELDSIZE, static_cast<curl_off_t>(postdata_remaining))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_READDATA, reinterpret_cast<void*>(this))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_READFUNCTION, S3fsCurl::ReadCallback)){ return false; } break; case REQTYPE::UPLOADMULTIPOST: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_HEADERDATA, reinterpret_cast<void*>(&responseHeaders))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_HEADERFUNCTION, HeaderCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_INFILESIZE_LARGE, static_cast<curl_off_t>(partdata.size))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_READFUNCTION, S3fsCurl::UploadReadCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_READDATA, reinterpret_cast<void*>(this))){ return false; } break; case REQTYPE::COPYMULTIPOST: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_HEADERDATA, reinterpret_cast<void*>(&headdata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_HEADERFUNCTION, WriteMemoryCallback)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_INFILESIZE, 0)){ return false; } break; case REQTYPE::MULTILIST: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } break; case REQTYPE::IAMCRED: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } if(S3fsCurl::ps3fscred->IsIBMIAMAuth()){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_POST, true)){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_POSTFIELDSIZE, static_cast<curl_off_t>(postdata_remaining))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_READDATA, reinterpret_cast<void*>(this))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_READFUNCTION, S3fsCurl::ReadCallback)){ return false; } } break; case REQTYPE::ABORTMULTIUPLOAD: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_CUSTOMREQUEST, "DELETE")){ return false; } break; case REQTYPE::IAMROLE: if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } break; default: S3FS_PRN_ERR("request type is unknown(%d)", static_cast<int>(type)); return false; } if(!S3fsCurl::AddUserAgent(hCurl)){ // put User-Agent return false; } return true; } // // returns curl return code // int S3fsCurl::RequestPerform(bool dontAddAuthHeaders /*=false*/) { if(S3fsLog::IsS3fsLogDbg()){ char* ptr_url = nullptr; curl_easy_getinfo(hCurl, CURLINFO_EFFECTIVE_URL, &ptr_url); S3FS_PRN_DBG("connecting to URL %s", SAFESTRPTR(ptr_url)); } LastResponseCode = S3FSCURL_RESPONSECODE_NOTSET; long responseCode = S3FSCURL_RESPONSECODE_NOTSET; int result = S3FSCURL_PERFORM_RESULT_NOTSET; // 1 attempt + retries... for(int retrycnt = 0; S3FSCURL_PERFORM_RESULT_NOTSET == result && retrycnt < S3fsCurl::retries; ++retrycnt){ // Reset response code responseCode = S3FSCURL_RESPONSECODE_NOTSET; // Insert headers if(!dontAddAuthHeaders) { if(!insertAuthHeaders()){ return -EIO; } } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_HTTPHEADER, requestHeaders)){ S3FS_PRN_ERR("Failed to call curl_easy_setopt, returned NOT CURLE_OK."); return -EIO; } // Requests curlCode = curl_easy_perform(hCurl.get()); // Check result switch(curlCode){ case CURLE_OK: // Need to look at the HTTP response code if(0 != curl_easy_getinfo(hCurl, CURLINFO_RESPONSE_CODE, &responseCode)){ S3FS_PRN_ERR("curl_easy_getinfo failed while trying to retrieve HTTP response code"); responseCode = S3FSCURL_RESPONSECODE_FATAL_ERROR; result = -EIO; break; } if(responseCode >= 200 && responseCode < 300){ S3FS_PRN_INFO3("HTTP response code %ld", responseCode); result = 0; break; } { // Try to parse more specific AWS error code otherwise fall back to HTTP error code. std::string value; if(simple_parse_xml(bodydata.c_str(), bodydata.size(), "Code", value)){ // TODO: other error codes if(value == "EntityTooLarge"){ result = -EFBIG; break; }else if(value == "InvalidObjectState"){ result = -EREMOTE; break; }else if(value == "KeyTooLongError"){ result = -ENAMETOOLONG; break; } } } // Service response codes which are >= 300 && < 500 switch(responseCode){ case 301: case 307: S3FS_PRN_ERR("HTTP response code 301(Moved Permanently: also happens when bucket's region is incorrect), returning EIO. Body Text: %s", bodydata.c_str()); S3FS_PRN_ERR("The options of url and endpoint may be useful for solving, please try to use both options."); result = -EIO; break; case 400: if(op == "HEAD"){ if(path.size() > 1024){ S3FS_PRN_ERR("HEAD HTTP response code %ld with path longer than 1024, returning ENAMETOOLONG.", responseCode); return -ENAMETOOLONG; } S3FS_PRN_ERR("HEAD HTTP response code %ld, returning EPERM.", responseCode); result = -EPERM; }else{ S3FS_PRN_ERR("HTTP response code %ld, returning EIO. Body Text: %s", responseCode, bodydata.c_str()); result = -EIO; } break; case 403: S3FS_PRN_ERR("HTTP response code %ld, returning EPERM. Body Text: %s", responseCode, bodydata.c_str()); result = -EPERM; break; case 404: S3FS_PRN_INFO3("HTTP response code 404 was returned, returning ENOENT"); S3FS_PRN_DBG("Body Text: %s", bodydata.c_str()); result = -ENOENT; break; case 416: S3FS_PRN_INFO3("HTTP response code 416 was returned, returning EIO"); result = -EIO; break; case 501: S3FS_PRN_INFO3("HTTP response code 501 was returned, returning ENOTSUP"); S3FS_PRN_DBG("Body Text: %s", bodydata.c_str()); result = -ENOTSUP; break; case 429: case 500: case 503: { S3FS_PRN_INFO3("HTTP response code %ld was returned, slowing down", responseCode); S3FS_PRN_DBG("Body Text: %s", bodydata.c_str()); // Add jitter to avoid thundering herd. unsigned int sleep_time = 2 << retry_count; sleep(sleep_time + static_cast<unsigned int>(random()) % sleep_time); break; } default: S3FS_PRN_ERR("HTTP response code %ld, returning EIO. Body Text: %s", responseCode, bodydata.c_str()); result = -EIO; break; } 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); { const std::lock_guard<std::mutex> lock(S3fsCurl::curl_handles_lock); S3fsCurl::curl_progress[hCurl.get()] = {time(nullptr), -1, -1}; } 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(S3fsCurl::curl_ca_bundle.empty()){ if(!S3fsCurl::LocateBundle()){ S3FS_PRN_ERR("could not get CURL_CA_BUNDLE."); result = -EIO; } // retry with CAINFO }else{ S3FS_PRN_ERR("curlCode: %d msg: %s", curlCode, curl_easy_strerror(curlCode)); result = -EIO; } break; #ifdef CURLE_PEER_FAILED_VERIFICATION case CURLE_PEER_FAILED_VERIFICATION: S3FS_PRN_ERR("### CURLE_PEER_FAILED_VERIFICATION"); first_pos = S3fsCred::GetBucket().find_first_of('.'); if(first_pos != std::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)); } result = -EIO; 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, &responseCode)){ result = -EIO; }else{ S3FS_PRN_INFO3("HTTP response code =%ld", responseCode); // Let's try to retrieve the if(404 == responseCode){ result = -ENOENT; }else if(500 > responseCode){ result = -EIO; } } break; // Unknown CURL return code default: S3FS_PRN_ERR("###curlCode: %d msg: %s", curlCode, curl_easy_strerror(curlCode)); result = -EIO; break; } // switch if(S3FSCURL_PERFORM_RESULT_NOTSET == result){ S3FS_PRN_INFO("### retrying..."); if(!RemakeHandle()){ S3FS_PRN_INFO("Failed to reset handle and internal data for retrying."); result = -EIO; break; } } } // for // set last response code if(S3FSCURL_RESPONSECODE_NOTSET == responseCode){ LastResponseCode = S3FSCURL_RESPONSECODE_FATAL_ERROR; }else{ LastResponseCode = responseCode; } if(S3FSCURL_PERFORM_RESULT_NOTSET == result){ S3FS_PRN_ERR("### giving up"); result = -EIO; } return result; } // // 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" // std::string S3fsCurl::CalcSignatureV2(const std::string& method, const std::string& strMD5, const std::string& content_type, const std::string& date, const std::string& resource, const std::string& secret_access_key, const std::string& access_token) { std::string Signature; std::string StringToSign; if(!access_token.empty()){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-security-token", access_token.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 = secret_access_key.data(); size_t key_len = secret_access_key.size(); const auto* sdata = reinterpret_cast<const unsigned char*>(StringToSign.data()); size_t sdata_len = StringToSign.size(); unsigned int md_len = 0; std::unique_ptr<unsigned char[]> md = s3fs_HMAC(key, key_len, sdata, sdata_len, &md_len); Signature = s3fs_base64(md.get(), md_len); return Signature; } std::string S3fsCurl::CalcSignature(const std::string& method, const std::string& canonical_uri, const std::string& query_string, const std::string& strdate, const std::string& payload_hash, const std::string& date8601, const std::string& secret_access_key, const std::string& access_token) { std::string StringCQ, StringToSign; std::string uriencode; if(!access_token.empty()){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-security-token", access_token.c_str()); } uriencode = urlEncodePath(canonical_uri); StringCQ = method + "\n"; if(method == "HEAD" || method == "PUT" || method == "DELETE"){ StringCQ += uriencode + "\n"; }else if(method == "GET" && uriencode.empty()){ StringCQ +="/\n"; }else if(method == "GET" && is_prefix(uriencode.c_str(), "/")){ StringCQ += uriencode +"\n"; }else if(method == "GET" && !is_prefix(uriencode.c_str(), "/")){ StringCQ += "/\n" + urlEncodeQuery(canonical_uri) +"\n"; }else if(method == "POST"){ StringCQ += uriencode + "\n"; } StringCQ += urlEncodeQuery(query_string) + "\n"; StringCQ += get_canonical_headers(requestHeaders) + "\n"; StringCQ += get_sorted_header_keys(requestHeaders) + "\n"; StringCQ += payload_hash; std::string kSecret = "AWS4" + secret_access_key; unsigned int kDate_len,kRegion_len, kService_len, kSigning_len = 0; std::unique_ptr<unsigned char[]> kDate = s3fs_HMAC256(kSecret.c_str(), kSecret.size(), reinterpret_cast<const unsigned char*>(strdate.data()), strdate.size(), &kDate_len); std::unique_ptr<unsigned char[]> kRegion = s3fs_HMAC256(kDate.get(), kDate_len, reinterpret_cast<const unsigned char*>(endpoint.c_str()), endpoint.size(), &kRegion_len); std::unique_ptr<unsigned char[]> kService = s3fs_HMAC256(kRegion.get(), kRegion_len, reinterpret_cast<const unsigned char*>("s3"), sizeof("s3") - 1, &kService_len); std::unique_ptr<unsigned char[]> kSigning = s3fs_HMAC256(kService.get(), kService_len, reinterpret_cast<const unsigned char*>("aws4_request"), sizeof("aws4_request") - 1, &kSigning_len); const auto* cRequest = reinterpret_cast<const unsigned char*>(StringCQ.c_str()); size_t cRequest_len = StringCQ.size(); sha256_t sRequest; s3fs_sha256(cRequest, cRequest_len, &sRequest); StringToSign = "AWS4-HMAC-SHA256\n"; StringToSign += date8601 + "\n"; StringToSign += strdate + "/" + endpoint + "/s3/aws4_request\n"; StringToSign += s3fs_hex_lower(sRequest.data(), sRequest.size()); const auto* cscope = reinterpret_cast<const unsigned char*>(StringToSign.c_str()); size_t cscope_len = StringToSign.size(); unsigned int md_len = 0; std::unique_ptr<unsigned char[]> md = s3fs_HMAC256(kSigning.get(), kSigning_len, cscope, cscope_len, &md_len); return s3fs_hex_lower(md.get(), md_len); } std::string S3fsCurl::extractURI(const std::string& url) { // If the URL is empty, return "/" if (url.empty()) { return "/"; } // Find the position of "://" std::size_t protocol_pos = url.find("://"); if (protocol_pos == std::string::npos) { // If "://" is not found, return "/" return "/"; } // Find the position of the first "/" after "://" std::size_t uri_pos = url.find('/', protocol_pos + 3); if (uri_pos == std::string::npos) { // If no "/" is found after the domain, return "/" return "/"; } // Extract the URI std::string uri = url.substr(uri_pos); // Ensure the URI ends with "/" if (uri.back() != '/') { uri += '/'; } return uri; } bool S3fsCurl::insertV4Headers(const std::string& access_key_id, const std::string& secret_access_key, const std::string& access_token) { std::string server_path = type == REQTYPE::LISTBUCKET ? "/" : path; std::string payload_hash; switch (type) { case REQTYPE::PUT: if(GetUnsignedPayload()){ payload_hash = "UNSIGNED-PAYLOAD"; }else{ payload_hash = s3fs_sha256_hex_fd(b_infile == nullptr ? -1 : fileno(b_infile.get()), 0, -1); } break; case REQTYPE::COMPLETEMULTIPOST: { size_t cRequest_len = strlen(reinterpret_cast<const char *>(b_postdata)); sha256_t sRequest; s3fs_sha256(b_postdata, cRequest_len, &sRequest); payload_hash = s3fs_hex_lower(sRequest.data(), sRequest.size()); break; } case REQTYPE::UPLOADMULTIPOST: if(GetUnsignedPayload()){ payload_hash = "UNSIGNED-PAYLOAD"; }else{ payload_hash = s3fs_sha256_hex_fd(partdata.fd, partdata.startpos, partdata.size); } break; default: break; } if(b_infile != nullptr && payload_hash.empty()){ S3FS_PRN_ERR("Failed to make SHA256."); return false; } S3FS_PRN_INFO3("computing signature [%s] [%s] [%s] [%s]", op.c_str(), server_path.c_str(), query_string.c_str(), payload_hash.c_str()); std::string strdate; std::string date8601; get_date_sigv3(strdate, date8601); std::string contentSHA256 = payload_hash.empty() ? EMPTY_PAYLOAD_HASH : payload_hash; const std::string realpath = pathrequeststyle ? S3fsCurl::extractURI(s3host) + S3fsCred::GetBucket() + server_path : server_path; //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::IsRequesterPays()) { requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-request-payer", "requester"); } if(!S3fsCurl::IsPublicBucket()){ std::string Signature = CalcSignature(op, realpath, query_string + (type == REQTYPE::PREMULTIPOST || type == REQTYPE::MULTILIST ? "=" : ""), strdate, contentSHA256, date8601, secret_access_key, access_token); std::string auth = "AWS4-HMAC-SHA256 Credential=" + access_key_id + "/" + strdate + "/" + endpoint + "/s3/aws4_request, SignedHeaders=" + get_sorted_header_keys(requestHeaders) + ", Signature=" + Signature; requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", auth.c_str()); } return true; } void S3fsCurl::insertV2Headers(const std::string& access_key_id, const std::string& secret_access_key, const std::string& access_token) { std::string resource; std::string turl; std::string server_path = type == REQTYPE::LISTBUCKET ? "/" : path; MakeUrlResource(server_path.c_str(), resource, turl); if(!query_string.empty() && type != REQTYPE::CHKBUCKET && type != REQTYPE::LISTBUCKET){ resource += "?" + query_string; } std::string date = get_date_rfc850(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Date", date.c_str()); if(op != "PUT" && op != "POST"){ requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", nullptr); } if(!S3fsCurl::IsPublicBucket()){ std::string Signature = CalcSignatureV2(op, get_header_value(requestHeaders, "Content-MD5"), get_header_value(requestHeaders, "Content-Type"), date, resource, secret_access_key, access_token); requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", ("AWS " + access_key_id + ":" + Signature).c_str()); } } void S3fsCurl::insertIBMIAMHeaders(const std::string& access_key_id, const std::string& access_token) { requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", ("Bearer " + access_token).c_str()); if(op == "PUT" && path == mount_prefix + "/"){ // ibm-service-instance-id header is required for bucket creation requests requestHeaders = curl_slist_sort_insert(requestHeaders, "ibm-service-instance-id", access_key_id.c_str()); } } bool S3fsCurl::insertAuthHeaders() { std::string access_key_id; std::string secret_access_key; std::string access_token; // check and get credential variables if(!S3fsCurl::ps3fscred->CheckIAMCredentialUpdate(&access_key_id, &secret_access_key, &access_token)){ S3FS_PRN_ERR("An error occurred in checking IAM credential."); return false; // do not insert auth headers on error } if(S3fsCurl::ps3fscred->IsIBMIAMAuth()){ insertIBMIAMHeaders(access_key_id, access_token); }else if(S3fsCurl::signature_type == signature_type_t::V2_ONLY){ insertV2Headers(access_key_id, secret_access_key, access_token); }else{ if(!insertV4Headers(access_key_id, secret_access_key, access_token)){ return false; } } return true; } int S3fsCurl::DeleteRequest(const char* tpath) { S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(!tpath){ return -EINVAL; } if(!CreateCurlHandle()){ return -EIO; } std::string resource; std::string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = nullptr; responseHeaders.clear(); op = "DELETE"; type = REQTYPE::DELETE; if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_CUSTOMREQUEST, "DELETE")){ return -EIO; } if(!S3fsCurl::AddUserAgent(hCurl)){ // put User-Agent return -EIO; } return RequestPerform(); } int S3fsCurl::GetIAMv2ApiToken(const char* token_url, int token_ttl, const char* token_ttl_hdr, std::string& response) { if(!token_url || !token_ttl_hdr){ S3FS_PRN_ERR("IAMv2 token url(%s) or ttl_hdr(%s) parameter are wrong.", token_url ? token_url : "null", token_ttl_hdr ? token_ttl_hdr : "null"); return -EIO; } response.clear(); url = token_url; if(!CreateCurlHandle()){ return -EIO; } requestHeaders = nullptr; responseHeaders.clear(); bodydata.clear(); std::string ttlstr = std::to_string(token_ttl); requestHeaders = curl_slist_sort_insert(requestHeaders, token_ttl_hdr, ttlstr.c_str()); // Curl appends an "Expect: 100-continue" header to the token request, // and aws responds with a 417 Expectation Failed. This ensures the // Expect header is empty before the request is sent. requestHeaders = curl_slist_sort_insert(requestHeaders, "Expect", ""); if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true)){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_INFILESIZE, 0)){ return -EIO; } if(!S3fsCurl::AddUserAgent(hCurl)){ // put User-Agent return -EIO; } // [NOTE] // Be sure to give "dontAddAuthHeaders=true". // If set to false(default), it will deadlock in S3fsCred. // int result = RequestPerform(true); if(0 == result){ response.swap(bodydata); }else{ S3FS_PRN_ERR("Error(%d) occurred, could not get IAMv2 api token.", result); } bodydata.clear(); return result; } // // Get AccessKeyId/SecretAccessKey/AccessToken/Expiration by IAM role, // and Set these value to class variable. // bool S3fsCurl::GetIAMCredentials(const char* cred_url, const char* iam_v2_token, const char* ibm_secret_access_key, std::string& response) { if(!cred_url){ S3FS_PRN_ERR("url is null."); return false; } url = cred_url; response.clear(); // at first set type for handle type = REQTYPE::IAMCRED; if(!CreateCurlHandle()){ return false; } requestHeaders = nullptr; responseHeaders.clear(); bodydata.clear(); std::string postContent; if(ibm_secret_access_key){ // make contents postContent += "grant_type=urn:ibm:params:oauth:grant-type:apikey"; postContent += "&response_type=cloud_iam"; postContent += "&apikey="; postContent += ibm_secret_access_key; // set postdata postdata = reinterpret_cast<const unsigned char*>(postContent.c_str()); b_postdata = postdata; postdata_remaining = postContent.size(); // without null b_postdata_remaining = postdata_remaining; requestHeaders = curl_slist_sort_insert(requestHeaders, "Authorization", "Basic Yng6Yng="); if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_POST, true)){ // POST return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_POSTFIELDSIZE, static_cast<curl_off_t>(postdata_remaining))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_READDATA, reinterpret_cast<void*>(this))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_READFUNCTION, S3fsCurl::ReadCallback)){ return false; } } if(iam_v2_token){ requestHeaders = curl_slist_sort_insert(requestHeaders, S3fsCred::IAMv2_token_hdr, iam_v2_token); } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } if(!S3fsCurl::AddUserAgent(hCurl)){ // put User-Agent return false; } // [NOTE] // Be sure to give "dontAddAuthHeaders=true". // If set to false(default), it will deadlock in S3fsCred. // int result = RequestPerform(true); // analyzing response if(0 == result){ response.swap(bodydata); }else{ S3FS_PRN_ERR("Error(%d) occurred, could not get IAM role name.", result); } bodydata.clear(); return (0 == result); } // // Get IAM role name automatically. // bool S3fsCurl::GetIAMRoleFromMetaData(const char* cred_url, const char* iam_v2_token, std::string& token) { if(!cred_url){ S3FS_PRN_ERR("url is null."); return false; } url = cred_url; token.clear(); S3FS_PRN_INFO3("Get IAM Role name"); // at first set type for handle type = REQTYPE::IAMROLE; if(!CreateCurlHandle()){ return false; } requestHeaders = nullptr; responseHeaders.clear(); bodydata.clear(); if(iam_v2_token){ requestHeaders = curl_slist_sort_insert(requestHeaders, S3fsCred::IAMv2_token_hdr, iam_v2_token); } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return false; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return false; } if(!S3fsCurl::AddUserAgent(hCurl)){ // put User-Agent return false; } // [NOTE] // Be sure to give "dontAddAuthHeaders=true". // If set to false(default), it will deadlock in S3fsCred. // int result = RequestPerform(true); // analyzing response if(0 == result){ token.swap(bodydata); }else{ S3FS_PRN_ERR("Error(%d) occurred, could not get IAM role name from meta data.", result); } bodydata.clear(); return (0 == result); } bool S3fsCurl::AddSseRequestHead(sse_type_t ssetype, const std::string& input, bool is_copy) { std::string ssevalue = input; switch(ssetype){ case sse_type_t::SSE_DISABLE: return true; case sse_type_t::SSE_S3: if(!is_copy){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-server-side-encryption", "AES256"); } return true; case sse_type_t::SSE_C: { std::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."); } return true; } case sse_type_t::SSE_KMS: if(!is_copy){ 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; } S3FS_PRN_ERR("sse type is unknown(%d).", static_cast<int>(S3fsCurl::ssetype)); return false; } // // tpath : target path for head request // 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, size_t ssekey_pos) { S3FS_PRN_INFO3("[tpath=%s][sseckeypos=%zu]", SAFESTRPTR(tpath), ssekey_pos); if(!tpath){ return false; } std::string resource; std::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); requestHeaders = nullptr; responseHeaders.clear(); // requestHeaders(SSE-C) if(0 <= static_cast<ssize_t>(ssekey_pos) && ssekey_pos < S3fsCurl::sseckeys.size()){ std::string md5; if(!S3fsCurl::GetSseKeyMd5(ssekey_pos, md5) || !AddSseRequestHead(sse_type_t::SSE_C, md5, false)){ S3FS_PRN_ERR("Failed to set SSE-C headers for sse-c key pos(%zu)(=md5(%s)).", ssekey_pos, md5.c_str()); return false; } } b_ssekey_pos = ssekey_pos; op = "HEAD"; type = REQTYPE::HEAD; // set lazy function fpLazySetup = PreHeadRequestSetCurlOpts; 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) || !fpLazySetup || !fpLazySetup(this) || 0 != (result = RequestPerform())){ // If has SSE-C keys, try to get with all SSE-C keys. for(size_t pos = 0; pos < S3fsCurl::sseckeys.size(); pos++){ if(!DestroyCurlHandle()){ break; } if(!PreHeadRequest(tpath, pos)){ break; } if(!fpLazySetup || !fpLazySetup(this)){ S3FS_PRN_ERR("Failed to lazy setup in single head request."); break; } 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(auto iter = responseHeaders.cbegin(); iter != responseHeaders.cend(); ++iter){ auto key = CaseInsensitiveStringView(iter->first); const auto& value = iter->second; if(key == "content-type" || key == "content-length" || key == "etag" || key == "last-modified" || key.is_prefix("x-amz")){ meta[iter->first] = value; } } return 0; } int S3fsCurl::PutHeadRequest(const char* tpath, const headers_t& meta, bool is_copy) { S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(!tpath){ return -EINVAL; } if(!CreateCurlHandle()){ return -EIO; } std::string resource; std::string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = nullptr; responseHeaders.clear(); bodydata.clear(); std::string contype = S3fsCurl::LookupMimeType(tpath); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", contype.c_str()); // Make request headers for(auto iter = meta.cbegin(); iter != meta.cend(); ++iter){ auto key = CaseInsensitiveStringView(iter->first); const auto& value = iter->second; if(key.is_prefix("x-amz-acl")){ // not set value, but after set it. }else if(key.is_prefix("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" && value != "aws:kms"){ // skip this header, because this header is specified after logic. }else if(key == "x-amz-server-side-encryption-aws-kms-key-id"){ // skip this header, because this header is specified after logic. }else if(key == "x-amz-server-side-encryption-customer-key-md5"){ // Only copy mode. if(is_copy){ if(!AddSseRequestHead(sse_type_t::SSE_C, value, true)){ S3FS_PRN_WARN("Failed to insert SSE-C header."); } } } } // "x-amz-acl", storage class, sse if(S3fsCurl::default_acl != acl_t::PRIVATE){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-acl", str(S3fsCurl::default_acl)); } if(strcasecmp(GetStorageClass().c_str(), "STANDARD") != 0){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-storage-class", GetStorageClass().c_str()); } // SSE if(S3fsCurl::GetSseType() != sse_type_t::SSE_DISABLE){ std::string ssevalue; if(!AddSseRequestHead(S3fsCurl::GetSseType(), ssevalue, 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); } op = "PUT"; type = REQTYPE::PUTHEAD; // setopt if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true)){ // HTTP PUT return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_INFILESIZE, 0)){ // Content-Length return -EIO; } if(!S3fsCurl::AddUserAgent(hCurl)){ // put User-Agent return -EIO; } S3FS_PRN_INFO3("copying... [path=%s]", tpath); int result = RequestPerform(); result = MapPutErrorResponse(result); bodydata.clear(); return result; } int S3fsCurl::PutRequest(const char* tpath, headers_t& meta, int fd) { struct stat st; S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(!tpath){ return -EINVAL; } if(-1 != fd){ // duplicate fd // // [NOTE] // This process requires FILE*, then it is linked to fd with fdopen. // After processing, the FILE* is closed with fclose, and fd is closed together. // The fd should not be closed here, so call dup here to duplicate it. // std::unique_ptr<FILE, decltype(&s3fs_fclose)> file(nullptr, &s3fs_fclose); int fd2; if(-1 == (fd2 = dup(fd)) || -1 == fstat(fd2, &st) || 0 != lseek(fd2, 0, SEEK_SET) || nullptr == (file = {fdopen(fd2, "rb"), &s3fs_fclose})){ S3FS_PRN_ERR("Could not duplicate file descriptor(errno=%d)", errno); if(-1 != fd2){ close(fd2); } return -errno; } b_infile = std::move(file); }else{ // This case is creating zero byte object.(calling by create_file_object()) S3FS_PRN_INFO3("create zero byte file object."); } if(!CreateCurlHandle()){ return -EIO; } std::string resource; std::string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = nullptr; responseHeaders.clear(); bodydata.clear(); // Make request headers if(S3fsCurl::is_content_md5){ std::string strMD5; if(-1 != fd){ strMD5 = s3fs_get_content_md5(fd); if(strMD5.empty()){ S3FS_PRN_ERR("Failed to make MD5."); return -EIO; } }else{ strMD5 = EMPTY_MD5_BASE64_HASH; } requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-MD5", strMD5.c_str()); } std::string contype = S3fsCurl::LookupMimeType(tpath); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", contype.c_str()); for(auto iter = meta.cbegin(); iter != meta.cend(); ++iter){ auto key = CaseInsensitiveStringView(iter->first); const auto& value = iter->second; if(key.is_prefix("x-amz-acl")){ // not set value, but after set it. }else if(key.is_prefix("x-amz-meta")){ requestHeaders = curl_slist_sort_insert(requestHeaders, iter->first.c_str(), value.c_str()); }else if(key == "x-amz-server-side-encryption" && value != "aws:kms"){ // skip this header, because this header is specified after logic. }else if(key == "x-amz-server-side-encryption-aws-kms-key-id"){ // 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 if(S3fsCurl::default_acl != acl_t::PRIVATE){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-acl", str(S3fsCurl::default_acl)); } if(strcasecmp(GetStorageClass().c_str(), "STANDARD") != 0){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-storage-class", GetStorageClass().c_str()); } // SSE // do not add SSE for create bucket if(0 != strcmp(tpath, "/")){ std::string ssevalue; if(!AddSseRequestHead(S3fsCurl::GetSseType(), ssevalue, 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); } op = "PUT"; type = REQTYPE::PUT; // setopt if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_UPLOAD, true)){ // HTTP PUT return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return -EIO; } if(b_infile){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_INFILESIZE_LARGE, static_cast<curl_off_t>(st.st_size))){ // Content-Length return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_INFILE, b_infile.get())){ return -EIO; } }else{ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_INFILESIZE, 0)){ // Content-Length: 0 return -EIO; } } if(!S3fsCurl::AddUserAgent(hCurl)){ // put User-Agent return -EIO; } S3FS_PRN_INFO3("uploading... [path=%s][fd=%d][size=%lld]", tpath, fd, static_cast<long long int>(-1 != fd ? st.st_size : 0)); int result = RequestPerform(); result = MapPutErrorResponse(result); bodydata.clear(); return result; } int S3fsCurl::PreGetObjectRequest(const char* tpath, int fd, off_t start, off_t size, sse_type_t ssetype, const std::string& ssevalue) { S3FS_PRN_INFO3("[tpath=%s][start=%lld][size=%lld]", SAFESTRPTR(tpath), static_cast<long long>(start), static_cast<long long>(size)); if(!tpath || -1 == fd || 0 > start || 0 > size){ return -EINVAL; } std::string resource; std::string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = nullptr; responseHeaders.clear(); if(0 < size){ std::string range = "bytes="; range += std::to_string(start); range += "-"; range += std::to_string(start + size - 1); requestHeaders = curl_slist_sort_insert(requestHeaders, "Range", range.c_str()); } // SSE-C if(sse_type_t::SSE_C == ssetype){ if(!AddSseRequestHead(ssetype, ssevalue, false)){ S3FS_PRN_WARN("Failed to set SSE header, but continue..."); } } op = "GET"; type = REQTYPE::GET; // set lazy function fpLazySetup = PreGetObjectRequestSetCurlOpts; // 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. return 0; } int S3fsCurl::GetObjectRequest(const char* tpath, int fd, off_t start, off_t size, sse_type_t ssetype, const std::string& ssevalue) { int result; S3FS_PRN_INFO3("[tpath=%s][start=%lld][size=%lld][ssetype=%u][ssevalue=%s]", SAFESTRPTR(tpath), static_cast<long long>(start), static_cast<long long>(size), static_cast<uint8_t>(ssetype), ssevalue.c_str()); if(!tpath){ return -EINVAL; } if(0 != (result = PreGetObjectRequest(tpath, fd, start, size, ssetype, ssevalue))){ return result; } if(!fpLazySetup || !fpLazySetup(this)){ S3FS_PRN_ERR("Failed to lazy setup in single get object request."); return -EIO; } S3FS_PRN_INFO3("downloading... [path=%s][fd=%d]", tpath, fd); result = RequestPerform(); partdata.clear(); return result; } int S3fsCurl::CheckBucket(const char* check_path, bool compat_dir, bool force_no_sse) { S3FS_PRN_INFO3("check a bucket path(%s)%s.", (check_path && 0 < strlen(check_path)) ? check_path : "", compat_dir ? " containing compatible directory paths" : ""); if(!check_path || 0 == strlen(check_path)){ return -EIO; } if(!CreateCurlHandle()){ return -EIO; } std::string strCheckPath; std::string urlargs; if(S3fsCurl::IsListObjectsV2()){ query_string = "list-type=2"; }else{ query_string.clear(); } if(!compat_dir){ // do not check compatibility directories strCheckPath = check_path; }else{ // check path including compatibility directory strCheckPath = "/"; if(1 < strlen(check_path)){ // for directory path ("/...") not root path("/") if(!query_string.empty()){ query_string += '&'; } query_string += "prefix="; query_string += &check_path[1]; // skip first '/' character } } if(!query_string.empty()){ urlargs = "?" + query_string; } std::string resource; std::string turl; MakeUrlResource(strCheckPath.c_str(), resource, turl); turl += urlargs; url = prepare_url(turl.c_str()); path = strCheckPath; requestHeaders = nullptr; responseHeaders.clear(); bodydata.clear(); // SSE if(!force_no_sse && S3fsCurl::GetSseType() != sse_type_t::SSE_DISABLE){ std::string ssevalue; if(!AddSseRequestHead(S3fsCurl::GetSseType(), ssevalue, false)){ S3FS_PRN_WARN("Failed to set SSE header, but continue..."); } } op = "GET"; type = REQTYPE::CHKBUCKET; // setopt if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_UNRESTRICTED_AUTH, 1L)){ return -EIO; } if(!S3fsCurl::AddUserAgent(hCurl)){ // put User-Agent return -EIO; } int result = RequestPerform(); if (result != 0) { S3FS_PRN_ERR("Check bucket failed, S3 response: %s", bodydata.c_str()); } return result; } int S3fsCurl::ListBucketRequest(const char* tpath, const char* query) { S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(!tpath){ return -EINVAL; } if(!CreateCurlHandle()){ return -EIO; } std::string resource; std::string turl; MakeUrlResource("", resource, turl); // NOTICE: path is "". if(query){ turl += "?"; turl += query; query_string = query; } url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = nullptr; responseHeaders.clear(); bodydata.clear(); op = "GET"; type = REQTYPE::LISTBUCKET; // setopt if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return -EIO; } if(S3fsCurl::is_verbose){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_DEBUGFUNCTION, S3fsCurl::CurlDebugBodyInFunc)){ // replace debug function return -EIO; } } if(!S3fsCurl::AddUserAgent(hCurl)){ // put User-Agent return -EIO; } 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::PreMultipartUploadRequest(const char* tpath, const headers_t& meta, std::string& upload_id) { S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(!tpath){ return -EINVAL; } if(!CreateCurlHandle()){ return -EIO; } std::string resource; std::string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); query_string = "uploads"; turl += "?" + query_string; url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = nullptr; bodydata.clear(); responseHeaders.clear(); std::string contype = S3fsCurl::LookupMimeType(tpath); for(auto iter = meta.cbegin(); iter != meta.cend(); ++iter){ auto key = CaseInsensitiveStringView(iter->first); const auto& value = iter->second; if(key.is_prefix("x-amz-acl")){ // not set value, but after set it. }else if(key.is_prefix("x-amz-meta")){ requestHeaders = curl_slist_sort_insert(requestHeaders, iter->first.c_str(), value.c_str()); }else if(key == "x-amz-server-side-encryption" && value != "aws:kms"){ // skip this header, because this header is specified after logic. }else if(key == "x-amz-server-side-encryption-aws-kms-key-id"){ // 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 if(S3fsCurl::default_acl != acl_t::PRIVATE){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-acl", str(S3fsCurl::default_acl)); } if(strcasecmp(GetStorageClass().c_str(), "STANDARD") != 0){ requestHeaders = curl_slist_sort_insert(requestHeaders, "x-amz-storage-class", GetStorageClass().c_str()); } // SSE if(S3fsCurl::GetSseType() != sse_type_t::SSE_DISABLE){ std::string ssevalue; if(!AddSseRequestHead(S3fsCurl::GetSseType(), ssevalue, 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); } requestHeaders = curl_slist_sort_insert(requestHeaders, "Accept", nullptr); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", contype.c_str()); op = "POST"; type = REQTYPE::PREMULTIPOST; // setopt if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_POST, true)){ // POST return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_POSTFIELDSIZE, 0)){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_INFILESIZE, 0)){ // Content-Length return -EIO; } if(!S3fsCurl::AddUserAgent(hCurl)){ // put User-Agent return -EIO; } // request int result; if(0 != (result = RequestPerform())){ bodydata.clear(); return result; } if(!simple_parse_xml(bodydata.c_str(), bodydata.size(), "UploadId", upload_id)){ bodydata.clear(); return -EIO; } bodydata.clear(); return 0; } int S3fsCurl::MultipartUploadComplete(const char* tpath, const std::string& upload_id, const etaglist_t& parts) { S3FS_PRN_INFO3("[tpath=%s][parts=%zu]", SAFESTRPTR(tpath), parts.size()); if(!tpath){ return -EINVAL; } // make contents std::string postContent; postContent += "<CompleteMultipartUpload>\n"; for(auto it = parts.cbegin(); it != parts.cend(); ++it){ if(it->etag.empty()){ S3FS_PRN_ERR("%d file part is not finished uploading.", it->part_num); return -EIO; } postContent += "<Part>\n"; postContent += " <PartNumber>" + std::to_string(it->part_num) + "</PartNumber>\n"; postContent += " <ETag>" + it->etag + "</ETag>\n"; postContent += "</Part>\n"; } postContent += "</CompleteMultipartUpload>\n"; // set postdata postdata = reinterpret_cast<const unsigned char*>(postContent.c_str()); b_postdata = postdata; postdata_remaining = postContent.size(); // without null b_postdata_remaining = postdata_remaining; if(!CreateCurlHandle()){ postdata = nullptr; b_postdata = nullptr; return -EIO; } std::string resource; std::string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); // [NOTE] // Encode the upload_id here. // In compatible S3 servers(Cloudflare, etc), there are cases where characters that require URL encoding are included. // query_string = "uploadId=" + urlEncodeGeneral(upload_id); turl += "?" + query_string; url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = nullptr; bodydata.clear(); responseHeaders.clear(); std::string contype = "application/xml"; requestHeaders = curl_slist_sort_insert(requestHeaders, "Accept", nullptr); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", contype.c_str()); if(sse_type_t::SSE_C == S3fsCurl::GetSseType()){ std::string ssevalue; if(!AddSseRequestHead(S3fsCurl::GetSseType(), ssevalue, false)){ S3FS_PRN_WARN("Failed to set SSE header, but continue..."); } } op = "POST"; type = REQTYPE::COMPLETEMULTIPOST; // setopt if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_POST, true)){ // POST return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_POSTFIELDSIZE, static_cast<curl_off_t>(postdata_remaining))){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_READDATA, reinterpret_cast<void*>(this))){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_READFUNCTION, S3fsCurl::ReadCallback)){ return -EIO; } if(S3fsCurl::is_verbose){ if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_DEBUGFUNCTION, S3fsCurl::CurlDebugBodyOutFunc)){ // replace debug function return -EIO; } } if(!S3fsCurl::AddUserAgent(hCurl)){ // put User-Agent return -EIO; } // request int result = RequestPerform(); bodydata.clear(); postdata = nullptr; b_postdata = nullptr; return result; } int S3fsCurl::MultipartListRequest(std::string& body) { S3FS_PRN_INFO3("list request(multipart)"); if(!CreateCurlHandle()){ return -EIO; } std::string resource; std::string turl; path = get_realpath("/"); MakeUrlResource(path.c_str(), resource, turl); query_string = "uploads"; turl += "?" + query_string; url = prepare_url(turl.c_str()); requestHeaders = nullptr; responseHeaders.clear(); bodydata.clear(); requestHeaders = curl_slist_sort_insert(requestHeaders, "Accept", nullptr); op = "GET"; type = REQTYPE::MULTILIST; // setopt if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&bodydata))){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback)){ return -EIO; } if(!S3fsCurl::AddUserAgent(hCurl)){ // put User-Agent return -EIO; } int result; if(0 == (result = RequestPerform()) && !bodydata.empty()){ body.swap(bodydata); }else{ body = ""; } bodydata.clear(); return result; } int S3fsCurl::AbortMultipartUpload(const char* tpath, const std::string& upload_id) { S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(!tpath){ return -EINVAL; } if(!CreateCurlHandle()){ return -EIO; } std::string resource; std::string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); // [NOTE] // Encode the upload_id here. // In compatible S3 servers(Cloudflare, etc), there are cases where characters that require URL encoding are included. // query_string = "uploadId=" + urlEncodeGeneral(upload_id); turl += "?" + query_string; url = prepare_url(turl.c_str()); path = get_realpath(tpath); requestHeaders = nullptr; responseHeaders.clear(); op = "DELETE"; type = REQTYPE::ABORTMULTIUPLOAD; if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_URL, url.c_str())){ return -EIO; } if(CURLE_OK != curl_easy_setopt(hCurl, CURLOPT_CUSTOMREQUEST, "DELETE")){ return -EIO; } if(!S3fsCurl::AddUserAgent(hCurl)){ // put User-Agent return -EIO; } 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::MultipartUploadPartSetup(const char* tpath, int part_num, const std::string& upload_id) { S3FS_PRN_INFO3("[tpath=%s][start=%lld][size=%lld][part=%d]", SAFESTRPTR(tpath), static_cast<long long int>(partdata.startpos), static_cast<long long int>(partdata.size), part_num); if(-1 == partdata.fd || -1 == partdata.startpos || -1 == partdata.size){ return -EINVAL; } requestHeaders = nullptr; // make md5 and file pointer if(S3fsCurl::is_content_md5){ md5_t md5raw; if(!s3fs_md5_fd(partdata.fd, partdata.startpos, partdata.size, &md5raw)){ S3FS_PRN_ERR("Could not make md5 for file(part %d)", part_num); return -EIO; } partdata.etag = s3fs_hex_lower(md5raw.data(), md5raw.size()); std::string md5base64 = s3fs_base64(md5raw.data(), md5raw.size()); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-MD5", md5base64.c_str()); } // make request // // [NOTE] // Encode the upload_id here. // In compatible S3 servers(Cloudflare, etc), there are cases where characters that require URL encoding are included. // query_string = "partNumber=" + std::to_string(part_num) + "&uploadId=" + urlEncodeGeneral(upload_id); std::string urlargs = "?" + query_string; std::string resource; std::string turl; MakeUrlResource(get_realpath(tpath).c_str(), resource, turl); turl += urlargs; url = prepare_url(turl.c_str()); path = get_realpath(tpath); bodydata.clear(); headdata.clear(); responseHeaders.clear(); // SSE-C if(sse_type_t::SSE_C == S3fsCurl::GetSseType()){ std::string ssevalue; if(!AddSseRequestHead(S3fsCurl::GetSseType(), ssevalue, false)){ S3FS_PRN_WARN("Failed to set SSE header, but continue..."); } } requestHeaders = curl_slist_sort_insert(requestHeaders, "Accept", nullptr); op = "PUT"; type = REQTYPE::UPLOADMULTIPOST; // set lazy function fpLazySetup = MultipartUploadPartSetCurlOpts; return 0; } int S3fsCurl::MultipartUploadPartRequest(const char* tpath, int part_num, const std::string& upload_id) { int result; S3FS_PRN_INFO3("[tpath=%s][start=%lld][size=%lld][part=%d]", SAFESTRPTR(tpath), static_cast<long long int>(partdata.startpos), static_cast<long long int>(partdata.size), part_num); // setup if(0 != (result = S3fsCurl::MultipartUploadPartSetup(tpath, part_num, upload_id))){ return result; } if(!fpLazySetup || !fpLazySetup(this)){ S3FS_PRN_ERR("Failed to lazy setup in multipart upload part request."); return -EIO; } // request if(0 == (result = RequestPerform())){ if(!MultipartUploadPartComplete()){ result = -EIO; } } // closing bodydata.clear(); headdata.clear(); return result; } int S3fsCurl::CopyMultipartUploadSetup(const char* from, const char* to, int part_num, const std::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 -EINVAL; } // [NOTE] // Encode the upload_id here. // In compatible S3 servers(Cloudflare, etc), there are cases where characters that require URL encoding are included. // query_string = "partNumber=" + std::to_string(part_num) + "&uploadId=" + urlEncodeGeneral(upload_id); std::string urlargs = "?" + query_string; std::string resource; std::string turl; MakeUrlResource(get_realpath(to).c_str(), resource, turl); turl += urlargs; url = prepare_url(turl.c_str()); path = get_realpath(to); requestHeaders = nullptr; responseHeaders.clear(); bodydata.clear(); headdata.clear(); std::string contype = S3fsCurl::LookupMimeType(to); requestHeaders = curl_slist_sort_insert(requestHeaders, "Content-Type", contype.c_str()); // Make request headers for(auto iter = meta.cbegin(); iter != meta.cend(); ++iter){ auto key = CaseInsensitiveStringView(iter->first); const auto& value = iter->second; 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()); }else if(key == "x-amz-server-side-encryption" && value != "aws:kms"){ // skip this header }else if(key == "x-amz-server-side-encryption-aws-kms-key-id"){ // skip this header }else if(key == "x-amz-server-side-encryption-customer-key-md5"){ if(!AddSseRequestHead(sse_type_t::SSE_C, value, true)){ S3FS_PRN_WARN("Failed to insert SSE-C header."); } } } // SSE-C if(sse_type_t::SSE_C == S3fsCurl::GetSseType()){ std::string ssevalue; if(!AddSseRequestHead(S3fsCurl::GetSseType(), ssevalue, false)){ S3FS_PRN_WARN("Failed to set SSE header, but continue..."); } } op = "PUT"; type = REQTYPE::COPYMULTIPOST; // set lazy function fpLazySetup = CopyMultipartUploadSetCurlOpts; // request S3FS_PRN_INFO3("copying... [from=%s][to=%s][part=%d]", from, to, part_num); return 0; } bool S3fsCurl::MultipartUploadPartComplete() { auto it = responseHeaders.find("ETag"); if (it == responseHeaders.cend()) { return false; } std::string etag = peeloff(it->second); // check etag(md5); // // The ETAG when using SSE_C and SSE_KMS does not reflect the MD5 we sent // SSE_C: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html // SSE_KMS is ignored in the above, but in the following it states the same in the highlights: // https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html // if(S3fsCurl::is_content_md5 && sse_type_t::SSE_C != S3fsCurl::GetSseType() && sse_type_t::SSE_KMS != S3fsCurl::GetSseType()){ if(!etag_equals(etag, partdata.etag)){ return false; } } partdata.petag->etag = etag; partdata.uploaded = true; return true; } // cppcheck-suppress unmatchedSuppression // cppcheck-suppress constParameter // cppcheck-suppress constParameterCallback bool S3fsCurl::CopyMultipartUploadCallback(S3fsCurl* s3fscurl, void* param) { if(!s3fscurl || param){ // this callback does not need a parameter return false; } // cppcheck-suppress unmatchedSuppression // cppcheck-suppress knownConditionTrueFalse return s3fscurl->CopyMultipartUploadComplete(); } bool S3fsCurl::CopyMultipartUploadComplete() { std::string etag; partdata.uploaded = simple_parse_xml(bodydata.c_str(), bodydata.size(), "ETag", etag); partdata.petag->etag = peeloff(std::move(etag)); bodydata.clear(); headdata.clear(); return true; } bool S3fsCurl::MixMultipartUploadComplete() { bool result; if(-1 == partdata.fd){ result = CopyMultipartUploadComplete(); }else{ result = MultipartUploadPartComplete(); } return result; } int S3fsCurl::MultipartHeadRequest(const char* tpath, off_t size, headers_t& meta) { int result; std::string upload_id; off_t chunk; off_t bytes_remaining; etaglist_t list; S3FS_PRN_INFO3("[tpath=%s]", SAFESTRPTR(tpath)); if(0 != (result = PreMultipartUploadRequest(tpath, meta, upload_id))){ return result; } DestroyCurlHandle(); // Initialize S3fsMultiCurl S3fsMultiCurl curlmulti(GetMaxParallelCount()); curlmulti.SetSuccessCallback(S3fsCurl::CopyMultipartUploadCallback); curlmulti.SetRetryCallback(S3fsCurl::CopyMultipartUploadRetryCallback); for(bytes_remaining = size; 0 < bytes_remaining; bytes_remaining -= chunk){ chunk = bytes_remaining > GetMultipartCopySize() ? GetMultipartCopySize() : bytes_remaining; std::ostringstream strrange; strrange << "bytes=" << (size - bytes_remaining) << "-" << (size - bytes_remaining + chunk - 1); meta["x-amz-copy-source-range"] = strrange.str(); // s3fscurl sub object std::unique_ptr<S3fsCurl> s3fscurl_para(new S3fsCurl(true)); s3fscurl_para->b_from = SAFESTRPTR(tpath); s3fscurl_para->b_meta = meta; s3fscurl_para->partdata.add_etag_list(list); // initiate upload part for parallel if(0 != (result = s3fscurl_para->CopyMultipartUploadSetup(tpath, tpath, s3fscurl_para->partdata.get_part_number(), upload_id, meta))){ S3FS_PRN_ERR("failed uploading part setup(%d)", result); return result; } // set into parallel object if(!curlmulti.SetS3fsCurlObject(std::move(s3fscurl_para))){ S3FS_PRN_ERR("Could not make curl object into multi curl(%s).", tpath); return -EIO; } } // Multi request if(0 != (result = curlmulti.Request())){ S3FS_PRN_ERR("error occurred in multi request(errno=%d).", result); int result2; if(0 != (result2 = abort_multipart_upload_request(std::string(tpath), upload_id))){ S3FS_PRN_ERR("error aborting multipart upload(errno=%d).", result2); } return result; } if(0 != (result = MultipartUploadComplete(tpath, upload_id, list))){ return result; } return 0; } int S3fsCurl::MultipartUploadRequest(const std::string& upload_id, const char* tpath, int fd, off_t offset, off_t size, etagpair* petagpair) { S3FS_PRN_INFO3("[upload_id=%s][tpath=%s][fd=%d][offset=%lld][size=%lld]", upload_id.c_str(), SAFESTRPTR(tpath), fd, static_cast<long long int>(offset), static_cast<long long int>(size)); // set partdata.fd = fd; partdata.startpos = offset; partdata.size = size; b_partdata_startpos = partdata.startpos; b_partdata_size = partdata.size; partdata.set_etag(petagpair); // upload part int result; if(0 != (result = MultipartUploadPartRequest(tpath, petagpair->part_num, upload_id))){ S3FS_PRN_ERR("failed uploading %d part by error(%d)", petagpair->part_num, result); return result; } DestroyCurlHandle(); return 0; } int S3fsCurl::MultipartRenameRequest(const char* from, const char* to, headers_t& meta, off_t size) { int result; std::string upload_id; off_t chunk; off_t bytes_remaining; etaglist_t list; S3FS_PRN_INFO3("[from=%s][to=%s]", SAFESTRPTR(from), SAFESTRPTR(to)); std::string srcresource; std::string srcurl; MakeUrlResource(get_realpath(from).c_str(), srcresource, srcurl); meta["Content-Type"] = S3fsCurl::LookupMimeType(to); meta["x-amz-copy-source"] = srcresource; if(0 != (result = PreMultipartUploadRequest(to, meta, upload_id))){ return result; } DestroyCurlHandle(); // Initialize S3fsMultiCurl S3fsMultiCurl curlmulti(GetMaxParallelCount()); curlmulti.SetSuccessCallback(S3fsCurl::CopyMultipartUploadCallback); curlmulti.SetRetryCallback(S3fsCurl::CopyMultipartUploadRetryCallback); for(bytes_remaining = size; 0 < bytes_remaining; bytes_remaining -= chunk){ chunk = bytes_remaining > GetMultipartCopySize() ? GetMultipartCopySize() : bytes_remaining; std::ostringstream strrange; strrange << "bytes=" << (size - bytes_remaining) << "-" << (size - bytes_remaining + chunk - 1); meta["x-amz-copy-source-range"] = strrange.str(); // s3fscurl sub object std::unique_ptr<S3fsCurl> s3fscurl_para(new S3fsCurl(true)); s3fscurl_para->b_from = SAFESTRPTR(from); s3fscurl_para->b_meta = meta; s3fscurl_para->partdata.add_etag_list(list); // initiate upload part for parallel if(0 != (result = s3fscurl_para->CopyMultipartUploadSetup(from, to, s3fscurl_para->partdata.get_part_number(), upload_id, meta))){ S3FS_PRN_ERR("failed uploading part setup(%d)", result); return result; } // set into parallel object if(!curlmulti.SetS3fsCurlObject(std::move(s3fscurl_para))){ S3FS_PRN_ERR("Could not make curl object into multi curl(%s).", to); return -EIO; } } // Multi request if(0 != (result = curlmulti.Request())){ S3FS_PRN_ERR("error occurred in multi request(errno=%d).", result); int result2; if(0 != (result2 = abort_multipart_upload_request(std::string(to), upload_id))){ S3FS_PRN_ERR("error aborting multipart upload(errno=%d).", result2); } return result; } if(0 != (result = MultipartUploadComplete(to, upload_id, list))){ return result; } return 0; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
159,487
C++
.cpp
4,005
31.982022
290
0.595462
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,459
fdcache_auto.cpp
s3fs-fuse_s3fs-fuse/src/fdcache_auto.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <cstdio> #include "s3fs_logger.h" #include "fdcache_auto.h" #include "fdcache.h" //------------------------------------------------ // AutoFdEntity methods //------------------------------------------------ AutoFdEntity::AutoFdEntity() : pFdEntity(nullptr), pseudo_fd(-1) { } AutoFdEntity::~AutoFdEntity() { Close(); } bool AutoFdEntity::Close() { if(pFdEntity){ if(!FdManager::get()->Close(pFdEntity, pseudo_fd)){ S3FS_PRN_ERR("Failed to close fdentity."); return false; } pFdEntity = nullptr; pseudo_fd = -1; } return true; } // [NOTE] // This method touches the internal fdentity with. // This is used to keep the file open. // int AutoFdEntity::Detach() { if(!pFdEntity){ S3FS_PRN_ERR("Does not have a associated FdEntity."); return -1; } int fd = pseudo_fd; pseudo_fd = -1; pFdEntity = nullptr; return fd; } FdEntity* AutoFdEntity::Attach(const char* path, int existfd) { Close(); if(nullptr == (pFdEntity = FdManager::get()->GetFdEntity(path, existfd, false))){ S3FS_PRN_DBG("Could not find fd entity object(file=%s, pseudo_fd=%d)", path, existfd); return nullptr; } pseudo_fd = existfd; return pFdEntity; } FdEntity* AutoFdEntity::Open(const char* path, const headers_t* pmeta, off_t size, const struct timespec& ts_mctime, int flags, bool force_tmpfile, bool is_create, bool ignore_modify, int* error) { Close(); if(nullptr == (pFdEntity = FdManager::get()->Open(pseudo_fd, path, pmeta, size, ts_mctime, flags, force_tmpfile, is_create, ignore_modify))){ if(error){ *error = pseudo_fd; } pseudo_fd = -1; return nullptr; } return pFdEntity; } // [NOTE] // the fd obtained by this method is not a newly created pseudo fd. // FdEntity* AutoFdEntity::GetExistFdEntity(const char* path, int existfd) { Close(); FdEntity* ent; if(nullptr == (ent = FdManager::get()->GetExistFdEntity(path, existfd))){ return nullptr; } return ent; } FdEntity* AutoFdEntity::OpenExistFdEntity(const char* path, int flags) { Close(); if(nullptr == (pFdEntity = FdManager::get()->OpenExistFdEntity(path, pseudo_fd, flags))){ return nullptr; } return pFdEntity; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
3,309
C++
.cpp
110
26.409091
195
0.659441
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,460
syncfiller.cpp
s3fs-fuse_s3fs-fuse/src/syncfiller.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <cstdio> #include <cstdlib> #include "s3fs_logger.h" #include "syncfiller.h" //------------------------------------------------------------------- // Class SyncFiller //------------------------------------------------------------------- SyncFiller::SyncFiller(void* buff, fuse_fill_dir_t filler) : filler_buff(buff), filler_func(filler) { if(!filler_buff || !filler_func){ S3FS_PRN_CRIT("Internal error: SyncFiller constructor parameter is critical value."); abort(); } } // // See. prototype fuse_fill_dir_t in fuse.h // int SyncFiller::Fill(const std::string& name, const struct stat *stbuf, off_t off) { const std::lock_guard<std::mutex> lock(filler_lock); int result = 0; if(filled.insert(name).second){ result = filler_func(filler_buff, name.c_str(), stbuf, off); } return result; } int SyncFiller::SufficiencyFill(const std::vector<std::string>& pathlist) { const std::lock_guard<std::mutex> lock(filler_lock); int result = 0; for(auto it = pathlist.cbegin(); it != pathlist.cend(); ++it) { if(filled.insert(*it).second){ if(0 != filler_func(filler_buff, it->c_str(), nullptr, 0)){ result = 1; } } } return result; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,244
C++
.cpp
66
30.666667
99
0.647465
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,461
fdcache.cpp
s3fs-fuse_s3fs-fuse/src/fdcache.cpp
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec.com> * * 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 <cstdio> #include <cstdlib> #include <cerrno> #include <climits> #include <unistd.h> #include <dirent.h> #include <mutex> #include <string> #include <sys/stat.h> #include <sys/statvfs.h> #include <utility> #include "fdcache.h" #include "fdcache_stat.h" #include "s3fs_util.h" #include "s3fs_logger.h" #include "s3fs_cred.h" #include "string_util.h" // // The following symbols are used by FdManager::RawCheckAllCache(). // // These must be #defines due to string literal concatenation. #define CACHEDBG_FMT_HEAD "---------------------------------------------------------------------------\n" \ "Check cache file and its stats file consistency at %s\n" \ "---------------------------------------------------------------------------" #define CACHEDBG_FMT_FOOT "---------------------------------------------------------------------------\n" \ "Summary - Total files: %d\n" \ " Detected error files: %d\n" \ " Detected error directories: %d\n" \ "---------------------------------------------------------------------------" #define CACHEDBG_FMT_FILE_OK "File: %s%s -> [OK] no problem" #define CACHEDBG_FMT_FILE_PROB "File: %s%s" #define CACHEDBG_FMT_DIR_PROB "Directory: %s" #define CACHEDBG_FMT_ERR_HEAD " -> [E] there is a mark that data exists in stats, but there is no data in the cache file." #define CACHEDBG_FMT_WARN_HEAD " -> [W] These show no data in stats, but there is evidence of data in the cache file(no problem)." #define CACHEDBG_FMT_WARN_OPEN "\n -> [W] This file is currently open and may not provide accurate analysis results." #define CACHEDBG_FMT_CRIT_HEAD " -> [C] %s" #define CACHEDBG_FMT_CRIT_HEAD2 " -> [C] " #define CACHEDBG_FMT_PROB_BLOCK " 0x%016zx(0x%016zx bytes)" // [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. // static constexpr char NOCACHE_PATH_PREFIX_FORM[] = " __S3FS_UNEXISTED_PATH_%lx__ / "; // important space words for simply //------------------------------------------------ // FdManager class variable //------------------------------------------------ FdManager FdManager::singleton; std::mutex FdManager::fd_manager_lock; std::mutex FdManager::cache_cleanup_lock; std::mutex FdManager::reserved_diskspace_lock; std::mutex FdManager::except_entmap_lock; std::string FdManager::cache_dir; bool FdManager::check_cache_dir_exist(false); off_t FdManager::free_disk_space = 0; off_t FdManager::fake_used_disk_space = 0; std::string FdManager::check_cache_output; bool FdManager::checked_lseek(false); bool FdManager::have_lseek_hole(false); std::string FdManager::tmp_dir = "/tmp"; //------------------------------------------------ // FdManager class methods //------------------------------------------------ bool FdManager::SetCacheDir(const char* dir) { if(!dir || '\0' == dir[0]){ cache_dir = ""; }else{ cache_dir = dir; } return true; } bool FdManager::SetCacheCheckOutput(const char* path) { if(!path || '\0' == path[0]){ check_cache_output.clear(); }else{ check_cache_output = path; } return true; } bool FdManager::DeleteCacheDirectory() { if(FdManager::cache_dir.empty()){ return true; } std::string cache_path; if(!FdManager::MakeCachePath(nullptr, cache_path, false)){ return false; } if(!delete_files_in_dir(cache_path.c_str(), true)){ return false; } std::string mirror_path = FdManager::cache_dir + "/." + S3fsCred::GetBucket() + ".mirror"; if(!delete_files_in_dir(mirror_path.c_str(), true)){ return false; } return true; } int FdManager::DeleteCacheFile(const char* path) { S3FS_PRN_INFO3("[path=%s]", SAFESTRPTR(path)); if(!path){ return -EIO; } if(FdManager::cache_dir.empty()){ return 0; } std::string cache_path; if(!FdManager::MakeCachePath(path, cache_path, false)){ return 0; } int result = 0; if(0 != unlink(cache_path.c_str())){ if(ENOENT == errno){ S3FS_PRN_DBG("failed to delete file(%s): errno=%d", path, errno); }else{ S3FS_PRN_ERR("failed to delete file(%s): errno=%d", path, errno); } return -errno; } if(0 != (result = CacheFileStat::DeleteCacheFileStat(path))){ if(-ENOENT == result){ S3FS_PRN_DBG("failed to delete stat file(%s): errno=%d", path, result); }else{ S3FS_PRN_ERR("failed to delete stat file(%s): errno=%d", path, result); } } return result; } bool FdManager::MakeCachePath(const char* path, std::string& cache_path, bool is_create_dir, bool is_mirror_path) { if(FdManager::cache_dir.empty()){ cache_path = ""; return true; } std::string resolved_path(FdManager::cache_dir); if(!is_mirror_path){ resolved_path += "/"; resolved_path += S3fsCred::GetBucket(); }else{ resolved_path += "/."; resolved_path += S3fsCred::GetBucket(); resolved_path += ".mirror"; } 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() { if(FdManager::cache_dir.empty()){ return true; } std::string toppath(FdManager::cache_dir + "/" + S3fsCred::GetBucket()); return check_exist_dir_permission(toppath.c_str()); } bool FdManager::MakeRandomTempPath(const char* path, std::string& tmppath) { char szBuff[64]; snprintf(szBuff, sizeof(szBuff), NOCACHE_PATH_PREFIX_FORM, random()); // worry for performance, but maybe don't worry. szBuff[sizeof(szBuff) - 1] = '\0'; // for safety tmppath = szBuff; tmppath += path ? path : ""; return true; } bool FdManager::SetCheckCacheDirExist(bool is_check) { bool old = FdManager::check_cache_dir_exist; FdManager::check_cache_dir_exist = is_check; return old; } bool FdManager::CheckCacheDirExist() { if(!FdManager::check_cache_dir_exist){ return true; } if(FdManager::cache_dir.empty()){ return true; } return IsDir(cache_dir); } off_t FdManager::GetEnsureFreeDiskSpaceHasLock() { return FdManager::free_disk_space; } off_t FdManager::SetEnsureFreeDiskSpace(off_t size) { const std::lock_guard<std::mutex> lock(FdManager::reserved_diskspace_lock); off_t old = FdManager::free_disk_space; FdManager::free_disk_space = size; return old; } bool FdManager::InitFakeUsedDiskSize(off_t fake_freesize) { const std::lock_guard<std::mutex> lock(FdManager::reserved_diskspace_lock); FdManager::fake_used_disk_space = 0; // At first, clear this value because this value is used in GetFreeDiskSpaceHasLock. off_t actual_freesize = FdManager::GetFreeDiskSpaceHasLock(nullptr); if(fake_freesize < actual_freesize){ FdManager::fake_used_disk_space = actual_freesize - fake_freesize; }else{ FdManager::fake_used_disk_space = 0; } return true; } off_t FdManager::GetTotalDiskSpaceByRatio(int ratio) { return FdManager::GetTotalDiskSpace(nullptr) * ratio / 100; } off_t FdManager::GetTotalDiskSpace(const char* path) { struct statvfs vfsbuf; int result = FdManager::GetVfsStat(path, &vfsbuf); if(result == -1){ return 0; } off_t actual_totalsize = vfsbuf.f_blocks * vfsbuf.f_frsize; return actual_totalsize; } off_t FdManager::GetFreeDiskSpaceHasLock(const char* path) { struct statvfs vfsbuf; int result = FdManager::GetVfsStat(path, &vfsbuf); if(result == -1){ return 0; } off_t actual_freesize = vfsbuf.f_bavail * vfsbuf.f_frsize; return (FdManager::fake_used_disk_space < actual_freesize ? (actual_freesize - FdManager::fake_used_disk_space) : 0); } int FdManager::GetVfsStat(const char* path, struct statvfs* vfsbuf){ std::string ctoppath; if(!FdManager::cache_dir.empty()){ ctoppath = FdManager::cache_dir + "/"; ctoppath = get_exist_directory_path(ctoppath); // existed directory if(ctoppath != "/"){ ctoppath += "/"; } }else{ ctoppath = tmp_dir + "/"; } if(path && '\0' != *path){ ctoppath += path; }else{ ctoppath += "."; } if(-1 == statvfs(ctoppath.c_str(), vfsbuf)){ S3FS_PRN_ERR("could not get vfs stat by errno(%d)", errno); return -1; } return 0; } bool FdManager::IsSafeDiskSpace(const char* path, off_t size, bool withmsg) { const std::lock_guard<std::mutex> lock(FdManager::reserved_diskspace_lock); off_t fsize = FdManager::GetFreeDiskSpaceHasLock(path); off_t needsize = size + FdManager::GetEnsureFreeDiskSpaceHasLock(); if(fsize < needsize){ if(withmsg){ S3FS_PRN_EXIT("There is no enough disk space for used as cache(or temporary) directory by s3fs. Requires %.3f MB, already has %.3f MB.", static_cast<double>(needsize) / 1024 / 1024, static_cast<double>(fsize) / 1024 / 1024); } return false; } return true; } bool FdManager::HaveLseekHole() { if(FdManager::checked_lseek){ return FdManager::have_lseek_hole; } // create temporary file int fd; auto ptmpfp = MakeTempFile(); if(nullptr == ptmpfp || -1 == (fd = fileno(ptmpfp.get()))){ S3FS_PRN_ERR("failed to open temporary file by errno(%d)", errno); FdManager::checked_lseek = true; FdManager::have_lseek_hole = false; return false; } // check SEEK_DATA/SEEK_HOLE options bool result = true; if(-1 == lseek(fd, 0, SEEK_DATA)){ if(EINVAL == errno){ S3FS_PRN_ERR("lseek does not support SEEK_DATA"); result = false; } } if(result && -1 == lseek(fd, 0, SEEK_HOLE)){ if(EINVAL == errno){ S3FS_PRN_ERR("lseek does not support SEEK_HOLE"); result = false; } } FdManager::checked_lseek = true; FdManager::have_lseek_hole = result; return FdManager::have_lseek_hole; } bool FdManager::SetTmpDir(const char *dir) { if(!dir || '\0' == dir[0]){ tmp_dir = "/tmp"; }else{ tmp_dir = dir; } return true; } bool FdManager::IsDir(const std::string& dir) { // check the directory struct stat st; if(0 != stat(dir.c_str(), &st)){ S3FS_PRN_ERR("could not stat() directory %s by errno(%d).", dir.c_str(), errno); return false; } if(!S_ISDIR(st.st_mode)){ S3FS_PRN_ERR("the directory %s is not a directory.", dir.c_str()); return false; } return true; } bool FdManager::CheckTmpDirExist() { if(FdManager::tmp_dir.empty()){ return true; } return IsDir(tmp_dir); } std::unique_ptr<FILE, decltype(&s3fs_fclose)> FdManager::MakeTempFile() { int fd; char cfn[PATH_MAX]; std::string fn = tmp_dir + "/s3fstmp.XXXXXX"; strncpy(cfn, fn.c_str(), sizeof(cfn) - 1); cfn[sizeof(cfn) - 1] = '\0'; fd = mkstemp(cfn); if (-1 == fd) { S3FS_PRN_ERR("failed to create tmp file. errno(%d)", errno); return {nullptr, &s3fs_fclose}; } if (-1 == unlink(cfn)) { S3FS_PRN_ERR("failed to delete tmp file. errno(%d)", errno); return {nullptr, &s3fs_fclose}; } return {fdopen(fd, "rb+"), &s3fs_fclose}; } bool FdManager::HasOpenEntityFd(const char* path) { const std::lock_guard<std::mutex> lock(FdManager::fd_manager_lock); const FdEntity* ent; int fd = -1; if(nullptr == (ent = FdManager::singleton.GetFdEntityHasLock(path, fd, false))){ return false; } return (0 < ent->GetOpenCount()); } // [NOTE] // Returns the number of open pseudo fd. // int FdManager::GetOpenFdCount(const char* path) { const std::lock_guard<std::mutex> lock(FdManager::fd_manager_lock); return FdManager::singleton.GetPseudoFdCount(path); } //------------------------------------------------ // FdManager methods //------------------------------------------------ FdManager::FdManager() { if(this != FdManager::get()){ abort(); } } FdManager::~FdManager() { if(this == FdManager::get()){ for(auto iter = fent.cbegin(); fent.cend() != iter; ++iter){ FdEntity* ent = (*iter).second.get(); S3FS_PRN_WARN("To exit with the cache file opened: path=%s, refcnt=%d", ent->GetPath().c_str(), ent->GetOpenCount()); } fent.clear(); except_fent.clear(); }else{ abort(); } } FdEntity* FdManager::GetFdEntityHasLock(const char* path, int& existfd, bool newfd) { S3FS_PRN_INFO3("[path=%s][pseudo_fd=%d]", SAFESTRPTR(path), existfd); if(!path || '\0' == path[0]){ return nullptr; } UpdateEntityToTempPath(); auto fiter = fent.find(path); if(fent.cend() != fiter && fiter->second){ if(-1 == existfd){ if(newfd){ existfd = fiter->second->OpenPseudoFd(O_RDWR); // [NOTE] O_RDWR flags } return fiter->second.get(); }else{ if(fiter->second->FindPseudoFd(existfd)){ if(newfd){ existfd = fiter->second->Dup(existfd); } return fiter->second.get(); } } } if(-1 != existfd){ for(auto iter = fent.cbegin(); iter != fent.cend(); ++iter){ if(iter->second && iter->second->FindPseudoFd(existfd)){ // found opened fd in map if(iter->second->GetPath() == path){ if(newfd){ existfd = iter->second->Dup(existfd); } return iter->second.get(); } // found fd, but it is used another file(file descriptor is recycled) // so returns nullptr. break; } } } // If the cache directory is not specified, s3fs opens a temporary file // when the file is opened. if(!FdManager::IsCacheDir()){ for(auto iter = fent.cbegin(); iter != fent.cend(); ++iter){ if(iter->second && iter->second->IsOpen() && iter->second->GetPath() == path){ return iter->second.get(); } } } return nullptr; } FdEntity* FdManager::Open(int& fd, const char* path, const headers_t* pmeta, off_t size, const struct timespec& ts_mctime, int flags, bool force_tmpfile, bool is_create, bool ignore_modify) { S3FS_PRN_DBG("[path=%s][size=%lld][ts_mctime=%s][flags=0x%x][force_tmpfile=%s][create=%s][ignore_modify=%s]", SAFESTRPTR(path), static_cast<long long>(size), str(ts_mctime).c_str(), flags, (force_tmpfile ? "yes" : "no"), (is_create ? "yes" : "no"), (ignore_modify ? "yes" : "no")); if(!path || '\0' == path[0]){ return nullptr; } const std::lock_guard<std::mutex> lock(FdManager::fd_manager_lock); UpdateEntityToTempPath(); // search in mapping by key(path) auto iter = fent.find(path); if(fent.end() == iter && !force_tmpfile && !FdManager::IsCacheDir()){ // If the cache directory is not specified, s3fs opens a temporary file // when the file is opened. // Then if it could not find a entity in map for the file, s3fs should // search a entity in all which opened the temporary file. // for(iter = fent.begin(); iter != fent.end(); ++iter){ if(iter->second && iter->second->IsOpen() && iter->second->GetPath() == path){ break; // found opened fd in mapping } } } if(fent.end() != iter){ // found FdEntity* ent = iter->second.get(); // [NOTE] // If the file is being modified and ignore_modify flag is false, // the file size will not be changed even if there is a request // to reduce the size of the modified file. // If you do, the "test_open_second_fd" test will fail. // if(!ignore_modify && ent->IsModified()){ // If the file is being modified and it's size is larger than size parameter, it will not be resized. off_t cur_size = 0; if(ent->GetSize(cur_size) && size <= cur_size){ size = -1; } } // (re)open if(0 > (fd = ent->Open(pmeta, size, ts_mctime, flags))){ S3FS_PRN_ERR("failed to (re)open and create new pseudo fd for path(%s).", path); return nullptr; } return ent; }else if(is_create){ // not found std::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 nullptr; } // make new obj auto ent = std::make_shared<FdEntity>(path, cache_path.c_str()); // open if(0 > (fd = ent->Open(pmeta, size, ts_mctime, flags))){ S3FS_PRN_ERR("failed to open and create new pseudo fd for path(%s) errno:%d.", path, fd); return nullptr; } if(!cache_path.empty()){ // using cache return (fent[path] = std::move(ent)).get(); }else{ // not using cache, so the key of fdentity is set not really existing 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. // std::string tmppath; FdManager::MakeRandomTempPath(path, tmppath); return (fent[tmppath] = std::move(ent)).get(); } }else{ return nullptr; } } // [NOTE] // This method does not create a new pseudo fd. // It just finds existfd and returns the corresponding entity. // FdEntity* FdManager::GetExistFdEntity(const char* path, int existfd) { S3FS_PRN_DBG("[path=%s][pseudo_fd=%d]", SAFESTRPTR(path), existfd); const std::lock_guard<std::mutex> lock(FdManager::fd_manager_lock); UpdateEntityToTempPath(); // search from all entity. for(auto iter = fent.cbegin(); iter != fent.cend(); ++iter){ if(iter->second && iter->second->FindPseudoFd(existfd)){ // found existfd in entity return iter->second.get(); } } // not found entity return nullptr; } FdEntity* FdManager::OpenExistFdEntity(const char* path, int& fd, int flags) { S3FS_PRN_DBG("[path=%s][flags=0x%x]", SAFESTRPTR(path), flags); // search entity by path, and create pseudo fd FdEntity* ent = Open(fd, path, nullptr, -1, S3FS_OMIT_TS, flags, false, false, false); if(!ent){ // Not found entity return nullptr; } return ent; } int FdManager::GetPseudoFdCount(const char* path) { S3FS_PRN_DBG("[path=%s]", SAFESTRPTR(path)); if(!path || '\0' == path[0]){ return 0; } UpdateEntityToTempPath(); // search from all entity. for(auto iter = fent.cbegin(); iter != fent.cend(); ++iter){ if(iter->second && iter->second->GetPath() == path){ // found the entity for the path return iter->second->GetOpenCount(); } } // not found entity return 0; } void FdManager::Rename(const std::string &from, const std::string &to) { const std::lock_guard<std::mutex> lock(FdManager::fd_manager_lock); UpdateEntityToTempPath(); auto iter = fent.find(from); if(fent.end() == iter && !FdManager::IsCacheDir()){ // If the cache directory is not specified, s3fs opens a temporary file // when the file is opened. // Then if it could not find a entity in map for the file, s3fs should // search a entity in all which opened the temporary file. // for(iter = fent.begin(); iter != fent.end(); ++iter){ if(iter->second && iter->second->IsOpen() && iter->second->GetPath() == from){ break; // found opened fd in mapping } } } if(fent.end() != iter){ // found S3FS_PRN_DBG("[from=%s][to=%s]", from.c_str(), to.c_str()); auto ent(std::move(iter->second)); // retrieve old fd entity from map fent.erase(iter); // rename path and caches in fd entity std::string fentmapkey; if(!ent->RenamePath(to, fentmapkey)){ S3FS_PRN_ERR("Failed to rename FdEntity object for %s to %s", from.c_str(), to.c_str()); return; } // set new fd entity to map fent[fentmapkey] = std::move(ent); } } bool FdManager::Close(FdEntity* ent, int fd) { S3FS_PRN_DBG("[ent->file=%s][pseudo_fd=%d]", ent ? ent->GetPath().c_str() : "", fd); if(!ent || -1 == fd){ return true; // returns success } const std::lock_guard<std::mutex> lock(FdManager::fd_manager_lock); UpdateEntityToTempPath(); for(auto iter = fent.cbegin(); iter != fent.cend(); ++iter){ if(iter->second.get() == ent){ ent->Close(fd); if(!ent->IsOpen()){ // remove found entity from map. iter = fent.erase(iter); // check another key name for entity value to be on the safe side for(; iter != fent.cend(); ){ if(iter->second.get() == ent){ iter = fent.erase(iter); }else{ ++iter; } } } return true; } } return false; } bool FdManager::ChangeEntityToTempPath(std::shared_ptr<FdEntity> ent, const char* path) { const std::lock_guard<std::mutex> lock(FdManager::except_entmap_lock); except_fent[path] = std::move(ent); return true; } bool FdManager::UpdateEntityToTempPath() { const std::lock_guard<std::mutex> lock(FdManager::except_entmap_lock); for(auto except_iter = except_fent.cbegin(); except_iter != except_fent.cend(); ){ std::string tmppath; FdManager::MakeRandomTempPath(except_iter->first.c_str(), tmppath); auto iter = fent.find(except_iter->first); if(fent.cend() != iter && iter->second.get() == except_iter->second.get()){ // Move the entry to the new key fent[tmppath] = std::move(iter->second); fent.erase(iter); except_iter = except_fent.erase(except_iter); }else{ // [NOTE] // ChangeEntityToTempPath method is called and the FdEntity pointer // set into except_fent is mapped into fent. // And since this method is always called before manipulating fent, // it will not enter here. // Thus, if it enters here, a warning is output. // S3FS_PRN_WARN("For some reason the FdEntity pointer(for %s) is not found in the fent map. Recovery procedures are being performed, but the cause needs to be identified.", except_iter->first.c_str()); // Add the entry for recovery procedures fent[tmppath] = except_iter->second; except_iter = except_fent.erase(except_iter); } } return true; } void FdManager::CleanupCacheDir() { //S3FS_PRN_DBG("cache cleanup requested"); if(!FdManager::IsCacheDir()){ return; } if(FdManager::cache_cleanup_lock.try_lock()){ //S3FS_PRN_DBG("cache cleanup started"); CleanupCacheDirInternal(""); //S3FS_PRN_DBG("cache cleanup ended"); }else{ // wait for other thread to finish cache cleanup FdManager::cache_cleanup_lock.lock(); } FdManager::cache_cleanup_lock.unlock(); } void FdManager::CleanupCacheDirInternal(const std::string &path) { DIR* dp; struct dirent* dent; std::string abs_path = cache_dir + "/" + S3fsCred::GetBucket() + path; if(nullptr == (dp = opendir(abs_path.c_str()))){ S3FS_PRN_ERR("could not open cache dir(%s) - errno(%d)", abs_path.c_str(), errno); return; } for(dent = readdir(dp); dent; dent = readdir(dp)){ if(0 == strcmp(dent->d_name, "..") || 0 == strcmp(dent->d_name, ".")){ continue; } std::string fullpath = abs_path; 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; } std::string next_path = path + "/" + dent->d_name; if(S_ISDIR(st.st_mode)){ CleanupCacheDirInternal(next_path); }else{ if(!FdManager::fd_manager_lock.try_lock()){ S3FS_PRN_INFO("could not get fd_manager_lock when clean up file(%s), then skip it.", next_path.c_str()); continue; } UpdateEntityToTempPath(); auto iter = fent.find(next_path); if(fent.cend() == iter) { S3FS_PRN_DBG("cleaned up: %s", next_path.c_str()); FdManager::DeleteCacheFile(next_path.c_str()); } FdManager::fd_manager_lock.unlock(); } } closedir(dp); } bool FdManager::ReserveDiskSpace(off_t size) { if(IsSafeDiskSpace(nullptr, size)){ const std::lock_guard<std::mutex> lock(FdManager::reserved_diskspace_lock); FdManager::free_disk_space += size; return true; } return false; } void FdManager::FreeReservedDiskSpace(off_t size) { const std::lock_guard<std::mutex> lock(FdManager::reserved_diskspace_lock); FdManager::free_disk_space -= size; } // // Inspect all files for stats file for cache file // // [NOTE] // The minimum sub_path parameter is "/". // The sub_path is a directory path starting from "/" and ending with "/". // // This method produces the following output. // // * Header // ------------------------------------------------------------ // Check cache file and its stats file consistency // ------------------------------------------------------------ // * When the cache file and its stats information match // File path: <file path> -> [OK] no problem // // * If there is a problem with the cache file and its stats information // File path: <file path> // -> [P] <If the problem is that parsing is not possible in the first place, the message is output here with this prefix.> // -> [E] there is a mark that data exists in stats, but there is no data in the cache file. // <offset address>(bytes) // ... // ... // -> [W] These show no data in stats, but there is evidence of data in the cache file.(no problem.) // <offset address>(bytes) // ... // ... // bool FdManager::RawCheckAllCache(FILE* fp, const char* cache_stat_top_dir, const char* sub_path, int& total_file_cnt, int& err_file_cnt, int& err_dir_cnt) { if(!cache_stat_top_dir || '\0' == cache_stat_top_dir[0] || !sub_path || '\0' == sub_path[0]){ S3FS_PRN_ERR("Parameter cache_stat_top_dir is empty."); return false; } // open directory of cache file's stats DIR* statsdir; std::string target_dir = cache_stat_top_dir; target_dir += sub_path; if(nullptr == (statsdir = opendir(target_dir.c_str()))){ S3FS_PRN_ERR("Could not open directory(%s) by errno(%d)", target_dir.c_str(), errno); return false; } // loop in directory of cache file's stats const struct dirent* pdirent = nullptr; while(nullptr != (pdirent = readdir(statsdir))){ if(DT_DIR == pdirent->d_type){ // found directory if(0 == strcmp(pdirent->d_name, ".") || 0 == strcmp(pdirent->d_name, "..")){ continue; } // reentrant for sub directory std::string subdir_path = sub_path; subdir_path += pdirent->d_name; subdir_path += '/'; if(!RawCheckAllCache(fp, cache_stat_top_dir, subdir_path.c_str(), total_file_cnt, err_file_cnt, err_dir_cnt)){ // put error message for this dir. ++err_dir_cnt; S3FS_PRN_CACHE(fp, CACHEDBG_FMT_DIR_PROB, subdir_path.c_str()); S3FS_PRN_CACHE(fp, CACHEDBG_FMT_CRIT_HEAD, "Something error is occurred in checking this directory"); } }else{ ++total_file_cnt; // make cache file path std::string strOpenedWarn; std::string cache_path; std::string object_file_path = sub_path; object_file_path += pdirent->d_name; if(!FdManager::MakeCachePath(object_file_path.c_str(), cache_path, false, false) || cache_path.empty()){ ++err_file_cnt; S3FS_PRN_CACHE(fp, CACHEDBG_FMT_FILE_PROB, object_file_path.c_str(), strOpenedWarn.c_str()); S3FS_PRN_CACHE(fp, CACHEDBG_FMT_CRIT_HEAD, "Could not make cache file path"); continue; } // check if the target file is currently in operation. { const std::lock_guard<std::mutex> lock(FdManager::fd_manager_lock); UpdateEntityToTempPath(); auto iter = fent.find(object_file_path); if(fent.cend() != iter){ // This file is opened now, then we need to put warning message. strOpenedWarn = CACHEDBG_FMT_WARN_OPEN; } } // open cache file int cache_file_fd; if(-1 == (cache_file_fd = open(cache_path.c_str(), O_RDONLY))){ ++err_file_cnt; S3FS_PRN_CACHE(fp, CACHEDBG_FMT_FILE_PROB, object_file_path.c_str(), strOpenedWarn.c_str()); S3FS_PRN_CACHE(fp, CACHEDBG_FMT_CRIT_HEAD, "Could not open cache file"); continue; } scope_guard guard([&]() { close(cache_file_fd); }); // get inode number for cache file struct stat st; if(0 != fstat(cache_file_fd, &st)){ ++err_file_cnt; S3FS_PRN_CACHE(fp, CACHEDBG_FMT_FILE_PROB, object_file_path.c_str(), strOpenedWarn.c_str()); S3FS_PRN_CACHE(fp, CACHEDBG_FMT_CRIT_HEAD, "Could not get file inode number for cache file"); continue; } ino_t cache_file_inode = st.st_ino; // open cache stat file and load page info. PageList pagelist; CacheFileStat cfstat(object_file_path.c_str()); if(!cfstat.ReadOnlyOpen() || !pagelist.Deserialize(cfstat, cache_file_inode)){ ++err_file_cnt; S3FS_PRN_CACHE(fp, CACHEDBG_FMT_FILE_PROB, object_file_path.c_str(), strOpenedWarn.c_str()); S3FS_PRN_CACHE(fp, CACHEDBG_FMT_CRIT_HEAD, "Could not load cache file stats information"); continue; } cfstat.Release(); // compare cache file size and stats information if(st.st_size != pagelist.Size()){ ++err_file_cnt; S3FS_PRN_CACHE(fp, CACHEDBG_FMT_FILE_PROB, object_file_path.c_str(), strOpenedWarn.c_str()); S3FS_PRN_CACHE(fp, CACHEDBG_FMT_CRIT_HEAD2 "The cache file size(%lld) and the value(%lld) from cache file stats are different", static_cast<long long int>(st.st_size), static_cast<long long int>(pagelist.Size())); continue; } // compare cache file stats and cache file blocks fdpage_list_t err_area_list; fdpage_list_t warn_area_list; if(!pagelist.CompareSparseFile(cache_file_fd, st.st_size, err_area_list, warn_area_list)){ // Found some error or warning S3FS_PRN_CACHE(fp, CACHEDBG_FMT_FILE_PROB, object_file_path.c_str(), strOpenedWarn.c_str()); if(!warn_area_list.empty()){ S3FS_PRN_CACHE(fp, CACHEDBG_FMT_WARN_HEAD); for(auto witer = warn_area_list.cbegin(); witer != warn_area_list.cend(); ++witer){ S3FS_PRN_CACHE(fp, CACHEDBG_FMT_PROB_BLOCK, static_cast<size_t>(witer->offset), static_cast<size_t>(witer->bytes)); } } if(!err_area_list.empty()){ ++err_file_cnt; S3FS_PRN_CACHE(fp, CACHEDBG_FMT_ERR_HEAD); for(auto eiter = err_area_list.cbegin(); eiter != err_area_list.cend(); ++eiter){ S3FS_PRN_CACHE(fp, CACHEDBG_FMT_PROB_BLOCK, static_cast<size_t>(eiter->offset), static_cast<size_t>(eiter->bytes)); } } }else{ // There is no problem! if(!strOpenedWarn.empty()){ strOpenedWarn += "\n "; } S3FS_PRN_CACHE(fp, CACHEDBG_FMT_FILE_OK, object_file_path.c_str(), strOpenedWarn.c_str()); } err_area_list.clear(); warn_area_list.clear(); } } closedir(statsdir); return true; } bool FdManager::CheckAllCache() { if(!FdManager::HaveLseekHole()){ S3FS_PRN_ERR("lseek does not support SEEK_DATA/SEEK_HOLE, then could not check cache."); return false; } std::unique_ptr<FILE, decltype(&s3fs_fclose)> pfp(nullptr, &s3fs_fclose); FILE* fp; if(FdManager::check_cache_output.empty()){ fp = stdout; }else{ pfp.reset(fp = fopen(FdManager::check_cache_output.c_str(), "a+")); if(nullptr == pfp){ S3FS_PRN_ERR("Could not open(create) output file(%s) for checking all cache by errno(%d)", FdManager::check_cache_output.c_str(), errno); return false; } } // print head message S3FS_PRN_CACHE(fp, CACHEDBG_FMT_HEAD, S3fsLog::GetCurrentTime().c_str()); // Loop in directory of cache file's stats std::string top_path = CacheFileStat::GetCacheFileStatTopDir(); int total_file_cnt = 0; int err_file_cnt = 0; int err_dir_cnt = 0; bool result = RawCheckAllCache(fp, top_path.c_str(), "/", total_file_cnt, err_file_cnt, err_dir_cnt); if(!result){ S3FS_PRN_ERR("Processing failed due to some problem."); } // print foot message S3FS_PRN_CACHE(fp, CACHEDBG_FMT_FOOT, total_file_cnt, err_file_cnt, err_dir_cnt); return result; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
36,959
C++
.cpp
951
31.460568
285
0.577354
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,462
mknod_test.cc
s3fs-fuse_s3fs-fuse/test/mknod_test.cc
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2021 Andrew Gaul <andrew@gaul.org> * * 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 <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #if !defined(__APPLE__) && !defined(__FreeBSD__) #include <sys/sysmacros.h> #endif //--------------------------------------------------------- // Const //--------------------------------------------------------- static constexpr char usage_string[] = "Usage : \"mknod_test <base file path>\""; static constexpr char str_mode_reg[] = "REGULAR"; static constexpr char str_mode_chr[] = "CHARACTER"; static constexpr char str_mode_blk[] = "BLOCK"; static constexpr char str_mode_fifo[] = "FIFO"; static constexpr char str_mode_sock[] = "SOCK"; static constexpr char str_ext_reg[] = "reg"; static constexpr char str_ext_chr[] = "chr"; static constexpr char str_ext_blk[] = "blk"; static constexpr char str_ext_fifo[] = "fifo"; static constexpr char str_ext_sock[] = "sock"; // [NOTE] // It would be nice if PATH_MAX could be used as is, but since there are // issues using on Linux and we also must support for macos, this simple // test program defines a fixed value for simplicity. // static constexpr size_t S3FS_TEST_PATH_MAX = 255; static constexpr size_t MAX_BASE_PATH_LENGTH = S3FS_TEST_PATH_MAX - 5; //--------------------------------------------------------- // Test function //--------------------------------------------------------- bool TestMknod(const char* basepath, mode_t mode) { if(!basepath){ fprintf(stderr, "[ERROR] Called function with wrong basepath argument.\n"); return false; } const char* str_mode; dev_t dev; char filepath[S3FS_TEST_PATH_MAX]; switch(mode){ case S_IFREG: str_mode = str_mode_reg; dev = 0; snprintf(filepath, sizeof(filepath), "%s.%s", basepath, str_ext_reg); filepath[S3FS_TEST_PATH_MAX - 1] = '\0'; // for safety break; case S_IFCHR: str_mode = str_mode_chr; dev = makedev(0, 0); snprintf(filepath, sizeof(filepath), "%s.%s", basepath, str_ext_chr); filepath[S3FS_TEST_PATH_MAX - 1] = '\0'; // for safety break; case S_IFBLK: str_mode = str_mode_blk; dev = makedev((unsigned int)(259), 0); // temporary value snprintf(filepath, sizeof(filepath), "%s.%s", basepath, str_ext_blk); filepath[S3FS_TEST_PATH_MAX - 1] = '\0'; // for safety break; case S_IFIFO: str_mode = str_mode_fifo; dev = 0; snprintf(filepath, sizeof(filepath), "%s.%s", basepath, str_ext_fifo); filepath[S3FS_TEST_PATH_MAX - 1] = '\0'; // for safety break; case S_IFSOCK: str_mode = str_mode_sock; dev = 0; snprintf(filepath, sizeof(filepath), "%s.%s", basepath, str_ext_sock); filepath[S3FS_TEST_PATH_MAX - 1] = '\0'; // for safety break; default: fprintf(stderr, "[ERROR] Called function with wrong mode argument.\n"); return false; } // // Create // if(0 != mknod(filepath, mode | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH, dev)){ fprintf(stderr, "[ERROR] Could not create %s file(%s) : errno = %d\n", str_mode, filepath, errno); return false; } // // Check // struct stat st; if(0 != stat(filepath, &st)){ fprintf(stderr, "[ERROR] Could not get stat from %s file(%s) : errno = %d\n", str_mode, filepath, errno); return false; } if(mode != (st.st_mode & S_IFMT)){ fprintf(stderr, "[ERROR] Created %s file(%s) does not have 0%o stat\n", str_mode, filepath, mode); return false; } // // Remove // if(0 != unlink(filepath)){ fprintf(stderr, "[WARNING] Could not remove %s file(%s) : errno = %d\n", str_mode, filepath, mode); } return true; } //--------------------------------------------------------- // Main //--------------------------------------------------------- int main(int argc, const char *argv[]) { // Parse parameters if(2 != argc){ fprintf(stderr, "[ERROR] No parameter is specified.\n"); fprintf(stderr, "%s\n", usage_string); exit(EXIT_FAILURE); } if(0 == strcmp("-h", argv[1]) || 0 == strcmp("--help", argv[1])){ fprintf(stdout, "%s\n", usage_string); exit(EXIT_SUCCESS); } if(MAX_BASE_PATH_LENGTH < strlen(argv[1])){ fprintf(stderr, "[ERROR] Base file path is too long, it must be less than %zu\n", MAX_BASE_PATH_LENGTH); exit(EXIT_FAILURE); } // Test // // [NOTE] // Privilege is required to execute S_IFBLK. // if(0 != geteuid()){ fprintf(stderr, "[WARNING] Skipping mknod(S_IFBLK) due to missing root privileges.\n"); } if(!TestMknod(argv[1], S_IFREG) || !TestMknod(argv[1], S_IFCHR) || !TestMknod(argv[1], S_IFIFO) || !TestMknod(argv[1], S_IFSOCK) || (0 == geteuid() && !TestMknod(argv[1], S_IFBLK))) { exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
6,207
C++
.cc
170
31.088235
113
0.572472
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,463
junk_data.cc
s3fs-fuse_s3fs-fuse/test/junk_data.cc
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2021 Andrew Gaul <andrew@gaul.org> * * 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. */ // Generate junk data at high speed. An alternative to dd if=/dev/urandom. #include <cstdint> #include <cstdio> #include <cstdlib> int main(int argc, const char *argv[]) { if (argc != 2) { return 1; } uint64_t count = strtoull(argv[1], nullptr, 10); char buf[128 * 1024]; for (uint64_t i = 0; i < count; i += sizeof(buf)) { for (uint64_t j = 0; j < sizeof(buf) / sizeof(i); ++j) { *(reinterpret_cast<uint64_t *>(buf) + j) = i / sizeof(i) + j; } fwrite(buf, 1, sizeof(buf) > count - i ? count - i : sizeof(buf), stdout); } return 0; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
1,586
C++
.cc
46
31.434783
82
0.677734
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,464
cr_filename.cc
s3fs-fuse_s3fs-fuse/test/cr_filename.cc
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2021 Andrew Gaul <andrew@gaul.org> * * 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 <cstdio> #include <cstdlib> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> // [NOTE] // This is a program used for file size inspection. // File size checking should be done by the caller of this program. // This program truncates the file and reads the file in another process // between truncate and flush(close file). // int main(int argc, const char *argv[]) { if(argc != 2){ fprintf(stderr, "[ERROR] Wrong paraemters\n"); fprintf(stdout, "[Usage] cr_filename <base file path>\n"); exit(EXIT_FAILURE); } int fd; char filepath[4096]; snprintf(filepath, sizeof(filepath), "%s\r", argv[1]); filepath[sizeof(filepath) - 1] = '\0'; // for safety // create empty file if(-1 == (fd = open(filepath, O_CREAT|O_RDWR, 0644))){ fprintf(stderr, "[ERROR] Could not open file(%s)\n", filepath); exit(EXIT_FAILURE); } close(fd); // stat struct stat buf; if(0 != stat(filepath, &buf)){ fprintf(stderr, "[ERROR] Could not get stat for file(%s)\n", filepath); exit(EXIT_FAILURE); } // remove file if(0 != unlink(filepath)){ fprintf(stderr, "[ERROR] Could not remove file(%s)\n", filepath); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,307
C++
.cc
69
29.971014
82
0.67713
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,465
truncate_read_file.cc
s3fs-fuse_s3fs-fuse/test/truncate_read_file.cc
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2021 Andrew Gaul <andrew@gaul.org> * * 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 <cstdio> #include <cstdlib> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> // [NOTE] // This is a program used for file size inspection. // File size checking should be done by the caller of this program. // This program truncates the file and reads the file in another process // between truncate and flush(close file). // int main(int argc, const char *argv[]) { if(argc != 3){ fprintf(stderr, "[ERROR] Wrong paraemters\n"); fprintf(stdout, "[Usage] truncate_read_file <file path> <truncate size(bytes)>\n"); exit(EXIT_FAILURE); } const char* filepath = argv[1]; auto size = static_cast<off_t>(strtoull(argv[2], nullptr, 10)); int fd; // open file if(-1 == (fd = open(filepath, O_RDWR))){ fprintf(stderr, "[ERROR] Could not open file(%s)\n", filepath); exit(EXIT_FAILURE); } // truncate if(0 != ftruncate(fd, size)){ fprintf(stderr, "[ERROR] Could not truncate file(%s) to %lld byte.\n", filepath, (long long)size); close(fd); exit(EXIT_FAILURE); } // run sub-process for reading file(cat) char szCommand[1024]; snprintf(szCommand, sizeof(szCommand), "cat %s >/dev/null 2>&1", filepath); szCommand[sizeof(szCommand) - 1] = '\0'; // for safety if(0 != system(szCommand)){ fprintf(stderr, "[ERROR] Failed to run sub-process(cat).\n"); close(fd); exit(EXIT_FAILURE); } // close file(flush) close(fd); exit(EXIT_SUCCESS); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,558
C++
.cc
73
31.369863
106
0.667609
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,466
write_multiblock.cc
s3fs-fuse_s3fs-fuse/test/write_multiblock.cc
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <climits> #include <list> #include <memory> #include <string> #include <vector> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> //--------------------------------------------------------- // Structures and Typedefs //--------------------------------------------------------- struct write_block_part { off_t start; off_t size; }; typedef std::vector<write_block_part> wbpart_list_t; typedef std::list<std::string> strlist_t; //--------------------------------------------------------- // Const //--------------------------------------------------------- static constexpr char usage_string[] = "Usage : \"write_multiblock -f <file path> -p <start offset:size>\" (allows -f and -p multiple times.)"; //--------------------------------------------------------- // Utility functions //--------------------------------------------------------- static std::unique_ptr<unsigned char[]> create_random_data(off_t size) { int fd; if(-1 == (fd = open("/dev/urandom", O_RDONLY))){ std::cerr << "[ERROR] Could not open /dev/urandom" << std::endl; return nullptr; } std::unique_ptr<unsigned char[]> pbuff(new unsigned char[size]); for(ssize_t readpos = 0, readcnt = 0; readpos < size; readpos += readcnt){ if(-1 == (readcnt = read(fd, &(pbuff[readpos]), static_cast<size_t>(size - readpos)))){ if(EAGAIN != errno && EWOULDBLOCK != errno && EINTR != errno){ std::cerr << "[ERROR] Failed reading from /dev/urandom with errno: " << errno << std::endl; close(fd); return nullptr; } readcnt = 0; } } close(fd); return pbuff; } static off_t cvt_string_to_number(const char* pstr) { if(!pstr){ return -1; } errno = 0; char* ptemp = nullptr; long long result = strtoll(pstr, &ptemp, 10); if(!ptemp || ptemp == pstr || *ptemp != '\0'){ return -1; } if((result == LLONG_MIN || result == LLONG_MAX) && errno == ERANGE){ return -1; } return static_cast<off_t>(result); } static bool parse_string(const char* pstr, char delim, strlist_t& strlist) { if(!pstr){ return false; } std::string strAll(pstr); while(!strAll.empty()){ size_t pos = strAll.find_first_of(delim); if(std::string::npos != pos){ strlist.push_back(strAll.substr(0, pos)); strAll = strAll.substr(pos + 1); }else{ strlist.push_back(strAll); strAll.clear(); } } return true; } static bool parse_write_blocks(const char* pstr, wbpart_list_t& wbparts, off_t& max_size) { if(!pstr){ return false; } strlist_t partlist; if(!parse_string(pstr, ',', partlist)){ return false; } for(auto iter = partlist.cbegin(); iter != partlist.cend(); ++iter){ strlist_t partpair; if(parse_string(iter->c_str(), ':', partpair) && 2 == partpair.size()){ write_block_part tmp_part; tmp_part.start = cvt_string_to_number(partpair.front().c_str()); partpair.pop_front(); tmp_part.size = cvt_string_to_number(partpair.front().c_str()); if(tmp_part.start < 0 || tmp_part.size <= 0){ std::cerr << "[ERROR] -p option parameter(" << pstr << ") is something wrong." << std::endl; return false; } max_size = std::max(max_size, tmp_part.size); wbparts.push_back(tmp_part); }else{ std::cerr << "[ERROR] -p option parameter(" << pstr << ") is something wrong." << std::endl; return false; } } return true; } static bool parse_arguments(int argc, char** argv, strlist_t& files, wbpart_list_t& wbparts, off_t& max_size) { if(argc < 2 || !argv){ std::cerr << "[ERROR] The -f option and -p option are required as arguments." << std::endl; std::cerr << usage_string << std::endl; return false; } files.clear(); wbparts.clear(); max_size = 0; int opt; while(-1 != (opt = getopt(argc, argv, "f:p:"))){ switch(opt){ case 'f': files.emplace_back(optarg); break; case 'p': if(!parse_write_blocks(optarg, wbparts, max_size)){ return false; } break; default: std::cerr << usage_string << std::endl; return false; } } if(files.empty() || wbparts.empty()){ std::cerr << "[ERROR] The -f option and -p option are required as arguments." << std::endl; std::cerr << usage_string << std::endl; return false; } return true; } //--------------------------------------------------------- // Main //--------------------------------------------------------- int main(int argc, char** argv) { // parse arguments strlist_t files; wbpart_list_t wbparts; off_t max_size = 0; if(!parse_arguments(argc, argv, files, wbparts, max_size)){ exit(EXIT_FAILURE); } // make data and buffer std::unique_ptr<unsigned char[]> pData = create_random_data(max_size); for(auto fiter = files.cbegin(); fiter != files.cend(); ++fiter){ // open/create file int fd; struct stat st; if(0 == stat(fiter->c_str(), &st)){ if(!S_ISREG(st.st_mode)){ std::cerr << "[ERROR] File " << *fiter << " is existed, but it is not regular file." << std::endl; exit(EXIT_FAILURE); } if(-1 == (fd = open(fiter->c_str(), O_WRONLY))){ std::cerr << "[ERROR] Could not open " << *fiter << std::endl; exit(EXIT_FAILURE); } }else{ if(-1 == (fd = open(fiter->c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644))){ std::cerr << "[ERROR] Could not create " << *fiter << std::endl; exit(EXIT_FAILURE); } } // write blocks for(auto piter = wbparts.cbegin(); piter != wbparts.cend(); ++piter){ // write one block for(ssize_t writepos = 0, writecnt = 0; writepos < piter->size; writepos += writecnt){ if(-1 == (writecnt = pwrite(fd, &(pData[writepos]), static_cast<size_t>(piter->size - writepos), (piter->start + writepos)))){ if(EAGAIN != errno && EWOULDBLOCK != errno && EINTR != errno){ std::cerr << "[ERROR] Failed writing to " << *fiter << " by errno : " << errno << std::endl; close(fd); exit(EXIT_FAILURE); } writecnt = 0; } } } // close file close(fd); } exit(EXIT_SUCCESS); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
8,037
C++
.cc
227
28.264317
143
0.526857
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
18,467
fdcache_fdinfo.h
s3fs-fuse_s3fs-fuse/src/fdcache_fdinfo.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_FDCACHE_FDINFO_H_ #define S3FS_FDCACHE_FDINFO_H_ #include <memory> #include <mutex> #include <string> #include "common.h" #include "fdcache_entity.h" #include "psemaphore.h" #include "metaheader.h" #include "types.h" class UntreatedParts; //------------------------------------------------ // Class PseudoFdInfo //------------------------------------------------ class PseudoFdInfo { private: int pseudo_fd; int physical_fd; int flags; // flags at open mutable std::mutex upload_list_lock; // protects upload_id/fd, upload_list, etc. std::string upload_id GUARDED_BY(upload_list_lock); // int upload_fd GUARDED_BY(upload_list_lock); // duplicated fd for uploading filepart_list_t upload_list GUARDED_BY(upload_list_lock); petagpool etag_entities GUARDED_BY(upload_list_lock); // list of etag string and part number entities(to maintain the etag entity even if MPPART_INFO is destroyed) int instruct_count GUARDED_BY(upload_list_lock); // number of instructions for processing by threads int completed_count GUARDED_BY(upload_list_lock); // number of completed processes by thread int last_result GUARDED_BY(upload_list_lock); // the result of thread processing Semaphore uploaded_sem; // use a semaphore to trigger an upload completion like event flag private: static void* MultipartUploadThreadWorker(void* arg); bool Clear(); void CloseUploadFd(); bool OpenUploadFd(); bool ResetUploadInfo() REQUIRES(upload_list_lock); bool RowInitialUploadInfo(const std::string& id, bool is_cancel_mp); void IncreaseInstructionCount(); bool CompleteInstruction(int result) REQUIRES(upload_list_lock); bool GetUploadInfo(std::string& id, int& fd) const; bool ParallelMultipartUpload(const char* path, const mp_part_list_t& mplist, bool is_copy); bool InsertUploadPart(off_t start, off_t size, int part_num, bool is_copy, etagpair** ppetag); bool PreMultipartUploadRequest(const std::string& strpath, const headers_t& meta); bool CancelAllThreads(); bool ExtractUploadPartsFromUntreatedArea(off_t untreated_start, off_t untreated_size, mp_part_list_t& to_upload_list, filepart_list_t& cancel_upload_list, off_t max_mp_size); bool IsUploadingHasLock() const REQUIRES(upload_list_lock); public: explicit PseudoFdInfo(int fd = -1, int open_flags = 0); ~PseudoFdInfo(); PseudoFdInfo(const PseudoFdInfo&) = delete; PseudoFdInfo(PseudoFdInfo&&) = delete; PseudoFdInfo& operator=(const PseudoFdInfo&) = delete; PseudoFdInfo& operator=(PseudoFdInfo&&) = delete; int GetPhysicalFd() const { return physical_fd; } int GetPseudoFd() const { return pseudo_fd; } int GetFlags() const { return flags; } bool Writable() const; bool Readable() const; bool Set(int fd, int open_flags); bool ClearUploadInfo(bool is_cancel_mp = false); bool InitialUploadInfo(const std::string& id){ return RowInitialUploadInfo(id, true); } bool IsUploading() const; bool GetUploadId(std::string& id) const; bool GetEtaglist(etaglist_t& list) const; bool AppendUploadPart(off_t start, off_t size, bool is_copy = false, etagpair** ppetag = nullptr); bool ParallelMultipartUploadAll(const char* path, const mp_part_list_t& to_upload_list, const mp_part_list_t& copy_list, int& result); int WaitAllThreadsExit(); ssize_t UploadBoundaryLastUntreatedArea(const char* path, headers_t& meta, FdEntity* pfdent) REQUIRES(pfdent->GetMutex()); bool ExtractUploadPartsFromAllArea(UntreatedParts& untreated_list, mp_part_list_t& to_upload_list, mp_part_list_t& to_copy_list, mp_part_list_t& to_download_list, filepart_list_t& cancel_upload_list, bool& wait_upload_complete, off_t max_mp_size, off_t file_size, bool use_copy); }; typedef std::map<int, std::unique_ptr<PseudoFdInfo>> fdinfo_map_t; #endif // S3FS_FDCACHE_FDINFO_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
5,354
C++
.h
98
49.153061
287
0.662149
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,468
mpu_util.h
s3fs-fuse_s3fs-fuse/src/mpu_util.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_MPU_UTIL_H_ #define S3FS_MPU_UTIL_H_ #include <cstdint> #include <ctime> #include <string> #include <vector> //------------------------------------------------------------------- // Structure / Typedef //------------------------------------------------------------------- typedef struct incomplete_multipart_upload_info { std::string key; std::string id; std::string date; }INCOMP_MPU_INFO; typedef std::vector<INCOMP_MPU_INFO> incomp_mpu_list_t; //------------------------------------------------------------------- // enum for utility process mode //------------------------------------------------------------------- enum class utility_incomp_type : uint8_t { NO_UTILITY_MODE = 0, // not utility mode INCOMP_TYPE_LIST, // list of incomplete mpu INCOMP_TYPE_ABORT // delete incomplete mpu }; extern utility_incomp_type utility_mode; //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- int s3fs_utility_processing(time_t abort_time); #endif // S3FS_MPU_UTIL_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,106
C++
.h
57
35.052632
82
0.587255
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,469
s3fs_xml.h
s3fs-fuse_s3fs-fuse/src/s3fs_xml.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_XML_H_ #define S3FS_S3FS_XML_H_ #include <libxml/xpath.h> #include <libxml/parser.h> // [NOTE] nessetially include this header in some environments #include <memory> #include <string> #include "mpu_util.h" class S3ObjList; typedef std::unique_ptr<xmlChar, decltype(xmlFree)> unique_ptr_xmlChar; typedef std::unique_ptr<xmlXPathObject, decltype(&xmlXPathFreeObject)> unique_ptr_xmlXPathObject; typedef std::unique_ptr<xmlXPathContext, decltype(&xmlXPathFreeContext)> unique_ptr_xmlXPathContext; typedef std::unique_ptr<xmlDoc, decltype(&xmlFreeDoc)> unique_ptr_xmlDoc; //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- bool is_truncated(xmlDocPtr doc); 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, bool prefix); int append_objects_from_xml(const char* path, xmlDocPtr doc, S3ObjList& head); unique_ptr_xmlChar get_next_continuation_token(xmlDocPtr doc); unique_ptr_xmlChar get_next_marker(xmlDocPtr doc); bool get_incomp_mpu_list(xmlDocPtr doc, incomp_mpu_list_t& list); bool simple_parse_xml(const char* data, size_t len, const char* key, std::string& value); #endif // S3FS_S3FS_XML_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,335
C++
.h
50
45.16
199
0.724077
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,470
fdcache_entity.h
s3fs-fuse_s3fs-fuse/src/fdcache_entity.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_FDCACHE_ENTITY_H_ #define S3FS_FDCACHE_ENTITY_H_ #include <cstdint> #include <fcntl.h> #include <memory> #include <mutex> #include <string> #include "common.h" #include "fdcache_page.h" #include "fdcache_untreated.h" #include "metaheader.h" #include "s3fs_util.h" //---------------------------------------------- // Typedef //---------------------------------------------- class PseudoFdInfo; typedef std::map<int, std::unique_ptr<PseudoFdInfo>> fdinfo_map_t; //------------------------------------------------ // class FdEntity //------------------------------------------------ class FdEntity : public std::enable_shared_from_this<FdEntity> { private: // [NOTE] // Distinguish between meta pending and new file creation pending, // because the processing(request) at these updates is different. // Therefore, the pending state is expressed by this enum type. // enum class pending_status_t : uint8_t { NO_UPDATE_PENDING = 0, UPDATE_META_PENDING, // pending meta header CREATE_FILE_PENDING // pending file creation and meta header }; static bool mixmultipart; // whether multipart uploading can use copy api. static bool streamupload; // whether stream uploading. mutable std::mutex fdent_lock; std::string path GUARDED_BY(fdent_lock); // object path int physical_fd GUARDED_BY(fdent_lock); // physical file(cache or temporary file) descriptor UntreatedParts untreated_list GUARDED_BY(fdent_lock); // list of untreated parts that have been written and not yet uploaded(for streamupload) fdinfo_map_t pseudo_fd_map GUARDED_BY(fdent_lock); // pseudo file descriptor information map std::unique_ptr<FILE, decltype(&s3fs_fclose)> pfile GUARDED_BY(fdent_lock) = {nullptr, &s3fs_fclose}; // file pointer(tmp file or cache file) ino_t inode GUARDED_BY(fdent_lock); // inode number for cache file headers_t orgmeta GUARDED_BY(fdent_lock); // original headers at opening off_t size_orgmeta GUARDED_BY(fdent_lock); // original file size in original headers mutable std::mutex fdent_data_lock ACQUIRED_AFTER(fdent_lock);// protects the following members PageList pagelist GUARDED_BY(fdent_data_lock); std::string cachepath GUARDED_BY(fdent_data_lock); // local cache file path // (if this is empty, does not load/save pagelist.) std::string mirrorpath GUARDED_BY(fdent_data_lock); // mirror file path to local cache file path pending_status_t pending_status GUARDED_BY(fdent_data_lock); // status for new file creation and meta update struct timespec holding_mtime GUARDED_BY(fdent_data_lock); // if mtime is updated while the file is open, it is set time_t value private: static int FillFile(int fd, unsigned char byte, off_t size, off_t start); static ino_t GetInode(int fd); static void* MultipartUploadThreadWorker(void* arg); // ([TODO] This is a temporary method is moved when S3fsMultiCurl is deprecated.) void Clear(); ino_t GetInode() const REQUIRES(FdEntity::fdent_data_lock); int OpenMirrorFile() REQUIRES(FdEntity::fdent_data_lock); int NoCacheLoadAndPost(PseudoFdInfo* pseudo_obj, off_t start = 0, off_t size = 0) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); // size=0 means loading to end PseudoFdInfo* CheckPseudoFdFlags(int fd, bool writable) REQUIRES(FdEntity::fdent_lock); bool IsUploading() REQUIRES(FdEntity::fdent_lock); bool SetAllStatus(bool is_loaded) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); bool SetAllStatusUnloaded() REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock) { return SetAllStatus(false); } int PreMultipartUploadRequest(PseudoFdInfo* pseudo_obj) REQUIRES(FdEntity::fdent_lock, fdent_data_lock); int NoCachePreMultipartUploadRequest(PseudoFdInfo* pseudo_obj) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); int NoCacheMultipartUploadRequest(PseudoFdInfo* pseudo_obj, int tgfd, off_t start, off_t size) REQUIRES(FdEntity::fdent_lock); int NoCacheMultipartUploadComplete(PseudoFdInfo* pseudo_obj) REQUIRES(FdEntity::fdent_lock); int RowFlushHasLock(int fd, const char* tpath, bool force_sync) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); int RowFlushNoMultipart(const PseudoFdInfo* pseudo_obj, const char* tpath) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); int RowFlushMultipart(PseudoFdInfo* pseudo_obj, const char* tpath) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); int RowFlushMixMultipart(PseudoFdInfo* pseudo_obj, const char* tpath) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); int RowFlushStreamMultipart(PseudoFdInfo* pseudo_obj, const char* tpath) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); ssize_t WriteNoMultipart(const PseudoFdInfo* pseudo_obj, const char* bytes, off_t start, size_t size) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); ssize_t WriteMultipart(PseudoFdInfo* pseudo_obj, const char* bytes, off_t start, size_t size) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); ssize_t WriteMixMultipart(PseudoFdInfo* pseudo_obj, const char* bytes, off_t start, size_t size) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); ssize_t WriteStreamUpload(PseudoFdInfo* pseudo_obj, const char* bytes, off_t start, size_t size) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); int UploadPendingHasLock(int fd) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); bool ReserveDiskSpace(off_t size) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); bool AddUntreated(off_t start, off_t size) REQUIRES(FdEntity::fdent_lock); bool IsDirtyMetadata() const REQUIRES(FdEntity::fdent_data_lock); std::shared_ptr<FdEntity> get_shared_ptr() { return shared_from_this(); } public: static bool GetNoMixMultipart() { return mixmultipart; } static bool SetNoMixMultipart(); static bool GetStreamUpload() { return streamupload; } static bool SetStreamUpload(bool isstream); explicit FdEntity(const char* tpath = nullptr, const char* cpath = nullptr); ~FdEntity(); FdEntity(const FdEntity&) = delete; FdEntity(FdEntity&&) = delete; FdEntity& operator=(const FdEntity&) = delete; FdEntity& operator=(FdEntity&&) = delete; void Close(int fd); bool IsOpen() const { const std::lock_guard<std::mutex> lock(fdent_lock); return (-1 != physical_fd); } bool FindPseudoFd(int fd) const { const std::lock_guard<std::mutex> lock(fdent_lock); return FindPseudoFdWithLock(fd); } bool FindPseudoFdWithLock(int fd) const REQUIRES(FdEntity::fdent_lock); int Open(const headers_t* pmeta, off_t size, const struct timespec& ts_mctime, int flags); bool LoadAll(int fd, off_t* size = nullptr, bool force_load = false); int Dup(int fd) { const std::lock_guard<std::mutex> lock(fdent_lock); return DupWithLock(fd); } int DupWithLock(int fd) REQUIRES(FdEntity::fdent_lock); int OpenPseudoFd(int flags = O_RDONLY); int GetOpenCount() const { const std::lock_guard<std::mutex> lock(fdent_lock); return GetOpenCountHasLock(); } int GetOpenCountHasLock() const REQUIRES(FdEntity::fdent_lock); std::string GetPath() const { const std::lock_guard<std::mutex> lock(fdent_lock); return path; } bool RenamePath(const std::string& newpath, std::string& fentmapkey); int GetPhysicalFd() const REQUIRES(FdEntity::fdent_lock) { return physical_fd; } bool IsModified() const; bool MergeOrgMeta(headers_t& updatemeta); int UploadPending(int fd) { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> lock_data(fdent_data_lock); return UploadPendingHasLock(fd); } bool GetStats(struct stat& st) const { const std::lock_guard<std::mutex> lock(fdent_lock); return GetStatsHasLock(st); } bool GetStatsHasLock(struct stat& st) const REQUIRES(FdEntity::fdent_lock); int SetCtime(struct timespec time) { const std::lock_guard<std::mutex> lock(fdent_lock); return SetCtimeHasLock(time); } int SetCtimeHasLock(struct timespec time) REQUIRES(FdEntity::fdent_lock); int SetAtime(struct timespec time) { const std::lock_guard<std::mutex> lock(fdent_lock); return SetAtimeHasLock(time); } int SetAtimeHasLock(struct timespec time) REQUIRES(FdEntity::fdent_lock); int SetMCtime(struct timespec mtime, struct timespec ctime) { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> lock2(fdent_data_lock); return SetMCtimeHasLock(mtime, ctime); } int SetMCtimeHasLock(struct timespec mtime, struct timespec ctime) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); bool UpdateCtime(); bool UpdateAtime(); bool UpdateMtime(bool clear_holding_mtime = false); bool UpdateMCtime(); bool SetHoldingMtime(struct timespec mtime); bool ClearHoldingMtime() REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); bool GetSize(off_t& size) const; bool GetXattr(std::string& xattr) const; bool SetXattr(const std::string& xattr); bool SetMode(mode_t mode) { const std::lock_guard<std::mutex> lock(fdent_lock); return SetModeHasLock(mode); } bool SetModeHasLock(mode_t mode) REQUIRES(FdEntity::fdent_lock); bool SetUId(uid_t uid) { const std::lock_guard<std::mutex> lock(fdent_lock); return SetUIdHasLock(uid); } bool SetUIdHasLock(uid_t uid) REQUIRES(FdEntity::fdent_lock); bool SetGId(gid_t gid) { const std::lock_guard<std::mutex> lock(fdent_lock); return SetGIdHasLock(gid); } bool SetGIdHasLock(gid_t gid) REQUIRES(FdEntity::fdent_lock); bool SetContentType(const char* path); int Load(off_t start, off_t size, bool is_modified_flag = false) REQUIRES(FdEntity::fdent_lock, FdEntity::fdent_data_lock); // size=0 means loading to end off_t BytesModified(); int RowFlush(int fd, const char* tpath, bool force_sync = false) { const std::lock_guard<std::mutex> lock(fdent_lock); const std::lock_guard<std::mutex> lock_data(fdent_data_lock); return RowFlushHasLock(fd, tpath, force_sync); } int Flush(int fd, bool force_sync = false) { return RowFlush(fd, nullptr, force_sync); } ssize_t Read(int fd, char* bytes, off_t start, size_t size, bool force_load = false); ssize_t Write(int fd, const char* bytes, off_t start, size_t size); bool PunchHole(off_t start = 0, size_t size = 0); void MarkDirtyNewFile(); bool IsDirtyNewFile() const; void MarkDirtyMetadata(); bool GetLastUpdateUntreatedPart(off_t& start, off_t& size) const REQUIRES(FdEntity::fdent_lock); bool ReplaceLastUpdateUntreatedPart(off_t front_start, off_t front_size, off_t behind_start, off_t behind_size) REQUIRES(FdEntity::fdent_lock); // Intentionally unimplemented -- for lock checking only. std::mutex* GetMutex() RETURN_CAPABILITY(fdent_lock); }; typedef std::map<std::string, std::shared_ptr<FdEntity>> fdent_map_t; // key=path, value=FdEntity #endif // S3FS_FDCACHE_ENTITY_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
13,265
C++
.h
225
50.751111
182
0.661287
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,471
s3fs_cred.h
s3fs-fuse_s3fs-fuse/src/s3fs_cred.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_CRED_H_ #define S3FS_CRED_H_ #include <map> #include <mutex> #include <string> #include "common.h" #include "s3fs_extcred.h" #include "types.h" //---------------------------------------------- // Typedefs //---------------------------------------------- typedef std::map<std::string, std::string> iamcredmap_t; //------------------------------------------------ // class S3fsCred //------------------------------------------------ // This is a class for operating and managing Credentials(accesskey, // secret key, tokens, etc.) used by S3fs. // Operations related to Credentials are aggregated in this class. // // cppcheck-suppress ctuOneDefinitionRuleViolation ; for stub in test_curl_util.cpp class S3fsCred { private: static constexpr char ALLBUCKET_FIELDS_TYPE[] = ""; // special key for mapping(This name is absolutely not used as a bucket name) static constexpr char KEYVAL_FIELDS_TYPE[] = "\t"; // special key for mapping(This name is absolutely not used as a bucket name) static constexpr char AWS_ACCESSKEYID[] = "AWSAccessKeyId"; static constexpr char AWS_SECRETKEY[] = "AWSSecretKey"; static constexpr int IAM_EXPIRE_MERGING = 20 * 60; // update timing static constexpr char ECS_IAM_ENV_VAR[] = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; static constexpr char IAMCRED_ACCESSKEYID[] = "AccessKeyId"; static constexpr char IAMCRED_SECRETACCESSKEY[] = "SecretAccessKey"; static constexpr char IAMCRED_ROLEARN[] = "RoleArn"; static std::string bucket_name; mutable std::mutex token_lock; std::string passwd_file; std::string aws_profile; bool load_iamrole; std::string AWSAccessKeyId GUARDED_BY(token_lock); std::string AWSSecretAccessKey GUARDED_BY(token_lock); std::string AWSAccessToken GUARDED_BY(token_lock); time_t AWSAccessTokenExpire GUARDED_BY(token_lock); bool is_ecs; bool is_use_session_token; bool is_ibm_iam_auth; std::string IAM_cred_url; int IAM_api_version GUARDED_BY(token_lock); std::string IAMv2_api_token GUARDED_BY(token_lock); size_t IAM_field_count; std::string IAM_token_field; std::string IAM_expiry_field; std::string IAM_role GUARDED_BY(token_lock); bool set_builtin_cred_opts; // true if options other than "credlib" is set std::string credlib; // credlib(name or path) std::string credlib_opts; // options for credlib void* hExtCredLib; fp_VersionS3fsCredential pFuncCredVersion; fp_InitS3fsCredential pFuncCredInit; fp_FreeS3fsCredential pFuncCredFree; fp_UpdateS3fsCredential pFuncCredUpdate; public: static constexpr char IAMv2_token_url[] = "http://169.254.169.254/latest/api/token"; static constexpr int IAMv2_token_ttl = 21600; static constexpr char IAMv2_token_ttl_hdr[] = "X-aws-ec2-metadata-token-ttl-seconds"; static constexpr char IAMv2_token_hdr[] = "X-aws-ec2-metadata-token"; private: static bool ParseIAMRoleFromMetaDataResponse(const char* response, std::string& rolename); bool SetS3fsPasswdFile(const char* file); bool IsSetPasswdFile() const; bool SetAwsProfileName(const char* profile_name); bool SetIAMRoleMetadataType(bool flag); bool SetAccessKey(const char* AccessKeyId, const char* SecretAccessKey) REQUIRES(S3fsCred::token_lock); bool SetAccessKeyWithSessionToken(const char* AccessKeyId, const char* SecretAccessKey, const char * SessionToken) REQUIRES(S3fsCred::token_lock); bool IsSetAccessKeys() const REQUIRES(S3fsCred::token_lock); bool SetIsECS(bool flag); bool SetIsUseSessionToken(bool flag); bool SetIsIBMIAMAuth(bool flag); int SetIMDSVersionHasLock(int version) REQUIRES(S3fsCred::token_lock); int SetIMDSVersion(int version) { const std::lock_guard<std::mutex> lock(token_lock); return SetIMDSVersionHasLock(version); } int GetIMDSVersion() const REQUIRES(S3fsCred::token_lock); bool SetIAMv2APITokenHasLock(const std::string& token) REQUIRES(S3fsCred::token_lock); const std::string& GetIAMv2APIToken() const REQUIRES(S3fsCred::token_lock); bool SetIAMRole(const char* role) REQUIRES(S3fsCred::token_lock); const std::string& GetIAMRoleHasLock() const REQUIRES(S3fsCred::token_lock); const std::string& GetIAMRole() const { const std::lock_guard<std::mutex> lock(token_lock); return GetIAMRoleHasLock(); } bool IsSetIAMRole() const REQUIRES(S3fsCred::token_lock); size_t SetIAMFieldCount(size_t field_count); std::string SetIAMCredentialsURL(const char* url); std::string SetIAMTokenField(const char* token_field); std::string SetIAMExpiryField(const char* expiry_field); bool IsReadableS3fsPasswdFile() const; bool CheckS3fsPasswdFilePerms(); bool ParseS3fsPasswdFile(bucketkvmap_t& resmap); bool ReadS3fsPasswdFile() REQUIRES(S3fsCred::token_lock); static int CheckS3fsCredentialAwsFormat(const kvmap_t& kvmap, std::string& access_key_id, std::string& secret_access_key); bool ReadAwsCredentialFile(const std::string &filename) REQUIRES(S3fsCred::token_lock); bool InitialS3fsCredentials() REQUIRES(S3fsCred::token_lock); bool ParseIAMCredentialResponse(const char* response, iamcredmap_t& keyval); bool GetIAMCredentialsURL(std::string& url, bool check_iam_role) REQUIRES(S3fsCred::token_lock); bool LoadIAMCredentials() REQUIRES(S3fsCred::token_lock); bool SetIAMCredentials(const char* response); bool SetIAMRoleFromMetaData(const char* response); bool SetExtCredLib(const char* arg); bool IsSetExtCredLib() const; bool SetExtCredLibOpts(const char* args); bool IsSetExtCredLibOpts() const; bool InitExtCredLib(); bool LoadExtCredLib(); bool UnloadExtCredLib(); bool UpdateExtCredentials() REQUIRES(S3fsCred::token_lock); static bool CheckForbiddenBucketParams(); public: static bool SetBucket(const std::string& bucket); static const std::string& GetBucket(); S3fsCred(); ~S3fsCred(); S3fsCred(const S3fsCred&) = delete; S3fsCred(S3fsCred&&) = delete; S3fsCred& operator=(const S3fsCred&) = delete; S3fsCred& operator=(S3fsCred&&) = delete; bool IsIBMIAMAuth() const { return is_ibm_iam_auth; } bool LoadIAMRoleFromMetaData(); bool CheckIAMCredentialUpdate(std::string* access_key_id = nullptr, std::string* secret_access_key = nullptr, std::string* access_token = nullptr); const char* GetCredFuncVersion(bool detail) const; int DetectParam(const char* arg); bool CheckAllParams(); }; #endif // S3FS_CRED_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
8,284
C++
.h
162
44.302469
155
0.661264
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,472
fdcache_pseudofd.h
s3fs-fuse_s3fs-fuse/src/fdcache_pseudofd.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_FDCACHE_PSEUDOFD_H_ #define S3FS_FDCACHE_PSEUDOFD_H_ #include <mutex> #include <vector> #include "common.h" //------------------------------------------------ // Typdefs //------------------------------------------------ // List of pseudo fd in use // typedef std::vector<int> pseudofd_list_t; //------------------------------------------------ // Class PseudoFdManager //------------------------------------------------ class PseudoFdManager { private: pseudofd_list_t pseudofd_list GUARDED_BY(pseudofd_list_lock); std::mutex pseudofd_list_lock; // protects pseudofd_list static PseudoFdManager& GetManager(); PseudoFdManager() = default; ~PseudoFdManager() = default; int GetUnusedMinPseudoFd() const REQUIRES(pseudofd_list_lock); int CreatePseudoFd(); bool ReleasePseudoFd(int fd); public: PseudoFdManager(const PseudoFdManager&) = delete; PseudoFdManager(PseudoFdManager&&) = delete; PseudoFdManager& operator=(const PseudoFdManager&) = delete; PseudoFdManager& operator=(PseudoFdManager&&) = delete; static int Get(); static bool Release(int fd); }; #endif // S3FS_FDCACHE_PSEUDOFD_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,222
C++
.h
61
32.967213
82
0.652862
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,473
fdcache_auto.h
s3fs-fuse_s3fs-fuse/src/fdcache_auto.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_FDCACHE_AUTO_H_ #define S3FS_FDCACHE_AUTO_H_ #include <fcntl.h> #include "common.h" #include "metaheader.h" class FdEntity; //------------------------------------------------ // class AutoFdEntity //------------------------------------------------ // A class that opens fdentry and closes it automatically. // This class object is used to prevent inconsistencies in // the number of references in fdentry. // The methods are wrappers to the method of the FdManager class. // class AutoFdEntity { private: FdEntity* pFdEntity; int pseudo_fd; public: AutoFdEntity(); ~AutoFdEntity(); AutoFdEntity(const AutoFdEntity&) = delete; AutoFdEntity(AutoFdEntity&&) = delete; AutoFdEntity& operator=(const AutoFdEntity&) = delete; AutoFdEntity& operator=(AutoFdEntity&&) = delete; bool Close(); int Detach(); FdEntity* Attach(const char* path, int existfd); int GetPseudoFd() const { return pseudo_fd; } FdEntity* Open(const char* path, const headers_t* pmeta, off_t size, const struct timespec& ts_mctime, int flags, bool force_tmpfile, bool is_create, bool ignore_modify, int* error = nullptr); FdEntity* GetExistFdEntity(const char* path, int existfd = -1); FdEntity* OpenExistFdEntity(const char* path, int flags = O_RDONLY); }; #endif // S3FS_FDCACHE_AUTO_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,352
C++
.h
62
34.967742
198
0.695614
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,474
fdcache_page.h
s3fs-fuse_s3fs-fuse/src/fdcache_page.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_FDCACHE_PAGE_H_ #define S3FS_FDCACHE_PAGE_H_ #include <cstdint> #include <sys/types.h> #include <vector> //------------------------------------------------ // Symbols //------------------------------------------------ // [NOTE] // If the following symbols in lseek whence are undefined, define them. // If it is not supported by lseek, s3fs judges by the processing result of lseek. // #ifndef SEEK_DATA #define SEEK_DATA 3 #endif #ifndef SEEK_HOLE #define SEEK_HOLE 4 #endif //------------------------------------------------ // Structure fdpage //------------------------------------------------ // page block information struct fdpage { off_t offset; off_t bytes; bool loaded; bool modified; explicit fdpage(off_t start = 0, off_t size = 0, bool is_loaded = false, bool is_modified = false) : offset(start), bytes(size), loaded(is_loaded), modified(is_modified) {} off_t next() const { return (offset + bytes); } off_t end() const { return (0 < bytes ? offset + bytes - 1 : 0); } }; typedef std::vector<struct fdpage> fdpage_list_t; //------------------------------------------------ // Class PageList //------------------------------------------------ class CacheFileStat; class FdEntity; // cppcheck-suppress copyCtorAndEqOperator class PageList { friend class FdEntity; // only one method access directly pages. private: fdpage_list_t pages; bool is_shrink; // [NOTE] true if it has been shrunk even once public: enum class page_status : int8_t { NOT_LOAD_MODIFIED = 0, LOADED, MODIFIED, LOAD_MODIFIED }; private: static bool GetSparseFilePages(int fd, size_t file_size, fdpage_list_t& sparse_list); static bool CheckZeroAreaInFile(int fd, off_t start, size_t bytes); static bool CheckAreaInSparseFile(const struct fdpage& checkpage, const fdpage_list_t& sparse_list, int fd, fdpage_list_t& err_area_list, fdpage_list_t& warn_area_list); void Clear(); bool Parse(off_t new_pos); bool Serialize(CacheFileStat& file, ino_t inode); public: static void FreeList(fdpage_list_t& list); explicit PageList(off_t size = 0, bool is_loaded = false, bool is_modified = false, bool shrunk = false); PageList(const PageList&) = delete; PageList(PageList&&) = delete; PageList& operator=(const PageList&) = delete; PageList& operator=(PageList&&) = delete; ~PageList(); bool Init(off_t size, bool is_loaded, bool is_modified); off_t Size() const; bool Resize(off_t size, bool is_loaded, bool is_modified); bool IsPageLoaded(off_t start = 0, off_t size = 0) const; // size=0 is checking to end of list bool SetPageLoadedStatus(off_t start, off_t size, PageList::page_status pstatus = page_status::LOADED, bool is_compress = true); bool FindUnloadedPage(off_t start, off_t& resstart, off_t& ressize) const; off_t GetTotalUnloadedPageSize(off_t start = 0, off_t size = 0, off_t limit_size = 0) const; // size=0 is checking to end of list size_t GetUnloadedPages(fdpage_list_t& unloaded_list, off_t start = 0, off_t size = 0) const; // size=0 is checking to end of list bool GetPageListsForMultipartUpload(fdpage_list_t& dlpages, fdpage_list_t& mixuppages, off_t max_partsize); bool GetNoDataPageLists(fdpage_list_t& nodata_pages, off_t start = 0, size_t size = 0); off_t BytesModified() const; bool IsModified() const; bool ClearAllModified(); bool Compress(); bool Deserialize(CacheFileStat& file, ino_t inode); void Dump() const; bool CompareSparseFile(int fd, size_t file_size, fdpage_list_t& err_area_list, fdpage_list_t& warn_area_list); }; #endif // S3FS_FDCACHE_PAGE_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
4,952
C++
.h
120
36.55
177
0.633832
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,475
metaheader.h
s3fs-fuse_s3fs-fuse/src/metaheader.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_METAHEADER_H_ #define S3FS_METAHEADER_H_ #include <map> #include <string> #include <strings.h> #include <sys/stat.h> //------------------------------------------------------------------- // headers_t //------------------------------------------------------------------- struct header_nocase_cmp { bool operator()(const std::string &strleft, const std::string &strright) const { return (strcasecmp(strleft.c_str(), strright.c_str()) < 0); } }; typedef std::map<std::string, std::string, header_nocase_cmp> headers_t; //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- struct timespec get_mtime(const headers_t& meta, bool overcheck = true); struct timespec get_ctime(const headers_t& meta, bool overcheck = true); struct timespec get_atime(const headers_t& meta, bool overcheck = true); off_t get_size(const char *s); off_t get_size(const headers_t& meta); mode_t get_mode(const char *s, int base = 0); mode_t get_mode(const headers_t& meta, const std::string& strpath, bool checkdir = false, bool forcedir = false); uid_t get_uid(const char *s); uid_t get_uid(const headers_t& meta); gid_t get_gid(const char *s); gid_t get_gid(const 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(const headers_t& meta); bool is_need_check_obj_detail(const headers_t& meta); bool merge_headers(headers_t& base, const headers_t& additional, bool add_noexist); bool simple_parse_xml(const char* data, size_t len, const char* key, std::string& value); #endif // S3FS_METAHEADER_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,695
C++
.h
66
39.166667
113
0.664506
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,476
s3objlist.h
s3fs-fuse_s3fs-fuse/src/s3objlist.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_S3OBJLIST_H_ #define S3FS_S3OBJLIST_H_ #include <map> #include <string> #include <utility> #include <vector> //------------------------------------------------------------------- // Structure / Typedef //------------------------------------------------------------------- struct s3obj_entry{ std::string normalname; // normalized name: if empty, object is normalized name. std::string orgname; // original name: if empty, object is original name. std::string etag; bool is_dir = false; }; typedef std::map<std::string, struct s3obj_entry> s3obj_t; typedef std::vector<std::string> s3obj_list_t; //------------------------------------------------------------------- // Class S3ObjList //------------------------------------------------------------------- class S3ObjList { private: s3obj_t objects; std::vector<std::string> common_prefixes; bool insert_normalized(const char* name, const char* normalized, bool is_dir); const s3obj_entry* GetS3Obj(const char* name) const; s3obj_t::const_iterator cbegin() const { return objects.cbegin(); } s3obj_t::const_iterator cend() const { return objects.cend(); } public: bool IsEmpty() const { return objects.empty(); } bool insert(const char* name, const char* etag = nullptr, 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; const std::vector<std::string>& GetCommonPrefixes() const { return common_prefixes; } void AddCommonPrefix(std::string prefix) { common_prefixes.push_back(std::move(prefix)); } 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); }; #endif // S3FS_S3OBJLIST_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
3,014
C++
.h
70
39.357143
101
0.64405
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,477
curl_util.h
s3fs-fuse_s3fs-fuse/src/curl_util.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_UTIL_H_ #define S3FS_CURL_UTIL_H_ #include <cstdint> #include <curl/curl.h> #include <string> enum class sse_type_t : uint8_t; //---------------------------------------------- // Functions //---------------------------------------------- struct curl_slist* curl_slist_sort_insert(struct curl_slist* list, const char* key, const char* value); struct curl_slist* curl_slist_remove(struct curl_slist* list, const char* key); 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); std::string get_header_value(const struct curl_slist* list, const std::string &key); 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 bool make_md5_from_binary(const char* pstr, size_t length, std::string& md5); std::string url_to_host(const std::string &url); std::string get_bucket_host(); const char* getCurlDebugHead(curl_infotype type); bool etag_equals(const std::string& s1, const std::string& s2); #endif // S3FS_CURL_UTIL_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,211
C++
.h
50
42.7
114
0.719461
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,478
psemaphore.h
s3fs-fuse_s3fs-fuse/src/psemaphore.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_SEMAPHORE_H_ #define S3FS_SEMAPHORE_H_ //------------------------------------------------------------------- // Class Semaphore //------------------------------------------------------------------- #if __cplusplus >= 202002L #include <semaphore> typedef std::counting_semaphore<INT_MAX> Semaphore; #else // portability wrapper for sem_t since macOS does not implement it #ifdef __APPLE__ #include <dispatch/dispatch.h> class Semaphore { public: explicit Semaphore(int value) : value(value), sem(dispatch_semaphore_create(value)) {} ~Semaphore() { // macOS cannot destroy a semaphore with posts less than the initializer for(int i = 0; i < value; ++i){ release(); } dispatch_release(sem); } Semaphore(const Semaphore&) = delete; Semaphore(Semaphore&&) = delete; Semaphore& operator=(const Semaphore&) = delete; Semaphore& operator=(Semaphore&&) = delete; void acquire() { dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); } bool try_acquire() { if(0 == dispatch_semaphore_wait(sem, DISPATCH_TIME_NOW)){ return true; }else{ return false; } } void release() { dispatch_semaphore_signal(sem); } private: int value; dispatch_semaphore_t sem; }; #else #include <cerrno> #include <semaphore.h> class Semaphore { public: explicit Semaphore(int value) { sem_init(&mutex, 0, value); } ~Semaphore() { sem_destroy(&mutex); } void acquire() { int r; do { r = sem_wait(&mutex); } while (r == -1 && errno == EINTR); } bool try_acquire() { int result; do{ result = sem_trywait(&mutex); }while(result == -1 && errno == EINTR); return (0 == result); } void release() { sem_post(&mutex); } private: sem_t mutex; }; #endif #endif #endif // S3FS_SEMAPHORE_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
3,112
C++
.h
99
25.383838
94
0.591653
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,479
s3fs_util.h
s3fs-fuse_s3fs-fuse/src/s3fs_util.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_ #include <cstdint> #include <functional> #include <string> #include <sys/stat.h> #ifndef CLOCK_REALTIME #define CLOCK_REALTIME 0 #endif #ifndef CLOCK_MONOTONIC #define CLOCK_MONOTONIC CLOCK_REALTIME #endif #ifndef CLOCK_MONOTONIC_COARSE #define CLOCK_MONOTONIC_COARSE CLOCK_MONOTONIC #endif //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- std::string get_realpath(const char *path); void init_sysconf_vars(); std::string get_username(uid_t uid); int is_uid_include_group(uid_t uid, gid_t gid); std::string mydirname(const char* path); std::string mydirname(const std::string& path); std::string mybasename(const char* path); std::string mybasename(const std::string& path); int mkdirp(const std::string& path, mode_t mode); std::string get_exist_directory_path(const std::string& path); bool check_exist_dir_permission(const char* dirpath); bool delete_files_in_dir(const char* dir, bool is_remove_own); bool compare_sysname(const char* target); void print_launch_message(int argc, char** argv); // // Utility for nanosecond time(timespec) // enum class stat_time_type : uint8_t { ATIME, MTIME, CTIME }; //------------------------------------------------------------------- // Utility for nanosecond time(timespec) //------------------------------------------------------------------- static constexpr struct timespec S3FS_OMIT_TS = {0, UTIME_OMIT}; int compare_timespec(const struct timespec& ts1, const struct timespec& ts2); int compare_timespec(const struct stat& st, stat_time_type type, const struct timespec& ts); void set_timespec_to_stat(struct stat& st, stat_time_type type, const struct timespec& ts); struct timespec* set_stat_to_timespec(const struct stat& st, stat_time_type type, struct timespec& ts); std::string str_stat_time(const struct stat& st, stat_time_type type); struct timespec* s3fs_realtime(struct timespec& ts); std::string s3fs_str_realtime(); // Wrap fclose since it is illegal to take the address of a stdlib function int s3fs_fclose(FILE* fp); class scope_guard { public: template<class Callable> explicit scope_guard(Callable&& undo_func) : func(std::forward<Callable>(undo_func)) {} ~scope_guard() { if(func != nullptr) { func(); } } void dismiss() { func = nullptr; } scope_guard(const scope_guard&) = delete; scope_guard(scope_guard&& other) = delete; scope_guard& operator=(const scope_guard&) = delete; scope_guard& operator=(scope_guard&&) = delete; private: std::function<void()> func; }; #endif // S3FS_S3FS_UTIL_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
3,733
C++
.h
102
34.205882
103
0.679036
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,480
sighandlers.h
s3fs-fuse_s3fs-fuse/src/sighandlers.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_SIGHANDLERS_H_ #define S3FS_SIGHANDLERS_H_ #include <memory> #include <thread> #include "psemaphore.h" //---------------------------------------------- // class S3fsSignals //---------------------------------------------- class S3fsSignals { private: static std::unique_ptr<S3fsSignals> pSingleton; static bool enableUsr1; std::unique_ptr<std::thread> pThreadUsr1; std::unique_ptr<Semaphore> pSemUsr1; protected: static S3fsSignals* get() { return pSingleton.get(); } static void HandlerUSR1(int sig); static void CheckCacheWorker(Semaphore* pSem); static void HandlerUSR2(int sig); static bool InitUsr2Handler(); static void HandlerHUP(int sig); static bool InitHupHandler(); S3fsSignals(); bool InitUsr1Handler(); bool DestroyUsr1Handler(); bool WakeupUsr1Thread(); public: ~S3fsSignals(); S3fsSignals(const S3fsSignals&) = delete; S3fsSignals(S3fsSignals&&) = delete; S3fsSignals& operator=(const S3fsSignals&) = delete; S3fsSignals& operator=(S3fsSignals&&) = delete; static bool Initialize(); static bool Destroy(); static bool SetUsr1Handler(const char* path); }; #endif // S3FS_SIGHANDLERS_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,312
C++
.h
65
30.984615
82
0.671005
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,481
curl.h
s3fs-fuse_s3fs-fuse/src/curl.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_ #include <atomic> #include <cstdint> #include <curl/curl.h> #include <map> #include <memory> #include <mutex> #include <string> #include <thread> #include <vector> #include "common.h" #include "fdcache_page.h" #include "metaheader.h" #include "psemaphore.h" #include "s3fs_util.h" #include "types.h" //---------------------------------------------- // Avoid dependency on libcurl version //---------------------------------------------- // [NOTE] // The following symbols (enum) depend on the version of libcurl. // CURLOPT_TCP_KEEPALIVE 7.25.0 and later // CURLOPT_SSL_ENABLE_ALPN 7.36.0 and later // CURLOPT_KEEP_SENDING_ON_ERROR 7.51.0 and later // // s3fs uses these, if you build s3fs with the old libcurl, // substitute the following symbols to avoid errors. // If the version of libcurl linked at runtime is old, // curl_easy_setopt results in an error(CURLE_UNKNOWN_OPTION) and // a message is output. // #if defined(HAVE_CURLOPT_TCP_KEEPALIVE) && (HAVE_CURLOPT_TCP_KEEPALIVE == 1) #define S3FS_CURLOPT_TCP_KEEPALIVE CURLOPT_TCP_KEEPALIVE #else #define S3FS_CURLOPT_TCP_KEEPALIVE static_cast<CURLoption>(213) #endif #if defined(HAVE_CURLOPT_SSL_ENABLE_ALPN) && (HAVE_CURLOPT_SSL_ENABLE_ALPN == 1) #define S3FS_CURLOPT_SSL_ENABLE_ALPN CURLOPT_SSL_ENABLE_ALPN #else #define S3FS_CURLOPT_SSL_ENABLE_ALPN static_cast<CURLoption>(226) #endif #if defined(HAVE_CURLOPT_KEEP_SENDING_ON_ERROR) && (HAVE_CURLOPT_KEEP_SENDING_ON_ERROR == 1) #define S3FS_CURLOPT_KEEP_SENDING_ON_ERROR CURLOPT_KEEP_SENDING_ON_ERROR #else #define S3FS_CURLOPT_KEEP_SENDING_ON_ERROR static_cast<CURLoption>(245) #endif //---------------------------------------------- // Structure / Typedefs //---------------------------------------------- struct curlprogress { time_t time; double dl_progress; double ul_progress; }; typedef std::unique_ptr<CURL, decltype(&curl_easy_cleanup)> CurlUniquePtr; //---------------------------------------------- // class S3fsCurl //---------------------------------------------- class S3fsCred; class S3fsCurl; // Prototype function for lazy setup options for curl handle typedef bool (*s3fscurl_lazy_setup)(S3fsCurl* s3fscurl); typedef std::map<std::string, std::string> sseckeymap_t; typedef std::vector<sseckeymap_t> sseckeylist_t; // Class for lapping curl // class S3fsCurl { // [TODO] // If S3fsMultiCurl is discontinued, the following friends will be deleted. friend class S3fsMultiCurl; private: enum class REQTYPE : int8_t { UNSET = -1, DELETE, HEAD, PUTHEAD, PUT, GET, CHKBUCKET, LISTBUCKET, PREMULTIPOST, COMPLETEMULTIPOST, UPLOADMULTIPOST, COPYMULTIPOST, MULTILIST, IAMCRED, ABORTMULTIUPLOAD, IAMROLE }; // Environment name static constexpr char S3FS_SSL_PRIVKEY_PASSWORD[] = "S3FS_SSL_PRIVKEY_PASSWORD"; // class variables static std::atomic<bool> curl_warnings_once; // emit older curl warnings only once static std::mutex curl_handles_lock; static struct callback_locks_t { std::mutex dns; std::mutex ssl_session; } callback_locks; 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 acl_t default_acl; static std::string 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 bool is_dump_body; static S3fsCred* ps3fscred; static long ssl_verify_hostname; static std::string client_cert; static std::string client_cert_type; static std::string client_priv_key; static std::string client_priv_key_type; static std::string client_key_password; static std::map<const CURL*, curlprogress> curl_progress; static std::string curl_ca_bundle; static mimes_t mimeTypes; static std::string userAgent; static int max_parallel_cnt; static int max_multireq; static off_t multipart_size; static off_t multipart_copy_size; static signature_type_t signature_type; static bool is_unsigned_payload; static bool is_ua; // User-Agent static bool listobjectsv2; static bool requester_pays; static std::string proxy_url; static bool proxy_http; static std::string proxy_userpwd; // load from file(<username>:<passphrase>) static long ipresolve_type; // this value is a libcurl symbol. // variables CurlUniquePtr hCurl PT_GUARDED_BY(curl_handles_lock) = {nullptr, curl_easy_cleanup}; REQTYPE type; // type of request std::string path; // target object path std::string url; // target object path(url) struct curl_slist* requestHeaders; headers_t responseHeaders; // header data by HeaderCallback std::string bodydata; // body data by WriteMemoryCallback std::string headdata; // header data by WriteMemoryCallback long LastResponseCode; const unsigned char* postdata; // use by post method and read callback function. off_t 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 ([TODO] If S3fsMultiCurl is discontinued, this variable will be deleted.) std::unique_ptr<FILE, decltype(&s3fs_fclose)> b_infile = {nullptr, &s3fs_fclose}; // backup for retrying const unsigned char* b_postdata; // backup for retrying off_t b_postdata_remaining; // backup for retrying off_t b_partdata_startpos; // backup for retrying off_t b_partdata_size; // backup for retrying size_t b_ssekey_pos; // backup for retrying std::string b_ssevalue; // backup for retrying sse_type_t b_ssetype; // backup for retrying std::string b_from; // backup for retrying(for copy request) headers_t b_meta; // backup for retrying(for copy request) std::string op; // the HTTP verb of the request ("PUT", "GET", etc.) std::string query_string; // request query string Semaphore *sem; std::mutex *completed_tids_lock; std::vector<std::thread::id> *completed_tids PT_GUARDED_BY(*completed_tids_lock); s3fscurl_lazy_setup fpLazySetup; // curl options for lazy setting function CURLcode curlCode; // handle curl return public: static constexpr long S3FSCURL_RESPONSECODE_NOTSET = -1; static constexpr long S3FSCURL_RESPONSECODE_FATAL_ERROR = -2; static constexpr int S3FSCURL_PERFORM_RESULT_NOTSET = 1; public: // constructor/destructor explicit S3fsCurl(bool ahbe = false); ~S3fsCurl(); S3fsCurl(const S3fsCurl&) = delete; S3fsCurl(S3fsCurl&&) = delete; S3fsCurl& operator=(const S3fsCurl&) = delete; S3fsCurl& operator=(S3fsCurl&&) = delete; private: // class methods static bool InitGlobalCurl(); static bool DestroyGlobalCurl(); static bool InitShareCurl(); static bool DestroyShareCurl(); static void LockCurlShare(CURL* handle, curl_lock_data nLockData, curl_lock_access laccess, void* useptr) NO_THREAD_SAFETY_ANALYSIS; static void UnlockCurlShare(CURL* handle, curl_lock_data nLockData, void* useptr) NO_THREAD_SAFETY_ANALYSIS; static bool InitCryptMutex(); static bool DestroyCryptMutex(); static int CurlProgress(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow); static std::string extractURI(const std::string& url); static bool LocateBundle(); 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 MultipartUploadPartCallback(S3fsCurl* s3fscurl, void* param); static bool CopyMultipartUploadCallback(S3fsCurl* s3fscurl, void* param); static bool MixMultipartUploadCallback(S3fsCurl* s3fscurl, void* param); static std::unique_ptr<S3fsCurl> MultipartUploadPartRetryCallback(S3fsCurl* s3fscurl); static std::unique_ptr<S3fsCurl> CopyMultipartUploadRetryCallback(S3fsCurl* s3fscurl); static std::unique_ptr<S3fsCurl> MixMultipartUploadRetryCallback(S3fsCurl* s3fscurl); static std::unique_ptr<S3fsCurl> ParallelGetObjectRetryCallback(S3fsCurl* s3fscurl); // lazy functions for set curl options static bool MultipartUploadPartSetCurlOpts(S3fsCurl* s3fscurl); static bool CopyMultipartUploadSetCurlOpts(S3fsCurl* s3fscurl); static bool PreGetObjectRequestSetCurlOpts(S3fsCurl* s3fscurl); static bool PreHeadRequestSetCurlOpts(S3fsCurl* s3fscurl); static bool LoadEnvSseCKeys(); static bool LoadEnvSseKmsid(); static bool PushbackSseKeys(const std::string& onekey); static bool AddUserAgent(const CurlUniquePtr& hCurl); static int CurlDebugFunc(const CURL* hcurl, curl_infotype type, char* data, size_t size, void* userptr); static int CurlDebugBodyInFunc(const CURL* hcurl, curl_infotype type, char* data, size_t size, void* userptr); static int CurlDebugBodyOutFunc(const CURL* hcurl, curl_infotype type, char* data, size_t size, void* userptr); static int RawCurlDebugFunc(const CURL* hcurl, curl_infotype type, char* data, size_t size, void* userptr, curl_infotype datatype); // methods bool ResetHandle() REQUIRES(S3fsCurl::curl_handles_lock); bool RemakeHandle(); bool ClearInternalData(); bool insertV4Headers(const std::string& access_key_id, const std::string& secret_access_key, const std::string& access_token); void insertV2Headers(const std::string& access_key_id, const std::string& secret_access_key, const std::string& access_token); void insertIBMIAMHeaders(const std::string& access_key_id, const std::string& access_token); bool insertAuthHeaders(); bool AddSseRequestHead(sse_type_t ssetype, const std::string& ssevalue, bool is_copy); bool PreHeadRequest(const char* tpath, size_t ssekey_pos = -1); bool PreHeadRequest(const std::string& tpath, size_t ssekey_pos = -1) { return PreHeadRequest(tpath.c_str(), ssekey_pos); } std::string CalcSignatureV2(const std::string& method, const std::string& strMD5, const std::string& content_type, const std::string& date, const std::string& resource, const std::string& secret_access_key, const std::string& access_token); std::string CalcSignature(const std::string& method, const std::string& canonical_uri, const std::string& query_string, const std::string& strdate, const std::string& payload_hash, const std::string& date8601, const std::string& secret_access_key, const std::string& access_token); int MultipartUploadPartSetup(const char* tpath, int part_num, const std::string& upload_id); int CopyMultipartUploadSetup(const char* from, const char* to, int part_num, const std::string& upload_id, headers_t& meta); bool MultipartUploadPartComplete(); bool CopyMultipartUploadComplete(); int MapPutErrorResponse(int result); public: // class methods static bool InitS3fsCurl(); static bool InitCredentialObject(S3fsCred* pcredobj); static bool InitMimeType(const std::string& strFile); static bool DestroyS3fsCurl(); static std::unique_ptr<S3fsCurl> CreateParallelS3fsCurl(const char* tpath, int fd, off_t start, off_t size, int part_num, bool is_copy, etagpair* petag, const std::string& upload_id, int& result); static int ParallelMultipartUploadRequest(const char* tpath, const headers_t& meta, int fd); static int ParallelMixMultipartUploadRequest(const char* tpath, headers_t& meta, int fd, const fdpage_list_t& mixuppages); static int ParallelGetObjectRequest(const char* tpath, int fd, off_t start, off_t size); // class methods(variables) static std::string LookupMimeType(const 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() { return S3fsCurl::readwrite_timeout; } static int SetRetries(int count); static int GetRetries(); static bool SetPublicBucket(bool flag); static bool IsPublicBucket() { return S3fsCurl::is_public_bucket; } static acl_t SetDefaultAcl(acl_t acl); static acl_t GetDefaultAcl(); static std::string SetStorageClass(const std::string& storage_class); static std::string GetStorageClass() { return S3fsCurl::storage_class; } static bool LoadEnvSse() { return (S3fsCurl::LoadEnvSseCKeys() && S3fsCurl::LoadEnvSseKmsid()); } static sse_type_t SetSseType(sse_type_t type); static sse_type_t GetSseType() { return S3fsCurl::ssetype; } static bool IsSseDisable() { return (sse_type_t::SSE_DISABLE == S3fsCurl::ssetype); } static bool IsSseS3Type() { return (sse_type_t::SSE_S3 == S3fsCurl::ssetype); } static bool IsSseCType() { return (sse_type_t::SSE_C == S3fsCurl::ssetype); } static bool IsSseKmsType() { return (sse_type_t::SSE_KMS == S3fsCurl::ssetype); } static bool FinalCheckSse(); static bool SetSseCKeys(const char* filepath); static bool SetSseKmsid(const char* kmsid); static bool IsSetSseKmsId() { return !S3fsCurl::ssekmsid.empty(); } static const char* GetSseKmsId() { return S3fsCurl::ssekmsid.c_str(); } static bool GetSseKey(std::string& md5, std::string& ssekey); static bool GetSseKeyMd5(size_t pos, std::string& md5); static size_t GetSseKeyCount(); static bool SetContentMd5(bool flag); static bool SetVerbose(bool flag); static bool GetVerbose() { return S3fsCurl::is_verbose; } static bool SetDumpBody(bool flag); static bool IsDumpBody() { return S3fsCurl::is_dump_body; } static long SetSslVerifyHostname(long value); static long GetSslVerifyHostname() { return S3fsCurl::ssl_verify_hostname; } static bool SetSSLClientCertOptions(const std::string& values); static void ResetOffset(S3fsCurl* pCurl); // maximum parallel GET and PUT requests static int SetMaxParallelCount(int value); static int GetMaxParallelCount() { return S3fsCurl::max_parallel_cnt; } // maximum parallel HEAD requests static int SetMaxMultiRequest(int max); static int GetMaxMultiRequest() { return S3fsCurl::max_multireq; } static bool SetMultipartSize(off_t size); static off_t GetMultipartSize() { return S3fsCurl::multipart_size; } static bool SetMultipartCopySize(off_t size); static off_t GetMultipartCopySize() { return S3fsCurl::multipart_copy_size; } static signature_type_t SetSignatureType(signature_type_t signature_type) { signature_type_t bresult = S3fsCurl::signature_type; S3fsCurl::signature_type = signature_type; return bresult; } static signature_type_t GetSignatureType() { return S3fsCurl::signature_type; } static bool SetUnsignedPayload(bool issset) { bool bresult = S3fsCurl::is_unsigned_payload; S3fsCurl::is_unsigned_payload = issset; return bresult; } static bool GetUnsignedPayload() { return S3fsCurl::is_unsigned_payload; } static bool SetUserAgentFlag(bool isset) { bool bresult = S3fsCurl::is_ua; S3fsCurl::is_ua = isset; return bresult; } static bool IsUserAgentFlag() { return S3fsCurl::is_ua; } static void InitUserAgent(); static bool SetListObjectsV2(bool isset) { bool bresult = S3fsCurl::listobjectsv2; S3fsCurl::listobjectsv2 = isset; return bresult; } static bool IsListObjectsV2() { return S3fsCurl::listobjectsv2; } static bool SetRequesterPays(bool flag) { bool old_flag = S3fsCurl::requester_pays; S3fsCurl::requester_pays = flag; return old_flag; } static bool IsRequesterPays() { return S3fsCurl::requester_pays; } static bool SetProxy(const char* url); static bool SetProxyUserPwd(const char* userpwd); static bool SetIPResolveType(const char* value); // methods bool CreateCurlHandle(bool remake = false); bool DestroyCurlHandle(bool clear_internal_data = true); bool DestroyCurlHandleHasLock(bool clear_internal_data = true) REQUIRES(S3fsCurl::curl_handles_lock); bool GetIAMCredentials(const char* cred_url, const char* iam_v2_token, const char* ibm_secret_access_key, std::string& response); bool GetIAMRoleFromMetaData(const char* cred_url, const char* iam_v2_token, std::string& token); bool GetResponseCode(long& responseCode, bool from_curl_handle = true) const; int RequestPerform(bool dontAddAuthHeaders=false); int DeleteRequest(const char* tpath); int GetIAMv2ApiToken(const char* token_url, int token_ttl, const char* token_ttl_hdr, std::string& response); int HeadRequest(const char* tpath, headers_t& meta); int PutHeadRequest(const char* tpath, const 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, off_t size, sse_type_t ssetype, const std::string& ssevalue); int GetObjectRequest(const char* tpath, int fd, off_t start, off_t size, sse_type_t ssetype, const std::string& ssevalue); int CheckBucket(const char* check_path, bool compat_dir, bool force_no_sse); int ListBucketRequest(const char* tpath, const char* query); int PreMultipartUploadRequest(const char* tpath, const headers_t& meta, std::string& upload_id); int MultipartUploadComplete(const char* tpath, const std::string& upload_id, const etaglist_t& parts); int MultipartUploadPartRequest(const char* tpath, int part_num, const std::string& upload_id); bool MixMultipartUploadComplete(); int MultipartListRequest(std::string& body); int AbortMultipartUpload(const char* tpath, const std::string& upload_id); int MultipartHeadRequest(const char* tpath, off_t size, headers_t& meta); int MultipartUploadRequest(const std::string& upload_id, const char* tpath, int fd, off_t offset, off_t size, etagpair* petagpair); int MultipartRenameRequest(const char* from, const char* to, headers_t& meta, off_t size); // methods(variables) const std::string& GetPath() const { return path; } const std::string& GetUrl() const { return url; } const std::string& GetOp() const { return op; } const headers_t* GetResponseHeaders() const { return &responseHeaders; } const std::string& GetBodyData() const { return bodydata; } const std::string& GetHeadData() const { return headdata; } CURLcode GetCurlCode() const { return curlCode; } long GetLastResponseCode() const { return LastResponseCode; } bool SetUseAhbe(bool ahbe); bool EnableUseAhbe() { return SetUseAhbe(true); } bool DisableUseAhbe() { return SetUseAhbe(false); } bool IsUseAhbe() const { return is_use_ahbe; } }; #endif // S3FS_CURL_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
22,499
C++
.h
385
51.14026
289
0.656704
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,482
s3fs_auth.h
s3fs-fuse_s3fs-fuse/src/s3fs_auth.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <array> #include <memory> #include <string> #include <sys/types.h> typedef std::array<unsigned char, 16> md5_t; typedef std::array<unsigned char, 32> sha256_t; //------------------------------------------------------------------- // Utility functions for Authentication //------------------------------------------------------------------- // // in common_auth.cpp // std::string s3fs_get_content_md5(int fd); std::string s3fs_sha256_hex_fd(int fd, off_t start, off_t size); // // in xxxxxx_auth.cpp // const char* s3fs_crypt_lib_name(); bool s3fs_init_global_ssl(); bool s3fs_destroy_global_ssl(); bool s3fs_init_crypt_mutex(); bool s3fs_destroy_crypt_mutex(); std::unique_ptr<unsigned char[]> s3fs_HMAC(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned int* digestlen); std::unique_ptr<unsigned char[]> s3fs_HMAC256(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned int* digestlen); bool s3fs_md5(const unsigned char* data, size_t datalen, md5_t* result); bool s3fs_md5_fd(int fd, off_t start, off_t size, md5_t* result); bool s3fs_sha256(const unsigned char* data, size_t datalen, sha256_t* digest); bool s3fs_sha256_fd(int fd, off_t start, off_t size, sha256_t* result); #endif // S3FS_AUTH_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,300
C++
.h
58
38.224138
146
0.699329
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,483
cache.h
s3fs-fuse_s3fs-fuse/src/cache.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <cstring> #include <map> #include <mutex> #include <string> #include <sys/stat.h> #include <vector> #include "common.h" #include "metaheader.h" //------------------------------------------------------------------- // Structure //------------------------------------------------------------------- // // Struct for stats cache // struct stat_cache_entry { struct stat stbuf = {}; unsigned long hit_count = 0; struct timespec cache_date = {0, 0}; headers_t meta; bool isforce = false; bool noobjcache = false; // Flag: cache is no object for no listing. unsigned long notruncate = 0L; // 0<: not remove automatically at checking truncate }; typedef std::map<std::string, stat_cache_entry> stat_cache_t; // key=path // // Struct for symbolic link cache // struct symlink_cache_entry { std::string link; unsigned long hit_count = 0; struct timespec cache_date = {0, 0}; // The function that operates timespec uses the same as Stats }; typedef std::map<std::string, symlink_cache_entry> symlink_cache_t; // // Typedefs for No truncate file name cache // typedef std::vector<std::string> notruncate_filelist_t; // untruncated file name list in dir typedef std::map<std::string, notruncate_filelist_t> notruncate_dir_map_t; // key is parent dir path //------------------------------------------------------------------- // Class StatCache //------------------------------------------------------------------- // [NOTE] About Symbolic link cache // The Stats cache class now also has a symbolic link cache. // It is possible to take out the Symbolic link cache in another class, // but the cache out etc. should be synchronized with the Stats cache // and implemented in this class. // Symbolic link cache size and timeout use the same settings as Stats // cache. This simplifies user configuration, and from a user perspective, // the symbolic link cache appears to be included in the Stats cache. // class StatCache { private: static StatCache singleton; static std::mutex stat_cache_lock; stat_cache_t stat_cache GUARDED_BY(stat_cache_lock); bool IsExpireTime; bool IsExpireIntervalType; // if this flag is true, cache data is updated at last access time. time_t ExpireTime; unsigned long CacheSize; bool IsCacheNoObject; symlink_cache_t symlink_cache GUARDED_BY(stat_cache_lock); notruncate_dir_map_t notruncate_file_cache GUARDED_BY(stat_cache_lock); StatCache(); ~StatCache(); void Clear(); bool GetStat(const std::string& key, struct stat* pst, headers_t* meta, bool overcheck, const char* petag, bool* pisforce); // Truncate stat cache bool TruncateCache() REQUIRES(StatCache::stat_cache_lock); // Truncate symbolic link cache bool TruncateSymlink() REQUIRES(StatCache::stat_cache_lock); bool AddNotruncateCache(const std::string& key) REQUIRES(stat_cache_lock); bool DelNotruncateCache(const std::string& key) REQUIRES(stat_cache_lock); public: StatCache(const StatCache&) = delete; StatCache(StatCache&&) = delete; StatCache& operator=(const StatCache&) = delete; StatCache& operator=(StatCache&&) = delete; // Reference singleton static StatCache* getStatCacheData() { return &singleton; } // Attribute unsigned long GetCacheSize() const; unsigned long SetCacheSize(unsigned long size); time_t GetExpireTime() const; time_t SetExpireTime(time_t expire, bool is_interval = false); time_t UnsetExpireTime(); bool SetCacheNoObject(bool flag); bool EnableCacheNoObject() { return SetCacheNoObject(true); } bool DisableCacheNoObject() { return SetCacheNoObject(false); } bool GetCacheNoObject() const { return IsCacheNoObject; } // Get stat cache bool GetStat(const std::string& key, struct stat* pst, headers_t* meta, bool overcheck = true, bool* pisforce = nullptr) { return GetStat(key, pst, meta, overcheck, nullptr, pisforce); } bool GetStat(const std::string& key, struct stat* pst, bool overcheck = true) { return GetStat(key, pst, nullptr, overcheck, nullptr, nullptr); } bool GetStat(const std::string& key, headers_t* meta, bool overcheck = true) { return GetStat(key, nullptr, meta, overcheck, nullptr, nullptr); } bool HasStat(const std::string& key, bool overcheck = true) { return GetStat(key, nullptr, nullptr, overcheck, nullptr, nullptr); } bool HasStat(const std::string& key, const char* etag, bool overcheck = true) { return GetStat(key, nullptr, nullptr, overcheck, etag, nullptr); } bool HasStat(const std::string& key, struct stat* pst, const char* etag) { return GetStat(key, pst, nullptr, true, etag, nullptr); } // Cache For no object bool IsNoObjectCache(const std::string& key, bool overcheck = true); bool AddNoObjectCache(const std::string& key); // Add stat cache bool AddStat(const std::string& key, const headers_t& meta, bool forcedir = false, bool no_truncate = false); // Update meta stats bool UpdateMetaStats(const std::string& key, const headers_t& meta); // Change no truncate flag void ChangeNoTruncateFlag(const std::string& key, bool no_truncate); // Delete stat cache bool DelStat(const std::string& key) { const std::lock_guard<std::mutex> lock(StatCache::stat_cache_lock); return DelStatHasLock(key); } bool DelStatHasLock(const std::string& key) REQUIRES(StatCache::stat_cache_lock); // Cache for symbolic link bool GetSymlink(const std::string& key, std::string& value); bool AddSymlink(const std::string& key, const std::string& value); bool DelSymlink(const std::string& key) { const std::lock_guard<std::mutex> lock(StatCache::stat_cache_lock); return DelSymlinkHasLock(key); } bool DelSymlinkHasLock(const std::string& key) REQUIRES(stat_cache_lock); // Cache for Notruncate file bool GetNotruncateCache(const std::string& parentdir, notruncate_filelist_t& list); }; //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- bool convert_header_to_stat(const char* path, const headers_t& meta, struct stat* pst, bool forcedir = false); #endif // S3FS_CACHE_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
8,054
C++
.h
188
36.840426
131
0.622066
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,484
s3fs_help.h
s3fs-fuse_s3fs-fuse/src/s3fs_help.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_HELP_H_ #define S3FS_S3FS_HELP_H_ //------------------------------------------------------------------- // Functions //------------------------------------------------------------------- void show_usage(); void show_help(); void show_version(); const char* short_version(); #endif // S3FS_S3FS_HELP_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
1,300
C++
.h
37
33.540541
82
0.664019
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,485
fdcache_untreated.h
s3fs-fuse_s3fs-fuse/src/fdcache_untreated.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_FDCACHE_UNTREATED_H_ #define S3FS_FDCACHE_UNTREATED_H_ #include <mutex> #include "common.h" #include "types.h" //------------------------------------------------ // Class UntreatedParts //------------------------------------------------ class UntreatedParts { private: mutable std::mutex untreated_list_lock; // protects untreated_list untreated_list_t untreated_list GUARDED_BY(untreated_list_lock); long last_tag GUARDED_BY(untreated_list_lock) = 0; // [NOTE] Use this to identify the latest updated part. private: bool RowGetPart(off_t& start, off_t& size, off_t max_size, off_t min_size, bool lastpart) const; public: UntreatedParts() = default; ~UntreatedParts() = default; UntreatedParts(const UntreatedParts&) = delete; UntreatedParts(UntreatedParts&&) = delete; UntreatedParts& operator=(const UntreatedParts&) = delete; UntreatedParts& operator=(UntreatedParts&&) = delete; bool empty(); bool AddPart(off_t start, off_t size); bool GetLastUpdatedPart(off_t& start, off_t& size, off_t max_size, off_t min_size = MIN_MULTIPART_SIZE) const { return RowGetPart(start, size, max_size, min_size, true); } bool ClearParts(off_t start, off_t size); bool ClearAll() { return ClearParts(0, 0); } bool GetLastUpdatePart(off_t& start, off_t& size) const; bool ReplaceLastUpdatePart(off_t start, off_t size); bool RemoveLastUpdatePart(); bool Duplicate(untreated_list_t& list); void Dump(); }; #endif // S3FS_FDCACHE_UNTREATED_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,617
C++
.h
62
37.903226
179
0.675984
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,486
s3fs_threadreqs.h
s3fs-fuse_s3fs-fuse/src/s3fs_threadreqs.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_THREADREQS_H_ #define S3FS_THREADREQS_H_ #include <string> #include "common.h" #include "metaheader.h" #include "curl.h" #include "s3objlist.h" #include "syncfiller.h" //------------------------------------------------------------------- // Structures for MultiThread Request //------------------------------------------------------------------- // // Head Request parameter structure for Thread Pool. // struct head_req_thparam { std::string path; headers_t* pmeta = nullptr; int result = 0; }; // // Multi Head Request parameter structure for Thread Pool. // struct multi_head_req_thparam { std::string path; SyncFiller* psyncfiller = nullptr; std::mutex* pthparam_lock = nullptr; int* pretrycount = nullptr; s3obj_list_t* pnotfound_list = nullptr; bool use_wtf8 = false; int* presult = nullptr; }; // // Delete Request parameter structure for Thread Pool. // struct delete_req_thparam { std::string path; int result = 0; }; // // Put Head Request parameter structure for Thread Pool. // struct put_head_req_thparam { std::string path; headers_t meta; bool isCopy = false; int result = 0; }; // // Put Request parameter structure for Thread Pool. // struct put_req_thparam { std::string path; headers_t meta; int fd = -1; bool ahbe = false; int result = 0; }; // // List Bucket Request parameter structure for Thread Pool. // struct list_bucket_req_thparam { std::string path; std::string query; std::string* presponseBody = nullptr; int result = 0; }; // // Check Service Request parameter structure for Thread Pool. // struct check_service_req_thparam { std::string path; bool forceNoSSE = false; bool support_compat_dir = false; long* presponseCode = nullptr; std::string* presponseBody = nullptr; int result = 0; }; // // Pre Multipart Upload Request parameter structure for Thread Pool. // struct pre_multipart_upload_req_thparam { std::string path; headers_t meta; std::string upload_id; int result = 0; }; // // Complete Multipart Upload Request parameter structure for Thread Pool. // struct complete_multipart_upload_req_thparam { std::string path; std::string upload_id; etaglist_t etaglist; int result = 0; }; // // Abort Multipart Upload Request parameter structure for Thread Pool. // struct abort_multipart_upload_req_thparam { std::string path; std::string upload_id; int result = 0; }; // // Get Object Request parameter structure for Thread Pool. // struct get_object_req_thparam { std::string path; int fd = -1; off_t start = 0; off_t size = 0; int result = 0; }; //------------------------------------------------------------------- // Thread Worker functions for MultiThread Request //------------------------------------------------------------------- void* head_req_threadworker(void* arg); void* multi_head_req_threadworker(void* arg); void* delete_req_threadworker(void* arg); void* put_head_req_threadworker(void* arg); void* put_req_threadworker(void* arg); void* list_bucket_req_threadworker(void* arg); void* check_service_req_threadworker(void* arg); void* pre_multipart_upload_req_threadworker(void* arg); void* complete_multipart_upload_threadworker(void* arg); void* abort_multipart_upload_req_threadworker(void* arg); void* get_object_req_threadworker(void* arg); //------------------------------------------------------------------- // Utility functions //------------------------------------------------------------------- int head_request(const std::string& strpath, headers_t& header); int delete_request(const std::string& strpath); int put_head_request(const std::string& strpath, const headers_t& meta, bool is_copy); int put_request(const std::string& strpath, const headers_t& meta, int fd, bool ahbe); int list_bucket_request(const std::string& strpath, const std::string& query, std::string& responseBody); int check_service_request(const std::string& strpath, bool forceNoSSE, bool support_compat_dir, long& responseCode, std::string& responseBody); int pre_multipart_upload_request(const std::string& path, const headers_t& meta, std::string& upload_id); int complete_multipart_upload_request(const std::string& path, const std::string& upload_id, const etaglist_t& parts); int abort_multipart_upload_request(const std::string& path, const std::string& upload_id); int get_object_request(const std::string& path, int fd, off_t start, off_t size); //------------------------------------------------------------------- // Direct Call Utility Functions //------------------------------------------------------------------- int get_iamv2api_token_request(const std::string& strurl, int tokenttl, const std::string& strttlhdr, std::string& token); int get_iamrole_request(const std::string& strurl, const std::string& striamtoken, std::string& token); int get_iamcred_request(const std::string& strurl, const std::string& striamtoken, const std::string& stribmsecret, std::string& cred); #endif // S3FS_THREADREQS_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
6,318
C++
.h
185
31.935135
143
0.639843
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,487
types.h
s3fs-fuse_s3fs-fuse/src/types.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_TYPES_H_ #define S3FS_TYPES_H_ #include <cstdlib> #include <cstdint> #include <cstring> #include <string> #include <map> #include <list> #include <utility> #include <vector> // // For extended attribute // (HAVE_XXX symbols are defined in config.h) // #ifdef HAVE_SYS_EXTATTR_H #include <sys/extattr.h> #elif HAVE_ATTR_XATTR_H #include <attr/xattr.h> #elif HAVE_SYS_XATTR_H #include <sys/xattr.h> #endif //------------------------------------------------------------------- // xattrs_t //------------------------------------------------------------------- // // Header "x-amz-meta-xattr" is for extended attributes. // This header is url encoded string which is json formatted. // x-amz-meta-xattr:urlencode({"xattr-1":"base64(value-1)","xattr-2":"base64(value-2)","xattr-3":"base64(value-3)"}) // typedef std::map<std::string, std::string> xattrs_t; //------------------------------------------------------------------- // acl_t //------------------------------------------------------------------- enum class acl_t : uint8_t { PRIVATE, PUBLIC_READ, PUBLIC_READ_WRITE, AWS_EXEC_READ, AUTHENTICATED_READ, BUCKET_OWNER_READ, BUCKET_OWNER_FULL_CONTROL, LOG_DELIVERY_WRITE, UNKNOWN }; inline const char* str(acl_t value) { switch(value){ case acl_t::PRIVATE: return "private"; case acl_t::PUBLIC_READ: return "public-read"; case acl_t::PUBLIC_READ_WRITE: return "public-read-write"; case acl_t::AWS_EXEC_READ: return "aws-exec-read"; case acl_t::AUTHENTICATED_READ: return "authenticated-read"; case acl_t::BUCKET_OWNER_READ: return "bucket-owner-read"; case acl_t::BUCKET_OWNER_FULL_CONTROL: return "bucket-owner-full-control"; case acl_t::LOG_DELIVERY_WRITE: return "log-delivery-write"; case acl_t::UNKNOWN: return nullptr; } abort(); } inline acl_t to_acl(const char *acl) { if(0 == strcmp(acl, "private")){ return acl_t::PRIVATE; }else if(0 == strcmp(acl, "public-read")){ return acl_t::PUBLIC_READ; }else if(0 == strcmp(acl, "public-read-write")){ return acl_t::PUBLIC_READ_WRITE; }else if(0 == strcmp(acl, "aws-exec-read")){ return acl_t::AWS_EXEC_READ; }else if(0 == strcmp(acl, "authenticated-read")){ return acl_t::AUTHENTICATED_READ; }else if(0 == strcmp(acl, "bucket-owner-read")){ return acl_t::BUCKET_OWNER_READ; }else if(0 == strcmp(acl, "bucket-owner-full-control")){ return acl_t::BUCKET_OWNER_FULL_CONTROL; }else if(0 == strcmp(acl, "log-delivery-write")){ return acl_t::LOG_DELIVERY_WRITE; }else{ return acl_t::UNKNOWN; } } //------------------------------------------------------------------- // sse_type_t //------------------------------------------------------------------- enum class sse_type_t : uint8_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 }; enum class signature_type_t : uint8_t { V2_ONLY, V4_ONLY, V2_OR_V4 }; //---------------------------------------------- // etaglist_t / filepart / untreatedpart //---------------------------------------------- // // Etag string and part number pair // struct etagpair { std::string etag; // expected etag value int part_num; // part number explicit etagpair(const char* petag = nullptr, int part = -1) : etag(petag ? petag : ""), part_num(part) {} ~etagpair() { clear(); } void clear() { etag.clear(); part_num = -1; } }; // Requires pointer stability and thus must be a list not a vector typedef std::list<etagpair> etaglist_t; struct petagpool { // Requires pointer stability and thus must be a list not a vector std::list<etagpair> petaglist; ~petagpool() { clear(); } void clear() { petaglist.clear(); } etagpair* add(const etagpair& etag_entity) { petaglist.push_back(etag_entity); return &petaglist.back(); } }; // // Each part information for Multipart upload // struct filepart { bool uploaded = false; // 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 off_t size; // uploading size bool is_copy; // whether is copy multipart etagpair* petag; // use only parallel upload explicit filepart(bool is_uploaded = false, int _fd = -1, off_t part_start = 0, off_t part_size = -1, bool is_copy_part = false, etagpair* petagpair = nullptr) : fd(_fd), startpos(part_start), size(part_size), is_copy(is_copy_part), petag(petagpair) {} ~filepart() { clear(); } void clear() { uploaded = false; etag = ""; fd = -1; startpos = 0; size = -1; is_copy = false; petag = nullptr; } void add_etag_list(etaglist_t& list, int partnum = -1) { if(-1 == partnum){ partnum = static_cast<int>(list.size()) + 1; } list.emplace_back(nullptr, partnum); petag = &list.back(); } void set_etag(etagpair* petagobj) { petag = petagobj; } int get_part_number() const { if(!petag){ return -1; } return petag->part_num; } }; typedef std::vector<filepart> filepart_list_t; // // Each part information for Untreated parts // struct untreatedpart { off_t start; // untreated start position off_t size; // number of untreated bytes long untreated_tag; // untreated part tag explicit untreatedpart(off_t part_start = 0, off_t part_size = 0, long part_untreated_tag = 0) : start(part_start), size(part_size), untreated_tag(part_untreated_tag) { if(part_start < 0 || part_size <= 0){ clear(); // wrong parameter, so clear value. } } ~untreatedpart() { clear(); } void clear() { start = 0; size = 0; untreated_tag = 0; } // [NOTE] // Check if the areas overlap // However, even if the areas do not overlap, this method returns true if areas are adjacent. // bool check_overlap(off_t chk_start, off_t chk_size) const { if(chk_start < 0 || chk_size <= 0 || start < 0 || size <= 0 || (chk_start + chk_size) < start || (start + size) < chk_start){ return false; } return true; } bool stretch(off_t add_start, off_t add_size, long tag) { if(!check_overlap(add_start, add_size)){ return false; } off_t new_start = std::min(start, add_start); off_t new_next_start = std::max((start + size), (add_start + add_size)); start = new_start; size = new_next_start - new_start; untreated_tag = tag; return true; } }; typedef std::vector<untreatedpart> untreated_list_t; // // Information on each part of multipart upload // struct mp_part { off_t start; off_t size; int part_num; // Set only for information to upload explicit mp_part(off_t set_start = 0, off_t set_size = 0, int part = 0) : start(set_start), size(set_size), part_num(part) {} }; typedef std::vector<struct mp_part> mp_part_list_t; inline off_t total_mp_part_list(const mp_part_list_t& mplist) { off_t size = 0; for(auto iter = mplist.cbegin(); iter != mplist.cend(); ++iter){ size += iter->size; } return size; } // // Rename directory struct // struct mvnode { mvnode(std::string old_path, std::string new_path, bool is_dir, bool is_normdir) : old_path(std::move(old_path)) , new_path(std::move(new_path)) , is_dir(is_dir) , is_normdir(is_normdir) {} std::string old_path; std::string new_path; bool is_dir; bool is_normdir; }; //------------------------------------------------------------------- // mimes_t //------------------------------------------------------------------- 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<std::string, std::string, case_insensitive_compare_func> mimes_t; //------------------------------------------------------------------- // Typedefs specialized for use //------------------------------------------------------------------- typedef std::vector<std::string> readline_t; typedef std::map<std::string, std::string> kvmap_t; typedef std::map<std::string, kvmap_t> bucketkvmap_t; #endif // S3FS_TYPES_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
10,045
C++
.h
321
26.847352
256
0.570661
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,488
s3fs_extcred.h
s3fs-fuse_s3fs-fuse/src/s3fs_extcred.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Takeshi Nakatani <ggtakec@gmail.com> * * 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_EXTCRED_H_ #define S3FS_EXTCRED_H_ //------------------------------------------------------------------- // Attributes(weak) : use only in s3fs-fuse internally //------------------------------------------------------------------- // [NOTE] // This macro is only used inside s3fs-fuse. // External projects that utilize this header file substitute empty //values as follows: // #ifndef S3FS_FUNCATTR_WEAK #define S3FS_FUNCATTR_WEAK #endif extern "C" { //------------------------------------------------------------------- // Prototype for External Credential 4 functions //------------------------------------------------------------------- // // [Required] VersionS3fsCredential // // Returns the library name and version as a string. // extern const char* VersionS3fsCredential(bool detail) S3FS_FUNCATTR_WEAK; // // [Optional] InitS3fsCredential // // A function that does the necessary initialization after the library is // loaded. This function is called only once immediately after loading the // library. // If there is a required initialization inside the library, implement it. // Implementation of this function is optional and not required. If not // implemented, it will not be called. // // const char* popts : String passed with the credlib_opts option. If the // credlib_opts option is not specified, nullptr will be // passed. // char** pperrstr : pperrstr is used to pass the error message to the // caller when an error occurs. // If this pointer is not nullptr, you can allocate memory // and set an error message to it. The allocated memory // area is freed by the caller. // extern bool InitS3fsCredential(const char* popts, char** pperrstr) S3FS_FUNCATTR_WEAK; // // [Optional] FreeS3fsCredential // // A function that is called only once just before the library is unloaded. // If there is a required discard process in the library, implement it. // Implementation of this feature is optional and not required. // If not implemented, it will not be called. // // char** pperrstr : pperrstr is used to pass the error message to the // caller when an error occurs. // If this pointer is not nullptr, you can allocate memory // and set an error message to it. The allocated memory // area is freed by the caller. // extern bool FreeS3fsCredential(char** pperrstr) S3FS_FUNCATTR_WEAK; // // [Required] UpdateS3fsCredential // // A function that updates the token. // // char** ppaccess_key_id : Allocate and set "Access Key ID" string // area to *ppaccess_key_id. // char** ppserect_access_key : Allocate and set "Access Secret Key ID" // string area to *ppserect_access_key. // char** ppaccess_token : Allocate and set "Token" string area to // *ppaccess_token. // long long* ptoken_expire : Set token expire time(time_t) value to // *ptoken_expire. // This is essentially a time_t* variable. // To avoid system differences about time_t // size, long long* is used. // When setting the value, cast from time_t // to long long to set the value. // char** pperrstr : pperrstr is used to pass the error message to the // caller when an error occurs. // // For all argument of the character string pointer(char **) set the // allocated string area. The allocated area is freed by the caller. // extern bool UpdateS3fsCredential(char** ppaccess_key_id, char** ppserect_access_key, char** ppaccess_token, long long* ptoken_expire, char** pperrstr) S3FS_FUNCATTR_WEAK; //--------------------------------------------------------- // Typedef Prototype function //--------------------------------------------------------- // // const char* VersionS3fsCredential() // typedef const char* (*fp_VersionS3fsCredential)(bool detail); // // bool InitS3fsCredential(char** pperrstr) // typedef bool (*fp_InitS3fsCredential)(const char* popts, char** pperrstr); // // bool FreeS3fsCredential(char** pperrstr) // typedef bool (*fp_FreeS3fsCredential)(char** pperrstr); // // bool UpdateS3fsCredential(char** ppaccess_key_id, char** ppserect_access_key, char** ppaccess_token, long long* ptoken_expire, char** pperrstr) // typedef bool (*fp_UpdateS3fsCredential)(char** ppaccess_key_id, char** ppserect_access_key, char** ppaccess_token, long long* ptoken_expire, char** pperrstr); } // extern "C" #endif // S3FS_EXTCRED_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
5,740
C++
.h
131
42.580153
170
0.63456
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,489
string_util.h
s3fs-fuse_s3fs-fuse/src/string_util.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_ #include <cstring> #include <ctime> #include <string> #include <strings.h> // // A collection of string utilities for manipulating URLs and HTTP responses. // //------------------------------------------------------------------- // Global variables //------------------------------------------------------------------- static constexpr char SPACES[] = " \t\r\n"; //------------------------------------------------------------------- // Inline functions //------------------------------------------------------------------- class CaseInsensitiveStringView { public: explicit CaseInsensitiveStringView(const std::string &str) : str(str.c_str()) {} bool operator==(const char *other) const { return strcasecmp(str, other) == 0; } bool is_prefix(const char *prefix) const { return strncasecmp(str, prefix, strlen(prefix)) == 0; } private: const char *str; }; static inline bool is_prefix(const char *str, const char *prefix) { return strncmp(str, prefix, strlen(prefix)) == 0; } static inline const char* SAFESTRPTR(const char *strptr) { return strptr ? strptr : ""; } //------------------------------------------------------------------- // Macros(WTF8) //------------------------------------------------------------------- #define WTF8_ENCODE(ARG) \ std::string ARG##_buf; \ const char * ARG = _##ARG; \ if (use_wtf8 && s3fs_wtf8_encode( _##ARG, 0 )) { \ s3fs_wtf8_encode( _##ARG, &ARG##_buf); \ ARG = ARG##_buf.c_str(); \ } //------------------------------------------------------------------- // Utilities //------------------------------------------------------------------- // TODO: rename to to_string? std::string str(const struct timespec& value); // // Cross-platform strptime // const char* s3fs_strptime(const char* s, const char* f, struct tm* tm); // // Convert string to off_t. Returns false on bad input. // Replacement for C++11 std::stoll. // bool s3fs_strtoofft(off_t* value, const char* str, int base = 0); // // This function returns 0 if a value that cannot be converted is specified. // Only call if 0 is considered an error and the operation can continue. // off_t cvt_strtoofft(const char* str, int base); // // String Manipulation // std::string trim_left(std::string s, const char *t = SPACES); std::string trim_right(std::string s, const char *t = SPACES); std::string trim(std::string s, const char *t = SPACES); std::string lower(std::string s); std::string upper(std::string s); std::string peeloff(std::string s); // // Date string // std::string get_date_rfc850(); 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); bool get_unixtime_from_iso8601(const char* pdate, time_t& unixtime); bool convert_unixtime_from_option_arg(const char* argv, time_t& unixtime); // // For encoding // std::string urlEncodeGeneral(const std::string &s); std::string urlEncodePath(const std::string &s); std::string urlEncodeQuery(const std::string &s); std::string urlDecode(const std::string& s); bool takeout_str_dquart(std::string& str); bool get_keyword_value(const std::string& target, const char* keyword, std::string& value); // // For binary string // std::string s3fs_hex_lower(const unsigned char* input, size_t length); std::string s3fs_hex_upper(const unsigned char* input, size_t length); std::string s3fs_base64(const unsigned char* input, size_t length); std::string s3fs_decode64(const char* input, size_t input_len); // // WTF8 // bool s3fs_wtf8_encode(const char *s, std::string *result); std::string s3fs_wtf8_encode(const std::string &s); bool s3fs_wtf8_decode(const char *s, std::string *result); std::string s3fs_wtf8_decode(const std::string &s); // // For CR in XML // std::string get_encoded_cr_code(const char* pbase); std::string get_decoded_cr_code(const char* pencode); #endif // S3FS_STRING_UTIL_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
4,953
C++
.h
129
36.573643
119
0.637687
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,490
common.h
s3fs-fuse_s3fs-fuse/src/common.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 <string> #include <sys/types.h> #include "../config.h" //------------------------------------------------------------------- // Global variables //------------------------------------------------------------------- // TODO: namespace these static constexpr int64_t FIVE_GB = 5LL * 1024LL * 1024LL * 1024LL; static constexpr off_t MIN_MULTIPART_SIZE = 5 * 1024 * 1024; extern bool foreground; extern bool nomultipart; extern bool pathrequeststyle; extern bool complement_stat; extern bool noxmlns; extern std::string program_name; extern std::string service_path; extern std::string s3host; extern std::string mount_prefix; extern std::string endpoint; extern std::string cipher_suites; extern std::string instance_name; //------------------------------------------------------------------- // For weak attribute //------------------------------------------------------------------- #define S3FS_FUNCATTR_WEAK __attribute__ ((weak,unused)) //------------------------------------------------------------------- // For clang -Wthread-safety //------------------------------------------------------------------- #if defined(__clang__) #define THREAD_ANNOTATION_ATTRIBUTE(x) __attribute__((x)) #else #define THREAD_ANNOTATION_ATTRIBUTE(x) // no-op #endif #define GUARDED_BY(x) \ THREAD_ANNOTATION_ATTRIBUTE(guarded_by(x)) #define PT_GUARDED_BY(x) \ THREAD_ANNOTATION_ATTRIBUTE(pt_guarded_by(x)) #define REQUIRES(...) \ THREAD_ANNOTATION_ATTRIBUTE(requires_capability(__VA_ARGS__)) #define RETURN_CAPABILITY(...) \ THREAD_ANNOTATION_ATTRIBUTE(lock_returned(__VA_ARGS__)) #define ACQUIRED_BEFORE(...) \ THREAD_ANNOTATION_ATTRIBUTE(acquired_before(__VA_ARGS__)) #define ACQUIRED_AFTER(...) \ THREAD_ANNOTATION_ATTRIBUTE(acquired_after(__VA_ARGS__)) #define NO_THREAD_SAFETY_ANALYSIS \ THREAD_ANNOTATION_ATTRIBUTE(no_thread_safety_analysis) #endif // S3FS_COMMON_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
3,022
C++
.h
77
37.441558
82
0.624104
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,491
s3fs.h
s3fs-fuse_s3fs-fuse/src/s3fs.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_H_ #define S3FS_S3FS_H_ #define FUSE_USE_VERSION 26 #include <fuse.h> #define S3FS_FUSE_EXIT() \ do{ \ struct fuse_context* pcxt = fuse_get_context(); \ if(pcxt){ \ fuse_exit(pcxt->fuse); \ } \ }while(0) // [NOTE] // 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. // Address of gratitude, this workaround quotes a document of // libxml2.( http://xmlsoft.org/xmlmem.html ) // // When valgrind is used to test memory leak of s3fs, a large // amount of chunk may be reported. You can check the memory // release accurately by defining the S3FS_MALLOC_TRIM flag // and building it. Also, when executing s3fs, you can define // the MMAP_THRESHOLD environment variable and check more // accurate memory leak.( see, man 3 free ) // #ifdef S3FS_MALLOC_TRIM #ifdef HAVE_MALLOC_TRIM #include <malloc.h> #define S3FS_MALLOCTRIM(pad) malloc_trim(pad) #else // HAVE_MALLOC_TRIM #define S3FS_MALLOCTRIM(pad) #endif // HAVE_MALLOC_TRIM #else // S3FS_MALLOC_TRIM #define S3FS_MALLOCTRIM(pad) #endif // S3FS_MALLOC_TRIM #endif // S3FS_S3FS_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,280
C++
.h
64
33.171875
82
0.721141
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,492
addhead.h
s3fs-fuse_s3fs-fuse/src/addhead.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_ADDHEAD_H_ #define S3FS_ADDHEAD_H_ #include <memory> #include <regex.h> #include <string> #include <utility> #include <vector> #include "metaheader.h" //---------------------------------------------- // Structure / Typedef //---------------------------------------------- typedef std::unique_ptr<regex_t, decltype(&regfree)> RegexPtr; struct add_header{ add_header(RegexPtr pregex, std::string basestring, std::string headkey, std::string headvalue) : pregex(std::move(pregex)) , basestring(std::move(basestring)) , headkey(std::move(headkey)) , headvalue(std::move(headvalue)) {} add_header(const add_header&) = delete; add_header(add_header&& val) = default; add_header& operator=(const add_header&) = delete; add_header& operator=(add_header&&) = delete; RegexPtr pregex; // not nullptr means using regex, nullptr means comparing suffix directly. std::string basestring; std::string headkey; std::string headvalue; }; typedef std::vector<add_header> addheadlist_t; //---------------------------------------------- // Class AdditionalHeader //---------------------------------------------- class AdditionalHeader { private: static AdditionalHeader singleton; bool is_enable; addheadlist_t addheadlist; protected: AdditionalHeader(); ~AdditionalHeader(); public: AdditionalHeader(const AdditionalHeader&) = delete; AdditionalHeader(AdditionalHeader&&) = delete; AdditionalHeader& operator=(const AdditionalHeader&) = delete; AdditionalHeader& operator=(AdditionalHeader&&) = delete; // Reference singleton static AdditionalHeader* get() { return &singleton; } bool Load(const char* file); void Unload(); bool AddHeader(headers_t& meta, const char* path) const; struct curl_slist* AddHeader(struct curl_slist* list, const char* path) const; bool Dump() const; }; #endif // S3FS_ADDHEAD_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
3,054
C++
.h
82
33.243902
108
0.652909
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,493
threadpoolman.h
s3fs-fuse_s3fs-fuse/src/threadpoolman.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_THREADPOOLMAN_H_ #define S3FS_THREADPOOLMAN_H_ #include <atomic> #include <future> #include <list> #include <mutex> #include <vector> #include "common.h" #include "psemaphore.h" //------------------------------------------------ // Typedefs for functions and structures //------------------------------------------------ // // Prototype function // typedef void* (*thpoolman_worker)(void*); // // Parameter structure // // [NOTE] // The args member is a value that is an argument of the worker function. // The psem member is allowed nullptr. If it is not nullptr, the post() method is // called when finishing the function. // struct thpoolman_param { void* args = nullptr; Semaphore* psem = nullptr; thpoolman_worker pfunc = nullptr; }; typedef std::list<thpoolman_param> thpoolman_params_t; //------------------------------------------------ // Class ThreadPoolMan //------------------------------------------------ class ThreadPoolMan { private: static std::unique_ptr<ThreadPoolMan> singleton; std::atomic<bool> is_exit; Semaphore thpoolman_sem; std::mutex thread_list_lock; std::vector<std::pair<std::thread, std::future<int>>> thread_list GUARDED_BY(thread_list_lock); thpoolman_params_t instruction_list GUARDED_BY(thread_list_lock); private: static void Worker(ThreadPoolMan* psingleton, std::promise<int> promise); explicit ThreadPoolMan(int count = 1); bool IsExit() const; void SetExitFlag(bool exit_flag); bool StopThreads(); bool StartThreads(int count); void SetInstruction(const thpoolman_param& pparam); public: ~ThreadPoolMan(); ThreadPoolMan(const ThreadPoolMan&) = delete; ThreadPoolMan(ThreadPoolMan&&) = delete; ThreadPoolMan& operator=(const ThreadPoolMan&) = delete; ThreadPoolMan& operator=(ThreadPoolMan&&) = delete; static bool Initialize(int count); static void Destroy(); static bool Instruct(const thpoolman_param& pparam); static bool AwaitInstruct(const thpoolman_param& param); }; #endif // S3FS_THREADPOOLMAN_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
3,199
C++
.h
90
31.933333
103
0.661708
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,494
curl_multi.h
s3fs-fuse_s3fs-fuse/src/curl_multi.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_MULTI_H_ #define S3FS_CURL_MULTI_H_ #include <future> #include <memory> #include <mutex> #include <thread> #include <vector> #include "common.h" //---------------------------------------------- // Typedef //---------------------------------------------- class S3fsCurl; typedef std::vector<std::unique_ptr<S3fsCurl>> s3fscurllist_t; typedef bool (*S3fsMultiSuccessCallback)(S3fsCurl* s3fscurl, void* param); // callback for succeed multi request typedef bool (*S3fsMultiNotFoundCallback)(S3fsCurl* s3fscurl, void* param); // callback for succeed multi request typedef std::unique_ptr<S3fsCurl> (*S3fsMultiRetryCallback)(S3fsCurl* s3fscurl); // callback for failure and retrying //---------------------------------------------- // class S3fsMultiCurl //---------------------------------------------- class S3fsMultiCurl { private: const int maxParallelism; s3fscurllist_t clist_all; // all of curl requests s3fscurllist_t clist_req; // curl requests are sent bool not_abort; // complete all requests without aborting on errors S3fsMultiSuccessCallback SuccessCallback; S3fsMultiNotFoundCallback NotFoundCallback; S3fsMultiRetryCallback RetryCallback; void* pSuccessCallbackParam; void* pNotFoundCallbackParam; std::mutex completed_tids_lock; std::vector<std::thread::id> completed_tids GUARDED_BY(completed_tids_lock); private: bool ClearEx(bool is_all); int MultiPerform(); int MultiRead(); static void RequestPerformWrapper(S3fsCurl* s3fscurl, std::promise<int> promise); public: explicit S3fsMultiCurl(int maxParallelism, bool not_abort = false); ~S3fsMultiCurl(); S3fsMultiCurl(const S3fsMultiCurl&) = delete; S3fsMultiCurl(S3fsMultiCurl&&) = delete; S3fsMultiCurl& operator=(const S3fsMultiCurl&) = delete; S3fsMultiCurl& operator=(S3fsMultiCurl&&) = delete; int GetMaxParallelism() const { return maxParallelism; } S3fsMultiSuccessCallback SetSuccessCallback(S3fsMultiSuccessCallback function); S3fsMultiNotFoundCallback SetNotFoundCallback(S3fsMultiNotFoundCallback function); S3fsMultiRetryCallback SetRetryCallback(S3fsMultiRetryCallback function); void* SetSuccessCallbackParam(void* param); void* SetNotFoundCallbackParam(void* param); bool Clear() { return ClearEx(true); } bool SetS3fsCurlObject(std::unique_ptr<S3fsCurl> s3fscurl); int Request(); }; #endif // S3FS_CURL_MULTI_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
3,618
C++
.h
83
39.144578
118
0.684569
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,495
test_util.h
s3fs-fuse_s3fs-fuse/src/test_util.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2014 Andrew Gaul <andrew@gaul.org> * * 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_TEST_UTIL_H_ #define S3FS_TEST_UTIL_H_ #include <cstdio> #include <cstdlib> #include <iostream> #include <string> #include "string_util.h" template <typename T> inline 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::cerr << std::endl; abort(); } } template <> inline void assert_equals(const std::string &x, const std::string &y, const char *file, int line) { if (x != y) { std::cerr << x << " != " << y << " at " << file << ":" << line << std::endl; std::cerr << s3fs_hex_lower(reinterpret_cast<const unsigned char *>(x.c_str()), x.size()) << std::endl; std::cerr << s3fs_hex_lower(reinterpret_cast<const unsigned char *>(y.c_str()), y.size()) << std::endl; abort(); } } template <typename T> inline void assert_nequals(const T &x, const T &y, const char *file, int line) { if (x == y) { std::cerr << x << " == " << y << " at " << file << ":" << line << std::endl; abort(); } } template <> inline void assert_nequals(const std::string &x, const std::string &y, const char *file, int line) { if (x == y) { std::cerr << x << " == " << y << " at " << file << ":" << line << std::endl; std::cerr << s3fs_hex_lower(reinterpret_cast<const unsigned char *>(x.c_str()), x.size()) << std::endl; std::cerr << s3fs_hex_lower(reinterpret_cast<const unsigned char *>(y.c_str()), y.size()) << std::endl; abort(); } } inline void assert_strequals(const char *x, const char *y, const char *file, int line) { if(x == nullptr && y == nullptr){ return; // cppcheck-suppress nullPointerRedundantCheck } else if(x == nullptr || y == nullptr || strcmp(x, y) != 0){ std::cerr << (x ? x : "null") << " != " << (y ? y : "null") << " at " << file << ":" << line << std::endl; abort(); } } inline void assert_bufequals(const char *x, size_t len1, const char *y, size_t len2, const char *file, int line) { if(x == nullptr && y == nullptr){ return; // cppcheck-suppress nullPointerRedundantCheck } else if(x == nullptr || y == nullptr || len1 != len2 || memcmp(x, y, len1) != 0){ std::cerr << (x ? std::string(x, len1) : "null") << " != " << (y ? std::string(y, len2) : "null") << " at " << file << ":" << line << std::endl; abort(); } } #define ASSERT_TRUE(x) assert_equals((x), true, __FILE__, __LINE__) #define ASSERT_FALSE(x) assert_equals((x), false, __FILE__, __LINE__) #define ASSERT_EQUALS(x, y) assert_equals((x), (y), __FILE__, __LINE__) #define ASSERT_NEQUALS(x, y) assert_nequals((x), (y), __FILE__, __LINE__) #define ASSERT_STREQUALS(x, y) assert_strequals((x), (y), __FILE__, __LINE__) #define ASSERT_BUFEQUALS(x, len1, y, len2) assert_bufequals((x), (len1), (y), (len2), __FILE__, __LINE__) #endif // S3FS_TEST_UTIL_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
3,955
C++
.h
94
38.595745
152
0.601871
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,496
fdcache.h
s3fs-fuse_s3fs-fuse/src/fdcache.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_FDCACHE_H_ #define S3FS_FDCACHE_H_ #include <mutex> #include <string> #include "common.h" #include "fdcache_entity.h" #include "s3fs_util.h" //------------------------------------------------ // class FdManager //------------------------------------------------ class FdManager { private: static FdManager singleton; static std::mutex fd_manager_lock; static std::mutex cache_cleanup_lock; static std::mutex reserved_diskspace_lock; static std::mutex except_entmap_lock; static std::string cache_dir; static bool check_cache_dir_exist; static off_t free_disk_space GUARDED_BY(reserved_diskspace_lock); // limit free disk space static off_t fake_used_disk_space GUARDED_BY(reserved_diskspace_lock); // difference between fake free disk space and actual at startup(for test/debug) static std::string check_cache_output; static bool checked_lseek; static bool have_lseek_hole; static std::string tmp_dir; fdent_map_t fent GUARDED_BY(fd_manager_lock); fdent_map_t except_fent GUARDED_BY(except_entmap_lock); // A map of delayed deletion fdentity private: static off_t GetFreeDiskSpaceHasLock(const char* path) REQUIRES(FdManager::reserved_diskspace_lock); static off_t GetTotalDiskSpace(const char* path); static bool IsDir(const std::string& dir); static int GetVfsStat(const char* path, struct statvfs* vfsbuf); static off_t GetEnsureFreeDiskSpaceHasLock() REQUIRES(FdManager::reserved_diskspace_lock); // Returns the number of open pseudo fd. int GetPseudoFdCount(const char* path) REQUIRES(fd_manager_lock); bool UpdateEntityToTempPath() REQUIRES(fd_manager_lock); void CleanupCacheDirInternal(const std::string &path = "") REQUIRES(cache_cleanup_lock); bool RawCheckAllCache(FILE* fp, const char* cache_stat_top_dir, const char* sub_path, int& total_file_cnt, int& err_file_cnt, int& err_dir_cnt); public: FdManager(); ~FdManager(); FdManager(const FdManager&) = delete; FdManager(FdManager&&) = delete; FdManager& operator=(const FdManager&) = delete; FdManager& operator=(FdManager&&) = delete; // Reference singleton static FdManager* get() { return &singleton; } static bool DeleteCacheDirectory(); static int DeleteCacheFile(const char* path); static bool SetCacheDir(const char* dir); static bool IsCacheDir() { return !FdManager::cache_dir.empty(); } static const char* GetCacheDir() { return FdManager::cache_dir.c_str(); } static bool SetCacheCheckOutput(const char* path); static const char* GetCacheCheckOutput() { return FdManager::check_cache_output.c_str(); } static bool MakeCachePath(const char* path, std::string& cache_path, bool is_create_dir = true, bool is_mirror_path = false); static bool CheckCacheTopDir(); static bool MakeRandomTempPath(const char* path, std::string& tmppath); static bool SetCheckCacheDirExist(bool is_check); static bool CheckCacheDirExist(); static bool HasOpenEntityFd(const char* path); static int GetOpenFdCount(const char* path); static off_t GetEnsureFreeDiskSpace() { const std::lock_guard<std::mutex> lock(FdManager::reserved_diskspace_lock); return FdManager::GetEnsureFreeDiskSpaceHasLock(); } static off_t SetEnsureFreeDiskSpace(off_t size); static bool InitFakeUsedDiskSize(off_t fake_freesize); static bool IsSafeDiskSpace(const char* path, off_t size, bool withmsg = false); static void FreeReservedDiskSpace(off_t size); static bool ReserveDiskSpace(off_t size); static bool HaveLseekHole(); static bool SetTmpDir(const char* dir); static bool CheckTmpDirExist(); static std::unique_ptr<FILE, decltype(&s3fs_fclose)> MakeTempFile(); static off_t GetTotalDiskSpaceByRatio(int ratio); // Return FdEntity associated with path, returning nullptr on error. This operation increments the reference count; callers must decrement via Close after use. FdEntity* GetFdEntity(const char* path, int& existfd, bool newfd = true) { const std::lock_guard<std::mutex> lock(FdManager::fd_manager_lock); return GetFdEntityHasLock(path, existfd, newfd); } FdEntity* GetFdEntityHasLock(const char* path, int& existfd, bool newfd = true) REQUIRES(FdManager::fd_manager_lock); FdEntity* Open(int& fd, const char* path, const headers_t* pmeta, off_t size, const struct timespec& ts_mctime, int flags, bool force_tmpfile, bool is_create, bool ignore_modify); FdEntity* GetExistFdEntity(const char* path, int existfd = -1); FdEntity* OpenExistFdEntity(const char* path, int& fd, int flags = O_RDONLY); void Rename(const std::string &from, const std::string &to); bool Close(FdEntity* ent, int fd); bool ChangeEntityToTempPath(std::shared_ptr<FdEntity> ent, const char* path); void CleanupCacheDir(); bool CheckAllCache(); }; #endif // S3FS_FDCACHE_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
6,185
C++
.h
120
46.291667
185
0.694265
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,497
fdcache_stat.h
s3fs-fuse_s3fs-fuse/src/fdcache_stat.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_FDCACHE_STAT_H_ #define S3FS_FDCACHE_STAT_H_ #include <string> //------------------------------------------------ // CacheFileStat //------------------------------------------------ class CacheFileStat { private: std::string path; int fd; private: static int MakeCacheFileStatPath(const char* path, std::string& sfile_path, bool is_create_dir = true); bool RawOpen(bool readonly); public: static std::string GetCacheFileStatTopDir(); static int DeleteCacheFileStat(const char* path); static bool CheckCacheFileStatTopDir(); static bool DeleteCacheFileStatDirectory(); static bool RenameCacheFileStat(const char* oldpath, const char* newpath); explicit CacheFileStat(const char* tpath = nullptr); ~CacheFileStat(); CacheFileStat(const CacheFileStat&) = delete; CacheFileStat(CacheFileStat&&) = delete; CacheFileStat& operator=(const CacheFileStat&) = delete; CacheFileStat& operator=(CacheFileStat&&) = delete; bool Open(); bool ReadOnlyOpen(); bool Release(); bool SetPath(const char* tpath, bool is_open = true); int GetFd() const { return fd; } }; #endif // S3FS_FDCACHE_STAT_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,260
C++
.h
60
33.333333
111
0.673516
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,498
syncfiller.h
s3fs-fuse_s3fs-fuse/src/syncfiller.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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 SYNCFILLER_H_ #define SYNCFILLER_H_ #include <string> #include <mutex> #include <vector> #include <set> #include "s3fs.h" //---------------------------------------------- // class SyncFiller //---------------------------------------------- // // A synchronous class that calls the fuse_fill_dir_t // function that processes the readdir data // class SyncFiller { private: mutable std::mutex filler_lock; void* filler_buff; fuse_fill_dir_t filler_func; std::set<std::string> filled; public: explicit SyncFiller(void* buff = nullptr, fuse_fill_dir_t filler = nullptr); ~SyncFiller() = default; SyncFiller(const SyncFiller&) = delete; SyncFiller(SyncFiller&&) = delete; SyncFiller& operator=(const SyncFiller&) = delete; SyncFiller& operator=(SyncFiller&&) = delete; int Fill(const std::string& name, const struct stat *stbuf, off_t off); int SufficiencyFill(const std::vector<std::string>& pathlist); }; #endif // SYNCFILLER_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
2,055
C++
.h
59
31.627119
84
0.667505
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,499
s3fs_logger.h
s3fs-fuse_s3fs-fuse/src/s3fs_logger.h
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * 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_LOGGER_H_ #define S3FS_LOGGER_H_ #include <cstdarg> #include <cstdint> #include <cstdio> #include <string> #include <syslog.h> #include <sys/time.h> #include "common.h" #ifdef CLOCK_MONOTONIC_COARSE #define S3FS_CLOCK_MONOTONIC CLOCK_MONOTONIC_COARSE #else // case of OSX #define S3FS_CLOCK_MONOTONIC CLOCK_MONOTONIC #endif //------------------------------------------------------------------- // S3fsLog class //------------------------------------------------------------------- class S3fsLog { public: enum s3fs_log_level : uint8_t { LEVEL_CRIT = 0, // LEVEL_CRIT LEVEL_ERR = 1, // LEVEL_ERR LEVEL_WARN = 3, // LEVEL_WARNING LEVEL_INFO = 7, // LEVEL_INFO LEVEL_DBG = 15 // LEVEL_DEBUG }; protected: static constexpr int NEST_MAX = 4; static constexpr const char* nest_spaces[NEST_MAX] = {"", " ", " ", " "}; static constexpr char LOGFILEENV[] = "S3FS_LOGFILE"; static constexpr char MSGTIMESTAMP[] = "S3FS_MSGTIMESTAMP"; static S3fsLog* pSingleton; static s3fs_log_level debug_level; static FILE* logfp; static std::string logfile; static bool time_stamp; protected: bool LowLoadEnv(); bool LowSetLogfile(const char* pfile); s3fs_log_level LowSetLogLevel(s3fs_log_level level); s3fs_log_level LowBumpupLogLevel(); public: static bool IsS3fsLogLevel(s3fs_log_level level); static bool IsS3fsLogCrit() { return IsS3fsLogLevel(LEVEL_CRIT); } static bool IsS3fsLogErr() { return IsS3fsLogLevel(LEVEL_ERR); } static bool IsS3fsLogWarn() { return IsS3fsLogLevel(LEVEL_WARN); } static bool IsS3fsLogInfo() { return IsS3fsLogLevel(LEVEL_INFO); } static bool IsS3fsLogDbg() { return IsS3fsLogLevel(LEVEL_DBG); } static constexpr int GetSyslogLevel(s3fs_log_level level) { return ( LEVEL_DBG == (level & LEVEL_DBG) ? LOG_DEBUG : LEVEL_INFO == (level & LEVEL_DBG) ? LOG_INFO : LEVEL_WARN == (level & LEVEL_DBG) ? LOG_WARNING : LEVEL_ERR == (level & LEVEL_DBG) ? LOG_ERR : LOG_CRIT ); } static std::string GetCurrentTime(); static constexpr const char* GetLevelString(s3fs_log_level level) { return ( LEVEL_DBG == (level & LEVEL_DBG) ? "[DBG] " : LEVEL_INFO == (level & LEVEL_DBG) ? "[INF] " : LEVEL_WARN == (level & LEVEL_DBG) ? "[WAN] " : LEVEL_ERR == (level & LEVEL_DBG) ? "[ERR] " : "[CRT] " ); } static constexpr const char* GetS3fsLogNest(int nest) { return nest_spaces[nest < NEST_MAX ? nest : NEST_MAX - 1]; } static bool IsSetLogFile() { return (nullptr != logfp); } static FILE* GetOutputLogFile() { return (logfp ? logfp : stdout); } static FILE* GetErrorLogFile() { return (logfp ? logfp : stderr); } static void SeekEnd() { if(logfp){ fseek(logfp, 0, SEEK_END); } } static void Flush() { if(logfp){ fflush(logfp); } } static bool SetLogfile(const char* pfile); static bool ReopenLogfile(); static s3fs_log_level SetLogLevel(s3fs_log_level level); static s3fs_log_level BumpupLogLevel(); static bool SetTimeStamp(bool value); explicit S3fsLog(); ~S3fsLog(); S3fsLog(const S3fsLog&) = delete; S3fsLog(S3fsLog&&) = delete; S3fsLog& operator=(const S3fsLog&) = delete; S3fsLog& operator=(S3fsLog&&) = delete; }; //------------------------------------------------------------------- // Debug macros //------------------------------------------------------------------- void s3fs_low_logprn(S3fsLog::s3fs_log_level level, const char* file, const char *func, int line, const char *fmt, ...) __attribute__ ((format (printf, 5, 6))); #define S3FS_LOW_LOGPRN(level, fmt, ...) \ do{ \ s3fs_low_logprn(level, __FILE__, __func__, __LINE__, fmt, ##__VA_ARGS__); \ }while(0) void s3fs_low_logprn2(S3fsLog::s3fs_log_level level, int nest, const char* file, const char *func, int line, const char *fmt, ...) __attribute__ ((format (printf, 6, 7))); #define S3FS_LOW_LOGPRN2(level, nest, fmt, ...) \ do{ \ s3fs_low_logprn2(level, nest, __FILE__, __func__, __LINE__, fmt, ##__VA_ARGS__); \ }while(0) #define S3FS_LOW_CURLDBG(fmt, ...) \ do{ \ if(foreground || S3fsLog::IsSetLogFile()){ \ S3fsLog::SeekEnd(); \ fprintf(S3fsLog::GetOutputLogFile(), "%s[CURL DBG] " fmt "%s\n", S3fsLog::GetCurrentTime().c_str(), __VA_ARGS__); \ S3fsLog::Flush(); \ }else{ \ syslog(S3fsLog::GetSyslogLevel(S3fsLog::LEVEL_CRIT), "%s" fmt "%s", instance_name.c_str(), __VA_ARGS__); \ } \ }while(0) #define S3FS_LOW_LOGPRN_EXIT(fmt, ...) \ do{ \ if(foreground || S3fsLog::IsSetLogFile()){ \ S3fsLog::SeekEnd(); \ fprintf(S3fsLog::GetErrorLogFile(), "s3fs: " fmt "%s\n", __VA_ARGS__); \ S3fsLog::Flush(); \ }else{ \ fprintf(S3fsLog::GetErrorLogFile(), "s3fs: " fmt "%s\n", __VA_ARGS__); \ syslog(S3fsLog::GetSyslogLevel(S3fsLog::LEVEL_CRIT), "%ss3fs: " fmt "%s", instance_name.c_str(), __VA_ARGS__); \ } \ }while(0) // Special macro for init message #define S3FS_PRN_INIT_INFO(fmt, ...) \ do{ \ if(foreground || S3fsLog::IsSetLogFile()){ \ S3fsLog::SeekEnd(); \ fprintf(S3fsLog::GetOutputLogFile(), "%s%s%s%s:%s(%d): " fmt "%s\n", S3fsLog::GetCurrentTime().c_str(), S3fsLog::GetLevelString(S3fsLog::LEVEL_INFO), S3fsLog::GetS3fsLogNest(0), __FILE__, __func__, __LINE__, __VA_ARGS__, ""); \ S3fsLog::Flush(); \ }else{ \ syslog(S3fsLog::GetSyslogLevel(S3fsLog::LEVEL_INFO), "%s%s" fmt "%s", instance_name.c_str(), S3fsLog::GetS3fsLogNest(0), __VA_ARGS__, ""); \ } \ }while(0) #define S3FS_PRN_LAUNCH_INFO(fmt, ...) \ do{ \ if(foreground || S3fsLog::IsSetLogFile()){ \ S3fsLog::SeekEnd(); \ fprintf(S3fsLog::GetOutputLogFile(), "%s%s" fmt "%s\n", S3fsLog::GetCurrentTime().c_str(), S3fsLog::GetLevelString(S3fsLog::LEVEL_INFO), __VA_ARGS__, ""); \ S3fsLog::Flush(); \ }else{ \ syslog(S3fsLog::GetSyslogLevel(S3fsLog::LEVEL_INFO), "%s" fmt "%s", instance_name.c_str(), __VA_ARGS__, ""); \ } \ }while(0) // Special macro for checking cache files #define S3FS_LOW_CACHE(fp, fmt, ...) \ do{ \ if(foreground || S3fsLog::IsSetLogFile()){ \ S3fsLog::SeekEnd(); \ fprintf(fp, fmt "%s\n", __VA_ARGS__); \ S3fsLog::Flush(); \ }else{ \ syslog(S3fsLog::GetSyslogLevel(S3fsLog::LEVEL_INFO), "%s: " fmt "%s", instance_name.c_str(), __VA_ARGS__); \ } \ }while(0) // [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(S3fsLog::LEVEL_CRIT, fmt, ##__VA_ARGS__) #define S3FS_PRN_ERR(fmt, ...) S3FS_LOW_LOGPRN(S3fsLog::LEVEL_ERR, fmt, ##__VA_ARGS__) #define S3FS_PRN_WARN(fmt, ...) S3FS_LOW_LOGPRN(S3fsLog::LEVEL_WARN, fmt, ##__VA_ARGS__) #define S3FS_PRN_DBG(fmt, ...) S3FS_LOW_LOGPRN(S3fsLog::LEVEL_DBG, fmt, ##__VA_ARGS__) #define S3FS_PRN_INFO(fmt, ...) S3FS_LOW_LOGPRN2(S3fsLog::LEVEL_INFO, 0, fmt, ##__VA_ARGS__) #define S3FS_PRN_INFO1(fmt, ...) S3FS_LOW_LOGPRN2(S3fsLog::LEVEL_INFO, 1, fmt, ##__VA_ARGS__) #define S3FS_PRN_INFO2(fmt, ...) S3FS_LOW_LOGPRN2(S3fsLog::LEVEL_INFO, 2, fmt, ##__VA_ARGS__) #define S3FS_PRN_INFO3(fmt, ...) S3FS_LOW_LOGPRN2(S3fsLog::LEVEL_INFO, 3, fmt, ##__VA_ARGS__) #define S3FS_PRN_CURL(fmt, ...) S3FS_LOW_CURLDBG(fmt, ##__VA_ARGS__, "") #define S3FS_PRN_CACHE(fp, ...) S3FS_LOW_CACHE(fp, ##__VA_ARGS__, "") // Macros to print log with fuse context #define PRINT_FUSE_CTX(level, indent, fmt, ...) do { \ if(S3fsLog::IsS3fsLogLevel(level)){ \ struct fuse_context *ctx = fuse_get_context(); \ if(ctx == NULL){ \ S3FS_LOW_LOGPRN2(level, indent, fmt, ##__VA_ARGS__); \ }else{ \ S3FS_LOW_LOGPRN2(level, indent, fmt"[pid=%u,uid=%u,gid=%u]",\ ##__VA_ARGS__, \ (unsigned int)(ctx->pid), \ (unsigned int)(ctx->uid), \ (unsigned int)(ctx->gid)); \ } \ } \ } while (0) #define FUSE_CTX_INFO(fmt, ...) do { \ PRINT_FUSE_CTX(S3fsLog::LEVEL_INFO, 0, fmt, ##__VA_ARGS__); \ } while (0) #define FUSE_CTX_INFO1(fmt, ...) do { \ PRINT_FUSE_CTX(S3fsLog::LEVEL_INFO, 1, fmt, ##__VA_ARGS__); \ } while (0) #define FUSE_CTX_DBG(fmt, ...) do { \ PRINT_FUSE_CTX(S3fsLog::LEVEL_DBG, 0, fmt, ##__VA_ARGS__); \ } while (0) #endif // S3FS_LOGGER_H_ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: expandtab sw=4 ts=4 fdm=marker * vim<600: expandtab sw=4 ts=4 */
11,011
C++
.h
237
38.481013
243
0.522626
s3fs-fuse/s3fs-fuse
8,508
1,013
270
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
18,500
crypto-openssl-10.cpp
AGWA_git-crypt/crypto-openssl-10.cpp
/* * Copyright 2012, 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see <http://www.gnu.org/licenses/>. * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include <openssl/opensslconf.h> #if !defined(OPENSSL_API_COMPAT) #include "crypto.hpp" #include "key.hpp" #include "util.hpp" #include <openssl/aes.h> #include <openssl/sha.h> #include <openssl/hmac.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <openssl/err.h> #include <sstream> #include <cstring> void init_crypto () { ERR_load_crypto_strings(); } struct Aes_ecb_encryptor::Aes_impl { AES_KEY key; }; Aes_ecb_encryptor::Aes_ecb_encryptor (const unsigned char* raw_key) : impl(new Aes_impl) { if (AES_set_encrypt_key(raw_key, KEY_LEN * 8, &(impl->key)) != 0) { throw Crypto_error("Aes_ctr_encryptor::Aes_ctr_encryptor", "AES_set_encrypt_key failed"); } } Aes_ecb_encryptor::~Aes_ecb_encryptor () { // Note: Explicit destructor necessary because class contains an unique_ptr // which contains an incomplete type when the unique_ptr is declared. explicit_memset(&impl->key, '\0', sizeof(impl->key)); } void Aes_ecb_encryptor::encrypt(const unsigned char* plain, unsigned char* cipher) { AES_encrypt(plain, cipher, &(impl->key)); } struct Hmac_sha1_state::Hmac_impl { HMAC_CTX ctx; }; Hmac_sha1_state::Hmac_sha1_state (const unsigned char* key, size_t key_len) : impl(new Hmac_impl) { HMAC_Init(&(impl->ctx), key, key_len, EVP_sha1()); } Hmac_sha1_state::~Hmac_sha1_state () { // Note: Explicit destructor necessary because class contains an unique_ptr // which contains an incomplete type when the unique_ptr is declared. HMAC_cleanup(&(impl->ctx)); } void Hmac_sha1_state::add (const unsigned char* buffer, size_t buffer_len) { HMAC_Update(&(impl->ctx), buffer, buffer_len); } void Hmac_sha1_state::get (unsigned char* digest) { unsigned int len; HMAC_Final(&(impl->ctx), digest, &len); } void random_bytes (unsigned char* buffer, size_t len) { if (RAND_bytes(buffer, len) != 1) { std::ostringstream message; while (unsigned long code = ERR_get_error()) { char error_string[120]; ERR_error_string_n(code, error_string, sizeof(error_string)); message << "OpenSSL Error: " << error_string << "; "; } throw Crypto_error("random_bytes", message.str()); } } #endif
3,430
C++
.cpp
102
31.813725
91
0.737764
AGWA/git-crypt
8,224
478
134
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
18,501
coprocess-unix.cpp
AGWA_git-crypt/coprocess-unix.cpp
/* * Copyright 2015 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see <http://www.gnu.org/licenses/>. * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include "coprocess.hpp" #include "util.hpp" #include <sys/types.h> #include <sys/wait.h> #include <errno.h> static int execvp (const std::string& file, const std::vector<std::string>& args) { std::vector<const char*> args_c_str; args_c_str.reserve(args.size()); for (std::vector<std::string>::const_iterator arg(args.begin()); arg != args.end(); ++arg) { args_c_str.push_back(arg->c_str()); } args_c_str.push_back(nullptr); return execvp(file.c_str(), const_cast<char**>(&args_c_str[0])); } Coprocess::Coprocess () { pid = -1; stdin_pipe_reader = -1; stdin_pipe_writer = -1; stdin_pipe_ostream = nullptr; stdout_pipe_reader = -1; stdout_pipe_writer = -1; stdout_pipe_istream = nullptr; } Coprocess::~Coprocess () { close_stdin(); close_stdout(); } std::ostream* Coprocess::stdin_pipe () { if (!stdin_pipe_ostream) { int fds[2]; if (pipe(fds) == -1) { throw System_error("pipe", "", errno); } stdin_pipe_reader = fds[0]; stdin_pipe_writer = fds[1]; stdin_pipe_ostream = new ofhstream(this, write_stdin); } return stdin_pipe_ostream; } void Coprocess::close_stdin () { delete stdin_pipe_ostream; stdin_pipe_ostream = nullptr; if (stdin_pipe_writer != -1) { close(stdin_pipe_writer); stdin_pipe_writer = -1; } if (stdin_pipe_reader != -1) { close(stdin_pipe_reader); stdin_pipe_reader = -1; } } std::istream* Coprocess::stdout_pipe () { if (!stdout_pipe_istream) { int fds[2]; if (pipe(fds) == -1) { throw System_error("pipe", "", errno); } stdout_pipe_reader = fds[0]; stdout_pipe_writer = fds[1]; stdout_pipe_istream = new ifhstream(this, read_stdout); } return stdout_pipe_istream; } void Coprocess::close_stdout () { delete stdout_pipe_istream; stdout_pipe_istream = nullptr; if (stdout_pipe_writer != -1) { close(stdout_pipe_writer); stdout_pipe_writer = -1; } if (stdout_pipe_reader != -1) { close(stdout_pipe_reader); stdout_pipe_reader = -1; } } void Coprocess::spawn (const std::vector<std::string>& args) { pid = fork(); if (pid == -1) { throw System_error("fork", "", errno); } if (pid == 0) { if (stdin_pipe_writer != -1) { close(stdin_pipe_writer); } if (stdout_pipe_reader != -1) { close(stdout_pipe_reader); } if (stdin_pipe_reader != -1) { dup2(stdin_pipe_reader, 0); close(stdin_pipe_reader); } if (stdout_pipe_writer != -1) { dup2(stdout_pipe_writer, 1); close(stdout_pipe_writer); } execvp(args[0], args); perror(args[0].c_str()); _exit(-1); } if (stdin_pipe_reader != -1) { close(stdin_pipe_reader); stdin_pipe_reader = -1; } if (stdout_pipe_writer != -1) { close(stdout_pipe_writer); stdout_pipe_writer = -1; } } int Coprocess::wait () { int status = 0; if (waitpid(pid, &status, 0) == -1) { throw System_error("waitpid", "", errno); } return status; } size_t Coprocess::write_stdin (void* handle, const void* buf, size_t count) { const int fd = static_cast<Coprocess*>(handle)->stdin_pipe_writer; ssize_t ret; while ((ret = write(fd, buf, count)) == -1 && errno == EINTR); // restart if interrupted if (ret < 0) { throw System_error("write", "", errno); } return ret; } size_t Coprocess::read_stdout (void* handle, void* buf, size_t count) { const int fd = static_cast<Coprocess*>(handle)->stdout_pipe_reader; ssize_t ret; while ((ret = read(fd, buf, count)) == -1 && errno == EINTR); // restart if interrupted if (ret < 0) { throw System_error("read", "", errno); } return ret; }
4,775
C++
.cpp
173
25.427746
93
0.686424
AGWA/git-crypt
8,224
478
134
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
18,502
key.cpp
AGWA_git-crypt/key.cpp
/* * Copyright 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see <http://www.gnu.org/licenses/>. * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include "key.hpp" #include "util.hpp" #include "crypto.hpp" #include <sys/types.h> #include <sys/stat.h> #include <stdint.h> #include <fstream> #include <istream> #include <ostream> #include <sstream> #include <cstring> #include <stdexcept> #include <vector> Key_file::Entry::Entry () { version = 0; explicit_memset(aes_key, 0, AES_KEY_LEN); explicit_memset(hmac_key, 0, HMAC_KEY_LEN); } void Key_file::Entry::load (std::istream& in) { while (true) { uint32_t field_id; if (!read_be32(in, field_id)) { throw Malformed(); } if (field_id == KEY_FIELD_END) { break; } uint32_t field_len; if (!read_be32(in, field_len)) { throw Malformed(); } if (field_id == KEY_FIELD_VERSION) { if (field_len != 4) { throw Malformed(); } if (!read_be32(in, version)) { throw Malformed(); } } else if (field_id == KEY_FIELD_AES_KEY) { if (field_len != AES_KEY_LEN) { throw Malformed(); } in.read(reinterpret_cast<char*>(aes_key), AES_KEY_LEN); if (in.gcount() != AES_KEY_LEN) { throw Malformed(); } } else if (field_id == KEY_FIELD_HMAC_KEY) { if (field_len != HMAC_KEY_LEN) { throw Malformed(); } in.read(reinterpret_cast<char*>(hmac_key), HMAC_KEY_LEN); if (in.gcount() != HMAC_KEY_LEN) { throw Malformed(); } } else if (field_id & 1) { // unknown critical field throw Incompatible(); } else { // unknown non-critical field - safe to ignore if (field_len > MAX_FIELD_LEN) { throw Malformed(); } in.ignore(field_len); if (in.gcount() != static_cast<std::streamsize>(field_len)) { throw Malformed(); } } } } void Key_file::Entry::load_legacy (uint32_t arg_version, std::istream& in) { version = arg_version; // First comes the AES key in.read(reinterpret_cast<char*>(aes_key), AES_KEY_LEN); if (in.gcount() != AES_KEY_LEN) { throw Malformed(); } // Then the HMAC key in.read(reinterpret_cast<char*>(hmac_key), HMAC_KEY_LEN); if (in.gcount() != HMAC_KEY_LEN) { throw Malformed(); } if (in.peek() != -1) { // Trailing data is a good indication that we are not actually reading a // legacy key file. (This is important to check since legacy key files // did not have any sort of file header.) throw Malformed(); } } void Key_file::Entry::store (std::ostream& out) const { // Version write_be32(out, KEY_FIELD_VERSION); write_be32(out, 4); write_be32(out, version); // AES key write_be32(out, KEY_FIELD_AES_KEY); write_be32(out, AES_KEY_LEN); out.write(reinterpret_cast<const char*>(aes_key), AES_KEY_LEN); // HMAC key write_be32(out, KEY_FIELD_HMAC_KEY); write_be32(out, HMAC_KEY_LEN); out.write(reinterpret_cast<const char*>(hmac_key), HMAC_KEY_LEN); // End write_be32(out, KEY_FIELD_END); } void Key_file::Entry::generate (uint32_t arg_version) { version = arg_version; random_bytes(aes_key, AES_KEY_LEN); random_bytes(hmac_key, HMAC_KEY_LEN); } const Key_file::Entry* Key_file::get_latest () const { return is_filled() ? get(latest()) : 0; } const Key_file::Entry* Key_file::get (uint32_t version) const { Map::const_iterator it(entries.find(version)); return it != entries.end() ? &it->second : 0; } void Key_file::add (const Entry& entry) { entries[entry.version] = entry; } void Key_file::load_legacy (std::istream& in) { entries[0].load_legacy(0, in); } void Key_file::load (std::istream& in) { unsigned char preamble[16]; in.read(reinterpret_cast<char*>(preamble), 16); if (in.gcount() != 16) { throw Malformed(); } if (std::memcmp(preamble, "\0GITCRYPTKEY", 12) != 0) { throw Malformed(); } if (load_be32(preamble + 12) != FORMAT_VERSION) { throw Incompatible(); } load_header(in); while (in.peek() != -1) { Entry entry; entry.load(in); add(entry); } } void Key_file::load_header (std::istream& in) { while (true) { uint32_t field_id; if (!read_be32(in, field_id)) { throw Malformed(); } if (field_id == HEADER_FIELD_END) { break; } uint32_t field_len; if (!read_be32(in, field_len)) { throw Malformed(); } if (field_id == HEADER_FIELD_KEY_NAME) { if (field_len > KEY_NAME_MAX_LEN) { throw Malformed(); } if (field_len == 0) { // special case field_len==0 to avoid possible undefined behavior // edge cases with an empty std::vector (particularly, &bytes[0]). key_name.clear(); } else { std::vector<char> bytes(field_len); in.read(&bytes[0], field_len); if (in.gcount() != static_cast<std::streamsize>(field_len)) { throw Malformed(); } key_name.assign(&bytes[0], field_len); } if (!validate_key_name(key_name.c_str())) { key_name.clear(); throw Malformed(); } } else if (field_id & 1) { // unknown critical field throw Incompatible(); } else { // unknown non-critical field - safe to ignore if (field_len > MAX_FIELD_LEN) { throw Malformed(); } in.ignore(field_len); if (in.gcount() != static_cast<std::streamsize>(field_len)) { throw Malformed(); } } } } void Key_file::store (std::ostream& out) const { out.write("\0GITCRYPTKEY", 12); write_be32(out, FORMAT_VERSION); if (!key_name.empty()) { write_be32(out, HEADER_FIELD_KEY_NAME); write_be32(out, key_name.size()); out.write(key_name.data(), key_name.size()); } write_be32(out, HEADER_FIELD_END); for (Map::const_iterator it(entries.begin()); it != entries.end(); ++it) { it->second.store(out); } } bool Key_file::load_from_file (const char* key_file_name) { std::ifstream key_file_in(key_file_name, std::fstream::binary); if (!key_file_in) { return false; } load(key_file_in); return true; } bool Key_file::store_to_file (const char* key_file_name) const { create_protected_file(key_file_name); std::ofstream key_file_out(key_file_name, std::fstream::binary); if (!key_file_out) { return false; } store(key_file_out); key_file_out.close(); if (!key_file_out) { return false; } return true; } std::string Key_file::store_to_string () const { std::ostringstream ss; store(ss); return ss.str(); } void Key_file::generate () { uint32_t version(is_empty() ? 0 : latest() + 1); entries[version].generate(version); } uint32_t Key_file::latest () const { if (is_empty()) { throw std::invalid_argument("Key_file::latest"); } return entries.begin()->first; } bool validate_key_name (const char* key_name, std::string* reason) { if (!*key_name) { if (reason) { *reason = "Key name may not be empty"; } return false; } if (std::strcmp(key_name, "default") == 0) { if (reason) { *reason = "`default' is not a legal key name"; } return false; } // Need to be restrictive with key names because they're used as part of a Git filter name size_t len = 0; while (char c = *key_name++) { if (!std::isalnum(c) && c != '-' && c != '_') { if (reason) { *reason = "Key names may contain only A-Z, a-z, 0-9, '-', and '_'"; } return false; } if (++len > KEY_NAME_MAX_LEN) { if (reason) { *reason = "Key name is too long"; } return false; } } return true; }
8,331
C++
.cpp
306
24.660131
91
0.669919
AGWA/git-crypt
8,224
478
134
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
18,503
util.cpp
AGWA_git-crypt/util.cpp
/* * Copyright 2012, 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see <http://www.gnu.org/licenses/>. * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include "git-crypt.hpp" #include "util.hpp" #include "coprocess.hpp" #include <string> #include <iostream> int exec_command (const std::vector<std::string>& args) { Coprocess proc; proc.spawn(args); return proc.wait(); } int exec_command (const std::vector<std::string>& args, std::ostream& output) { Coprocess proc; std::istream* proc_stdout = proc.stdout_pipe(); proc.spawn(args); output << proc_stdout->rdbuf(); return proc.wait(); } int exec_command_with_input (const std::vector<std::string>& args, const char* p, size_t len) { Coprocess proc; std::ostream* proc_stdin = proc.stdin_pipe(); proc.spawn(args); proc_stdin->write(p, len); proc.close_stdin(); return proc.wait(); } std::string escape_shell_arg (const std::string& str) { std::string new_str; new_str.push_back('"'); for (std::string::const_iterator it(str.begin()); it != str.end(); ++it) { if (*it == '"' || *it == '\\' || *it == '$' || *it == '`') { new_str.push_back('\\'); } new_str.push_back(*it); } new_str.push_back('"'); return new_str; } uint32_t load_be32 (const unsigned char* p) { return (static_cast<uint32_t>(p[3]) << 0) | (static_cast<uint32_t>(p[2]) << 8) | (static_cast<uint32_t>(p[1]) << 16) | (static_cast<uint32_t>(p[0]) << 24); } void store_be32 (unsigned char* p, uint32_t i) { p[3] = i; i >>= 8; p[2] = i; i >>= 8; p[1] = i; i >>= 8; p[0] = i; } bool read_be32 (std::istream& in, uint32_t& i) { unsigned char buffer[4]; in.read(reinterpret_cast<char*>(buffer), 4); if (in.gcount() != 4) { return false; } i = load_be32(buffer); return true; } void write_be32 (std::ostream& out, uint32_t i) { unsigned char buffer[4]; store_be32(buffer, i); out.write(reinterpret_cast<const char*>(buffer), 4); } void* explicit_memset (void* s, int c, std::size_t n) { volatile unsigned char* p = reinterpret_cast<unsigned char*>(s); while (n--) { *p++ = c; } return s; } static bool leakless_equals_char (const unsigned char* a, const unsigned char* b, std::size_t len) { volatile int diff = 0; while (len > 0) { diff |= *a++ ^ *b++; --len; } return diff == 0; } bool leakless_equals (const void* a, const void* b, std::size_t len) { return leakless_equals_char(reinterpret_cast<const unsigned char*>(a), reinterpret_cast<const unsigned char*>(b), len); } static void init_std_streams_platform (); // platform-specific initialization void init_std_streams () { // The following two lines are essential for achieving good performance: std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cin.exceptions(std::ios_base::badbit); std::cout.exceptions(std::ios_base::badbit); init_std_streams_platform(); } #ifdef _WIN32 #include "util-win32.cpp" #else #include "util-unix.cpp" #endif
4,077
C++
.cpp
136
27.955882
120
0.695153
AGWA/git-crypt
8,224
478
134
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false