1 /**
2  * @file src/megacmdcommonutils.h
3  * @brief MEGAcmd: Auxiliary methods
4  *
5  * (c) 2013 by Mega Limited, Auckland, New Zealand
6  *
7  * This file is part of the MEGAcmd.
8  *
9  * MEGAcmd is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12  *
13  * @copyright Simplified (2-clause) BSD License.
14  *
15  * You should have received a copy of the license along with this
16  * program.
17  */
18 
19 #ifndef MEGACMDCOMMONUTILS_H
20 #define MEGACMDCOMMONUTILS_H
21 
22 #include <string>
23 #include <vector>
24 #include <iomanip>
25 #include <map>
26 #include <set>
27 #include <stdint.h>
28 #include <sstream>
29 #include <iostream>
30 #include <iomanip>
31 #include <mutex>
32 
33 
34 using std::setw;
35 using std::left;
36 
37 #ifdef _WIN32
38 namespace mega{
39 
40 // Note: these was in megacmd namespace, but after one overload of operator<< was created within mega,
41 // ADL did not seem to be able to find it when solving template resolution in loggin.h (namespace mega),
42 // even for code coming from megacmd namespace.
43 // placing this operator in mega namespace eases ADL lookup and allows compilation
44 std::ostringstream & operator<< ( std::ostringstream & ostr, std::wstring const &str); //override for the log, otherwise SimpleLog won't compile.
45 }
46 #endif
47 
48 namespace megacmd {
49 
50 /* platform dependent */
51 #ifdef _WIN32
52 
53 #define OUTSTREAMTYPE std::wostream
54 #define OUTSTRINGSTREAM std::wostringstream
55 #define OUTSTRING std::wstring
56 #define COUT std::wcout
57 #define CERR std::wcerr
58 
59 //override << operators for wostream for string and const char *
60 std::wostream & operator<< ( std::wostream & ostr, std::string const & str );
61 std::wostream & operator<< ( std::wostream & ostr, const char * str );
62 
63 void stringtolocalw(const char* path, std::wstring* local);
64 void localwtostring(const std::wstring* wide, std::string *multibyte);
65 std::string getutf8fromUtf16(const wchar_t *ws);
66 void utf16ToUtf8(const wchar_t* utf16data, int utf16size, std::string* utf8string);
67 
68 #else
69 #define OUTSTREAMTYPE std::ostream
70 #define OUTSTRINGSTREAM std::ostringstream
71 #define OUTSTRING std::string
72 #define COUT std::cout
73 #define CERR std::cerr
74 
75 #endif
76 
77 #define OUTSTREAM COUT
78 
79 
80 /* commands */
81 static std::vector<std::string> validGlobalParameters {"v", "help"};
82 static std::vector<std::string> localremotefolderpatterncommands {"sync"};
83 static std::vector<std::string> remotepatterncommands {"export", "attr"};
84 static std::vector<std::string> remotefolderspatterncommands {"cd", "share"};
85 
86 static std::vector<std::string> multipleremotepatterncommands {"ls", "tree", "mkdir", "rm", "du", "find", "mv", "deleteversions", "cat", "mediainfo"
87 #ifdef HAVE_LIBUV
88                                            , "webdav", "ftp"
89 #endif
90                                           };
91 
92 static std::vector<std::string> remoteremotepatterncommands {"cp"};
93 
94 static std::vector<std::string> remotelocalpatterncommands {"get", "thumbnail", "preview"};
95 
96 static std::vector<std::string> localfolderpatterncommands {"lcd"};
97 
98 static std::vector<std::string> emailpatterncommands {"invite", "signup", "ipc", "users"};
99 
100 static std::vector<std::string> loginInValidCommands { "log", "debug", "speedlimit", "help", "logout", "version", "quit",
101                             "clear", "https", "exit", "errorcode", "proxy"
102 #if defined(_WIN32) && defined(NO_READLINE)
103                              , "autocomplete", "codepage"
104 #elif defined(_WIN32)
105                              , "unicode"
106 #endif
107 #if defined(_WIN32) || defined(__APPLE__)
108                              , "update"
109 #endif
110                            };
111 
112 static std::vector<std::string> allValidCommands { "login", "signup", "confirm", "session", "mount", "ls", "cd", "log", "debug", "pwd", "lcd", "lpwd", "import", "masterkey",
113                              "put", "get", "attr", "userattr", "mkdir", "rm", "du", "mv", "cp", "sync", "export", "share", "invite", "ipc", "df",
114                              "showpcr", "users", "speedlimit", "killsession", "whoami", "help", "passwd", "reload", "logout", "version", "quit",
115                              "thumbnail", "preview", "find", "completion", "clear", "https", "transfers", "exclude", "exit", "errorcode", "graphics",
116                              "cancel", "confirmcancel", "cat", "tree", "psa", "proxy"
117                              , "mediainfo"
118 #ifdef HAVE_LIBUV
119                              , "webdav", "ftp"
120 #endif
121 #ifdef ENABLE_BACKUPS
122                              , "backup"
123 #endif
124                              , "deleteversions"
125 #if defined(_WIN32) && defined(NO_READLINE)
126                              , "autocomplete", "codepage"
127 #elif defined(_WIN32)
128                              , "unicode"
129 #else
130                              , "permissions"
131 #endif
132 #if defined(_WIN32) || defined(__APPLE__)
133                              , "update"
134 #endif
135                            };
136 
137 
138 static const int RESUME_SESSION_TIMEOUT = 10;
139 
140 /* Files and folders */
141 
142 //tests if a path is writable  //TODO: move to fsAccess
143 bool canWrite(std::string path);
144 
145 bool isPublicLink(std::string link);
146 
147 bool isEncryptedLink(std::string link);
148 
149 std::string getPublicLinkHandle(const std::string &link);
150 
151 bool hasWildCards(std::string &what);
152 
153 std::string removeTrailingSeparators(std::string &path);
154 
155 
156 /* Strings related */
157 
158 long long charstoll(const char *instr);
159 
160 // trim from start
161 std::string &ltrim(std::string &s, const char &c);
162 
163 // trim at the end
164 std::string &rtrim(std::string &s, const char &c);
165 
166 std::vector<std::string> getlistOfWords(char *ptr, bool escapeBackSlashInCompletion = false, bool ignoreTrailingSpaces = false);
167 
168 bool stringcontained(const char * s, std::vector<std::string> list);
169 
170 char * dupstr(char* s);
171 
172 bool replace(std::string& str, const std::string& from, const std::string& to);
173 
174 void replaceAll(std::string& str, const std::string& from, const std::string& to);
175 
176 int toInteger(std::string what, int failValue = -1);
177 
178 std::string joinStrings(const std::vector<std::string>& vec, const char* delim = " ", bool quoted=true);
179 
180 std::string getFixLengthString(const std::string &origin, unsigned int size, const char delimm=' ', bool alignedright = false);
181 
182 std::string getRightAlignedString(const std::string origin, unsigned int minsize);
183 
184 template<typename T>
getLeftAlignedStr(T what,int n)185 OUTSTRING getLeftAlignedStr(T what, int n)
186 {
187     OUTSTRINGSTREAM os;
188     os << setw(n) << left << what;
189     return os.str();
190 }
191 
192 
193 template<typename T>
getRightAlignedStr(T what,int n)194 OUTSTRING getRightAlignedStr(T what, int n)
195 {
196     OUTSTRINGSTREAM os;
197     os << setw(n) << what;
198     return os.str();
199 }
200 
201 void printCenteredLine(std::string msj, unsigned int width, bool encapsulated = true);
202 void printCenteredContents(std::string msj, unsigned int width, bool encapsulated = true);
203 void printCenteredContentsCerr(std::string msj, unsigned int width, bool encapsulated = true);
204 void printCenteredLine(OUTSTREAMTYPE &os, std::string msj, unsigned int width, bool encapsulated = true);
205 void printCenteredContents(OUTSTREAMTYPE &os, std::string msj, unsigned int width, bool encapsulated = true);
206 
207 void printPercentageLineCerr(const char *title, long long completed, long long total, float percentDowloaded, bool cleanLineAfter = true);
208 
209 /* Flags and Options */
210 int getFlag(std::map<std::string, int> *flags, const char * optname);
211 
212 std::string getOption(std::map<std::string, std::string> *cloptions, const char * optname, std::string defaultValue = "");
213 
214 int getintOption(std::map<std::string, std::string> *cloptions, const char * optname, int defaultValue = 0);
215 
216 void discardOptionsAndFlags(std::vector<std::string> *ws);
217 
218 //This has been defined in megacmdutils.h because it depends on logging. If ever require offer a version without it here
219 //bool setOptionsAndFlags(map<string, string> *opts, map<string, int> *flags, vector<string> *ws, set<string> vvalidOptions, bool global)
220 
221 
222 /* Others */
223 std::string sizeToText(long long totalSize, bool equalizeUnitsLength = true, bool humanreadable = true);
224 std::string sizeProgressToText(long long partialSize, long long totalSize, bool equalizeUnitsLength = true, bool humanreadable = true);
225 
226 int64_t textToSize(const char *text);
227 
228 std::string percentageToText(float percentage);
229 
230 unsigned int getNumberOfCols(unsigned int defaultwidth = 90);
231 
232 void sleepSeconds(int seconds);
233 void sleepMilliSeconds(long microseconds);
234 
235 bool isValidEmail(std::string email);
236 
237 #ifdef __linux__
238 std::string getCurrentExecPath();
239 #endif
240 
241 /* Properties */
242 std::string &ltrimProperty(std::string &s, const char &c);
243 std::string &rtrimProperty(std::string &s, const char &c);
244 std::string &trimProperty(std::string &what);
245 std::string getPropertyFromFile(const char *configFile, const char *propertyName);
246 template <typename T>
getValueFromFile(const char * configFile,const char * propertyName,T defaultValue)247 T getValueFromFile(const char *configFile, const char *propertyName, T defaultValue)
248 {
249     std::string propValue = getPropertyFromFile(configFile, propertyName);
250     if (!propValue.size()) return defaultValue;
251 
252     T i;
253     std::istringstream is(propValue);
254     is >> i;
255     return i;
256 }
257 
258 class Field
259 {
260 public:
261     Field();
262     Field(std::string name, bool fixed = false, int fixedWidth = 0);
263 
264 public:
265     std::string name;
266     int fixedWidth;
267     bool fixedSize;
268     int dispWidth = 0;
269     int maxValueLength = 0;
270 
271     void updateMaxValue(int newcandidate);
272 };
273 
274 class ColumnDisplayer
275 {
276 public:
277     ColumnDisplayer(int unfixedColsMinSize = 0);
278 
279     void print(OUTSTREAMTYPE &os, int fullWidth, bool printHeader=true);
280     void addHeader(const std::string &name, bool fixed = true, int minWidth = 0);
281     void addValue(const std::string &name, const std::string & value, bool replace = false);
282     void endregistry();
283 
284 private:
285     std::map<std::string, Field> fields;
286     std::vector<std::string> fieldnames;
287     std::vector<std::map<std::string, std::string>> values;
288     std::vector<int> lengths;
289 
290     std::map<std::string, std::string> currentRegistry;
291     int currentlength = 0;
292 
293     int mUnfixedColsMinSize = 0;
294 
295 };
296 
297 }//end namespace
298 #endif // MEGACMDCOMMONUTILS_H
299