1 /**
2  * @file mega/megaclient.h
3  * @brief Client access engine core logic
4  *
5  * (c) 2013-2014 by Mega Limited, Auckland, New Zealand
6  *
7  * This file is part of the MEGA SDK - Client Access Engine.
8  *
9  * Applications using the MEGA API must present a valid application key
10  * and comply with the the rules set forth in the Terms of Service.
11  *
12  * The MEGA SDK is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15  *
16  * @copyright Simplified (2-clause) BSD License.
17  *
18  * You should have received a copy of the license along with this
19  * program.
20  */
21 
22 #ifndef MEGACLIENT_H
23 #define MEGACLIENT_H 1
24 
25 #include "json.h"
26 #include "db.h"
27 #include "gfx.h"
28 #include "filefingerprint.h"
29 #include "request.h"
30 #include "transfer.h"
31 #include "treeproc.h"
32 #include "sharenodekeys.h"
33 #include "account.h"
34 #include "backofftimer.h"
35 #include "http.h"
36 #include "pubkeyaction.h"
37 #include "pendingcontactrequest.h"
38 #include "mediafileattribute.h"
39 #include "useralerts.h"
40 #include "user.h"
41 
42 namespace mega {
43 
44 class SyncConfigBag;
45 
46 class MEGA_API FetchNodesStats
47 {
48 public:
49     enum {
50         MODE_DB = 0,
51         MODE_API = 1,
52         MODE_NONE = 2
53     };
54 
55     enum {
56         TYPE_ACCOUNT = 0,
57         TYPE_FOLDER = 1,
58         TYPE_NONE = 2
59     };
60 
61     enum {
62         API_CACHE = 0,
63         API_NO_CACHE = 1,    // use this for DB mode
64         API_NONE = 2
65     };
66 
67     FetchNodesStats();
68     void init();
69     void toJsonArray(string *json);
70 
71     //////////////////
72     // General info //
73     //////////////////
74     int mode; // DB = 0, API = 1
75     int cache; // no-cache = 0, no-cache = 1
76     int type; // Account = 0, Folder = 1
77     dstime startTime; // startup time (ds)
78 
79     /**
80      * \brief Number of nodes in the cached filesystem
81      *
82      * From DB: number on nodes in the local database
83      * From API: number of nodes in the response to the fetchnodes command
84      */
85     long long nodesCached;
86 
87     /**
88      * @brief Number of nodes in the current filesystem, after the reception of action packets
89      */
90     long long nodesCurrent;
91 
92     /**
93      * @brief Number of action packets to complete the cached filesystem
94      *
95      * From DB: Number of action packets to complete the local cache
96      * From API: Number of action packets to complete the server-side cache
97      */
98     int actionPackets;
99 
100     ////////////
101     // Errors //
102     ////////////
103 
104     /**
105      * @brief Number of error -3 or -4 received during the process (including cs and sc requests)
106      */
107     int eAgainCount;
108 
109     /**
110      * @brief Number of HTTP 500 errors received during the process (including cs and sc requests)
111      */
112     int e500Count;
113 
114     /**
115      * @brief Number of other errors received during the process (including cs and sc requests)
116      *
117      * The most common source of these errors are connectivity problems (no Internet, timeouts...)
118      */
119     int eOthersCount;
120 
121     ////////////////////////////////////////////////////////////////////
122     // Time elapsed until different steps since the startup time (ds) //
123     ////////////////////////////////////////////////////////////////////
124 
125     /**
126      * @brief Time until the first byte read
127      *
128      * From DB: time until the first record read from the database
129      * From API: time until the first byte read in response to the fetchnodes command (errors excluded)
130      */
131     dstime timeToFirstByte;
132 
133     /**
134      * @brief Time until the last byte read
135      *
136      * From DB: time until the last record is read from the database
137      * From API: time until the whole response to the fetchnodes command has been received
138      */
139     dstime timeToLastByte;
140 
141     /**
142      * @brief Time until the cached filesystem is ready
143      *
144      * From DB: time until the database has been read and processed
145      * From API: time until the fetchnodes command is processed
146      */
147     dstime timeToCached;
148 
149     /**
150      * @brief Time until the filesystem is ready to be used
151      *
152      * From DB: this time is the same as timeToCached
153      * From API: time until action packets have been processed
154      * It's needed to wait until the reception of action packets due to
155      * server-side caches.
156      */
157     dstime timeToResult;
158 
159     /**
160      * @brief Time until synchronizations have been resumed
161      *
162      * This involves the load of the local cache and the scan of known
163      * files. Files that weren't cached are scanned later.
164      */
165     dstime timeToSyncsResumed;
166 
167     /**
168      * @brief Time until the filesystem is current
169      *
170      * From DB: time until action packets have been processed
171      * From API: this time is the same as timeToResult
172      */
173     dstime timeToCurrent;
174 
175     /**
176      * @brief Time until the resumption of transfers has finished
177      *
178      * The resumption of transfers is done after the filesystem is current
179      */
180     dstime timeToTransfersResumed;
181 };
182 
183 /**
184  * @brief A helper class that keeps the SN (sequence number) members in sync and well initialized.
185  *  The server-client sequence number is updated along with every batch of actionpackets received from API
186  *  It is used to commit the open transaction in DB, so the account's local state is persisted. Upon resumption,
187  *  the scsn is sent to API, which provides the possible updates missing while the client was not running
188  */
189 class SCSN
190 {
191     // scsn that we are sending in sc requests (ie, where we are up to with the persisted node data)
192     char scsn[12];
193 
194     // sc inconsistency: stop querying for action packets
195     bool stopsc = false;
196 
197 public:
198 
199     bool setScsn(JSON*);
200     void setScsn(handle);
201     void stopScsn();
202 
203     bool ready() const;
204     bool stopped() const;
205 
206     const char* text() const;
207     handle getHandle() const;
208 
209     friend std::ostream& operator<<(std::ostream& os, const SCSN& scsn);
210 
211     SCSN();
212     void clear();
213 };
214 
215 class MEGA_API MegaClient
216 {
217 public:
218     // own identity
219     handle me;
220     string uid;
221 
222     // root nodes (files, incoming, rubbish)
223     handle rootnodes[3];
224 
225     // all nodes
226     node_map nodes;
227 
228     // keep track of user storage, inshare storage, file/folder counts per root node.
229     NodeCounterMap mNodeCounters;
230 
231     // all users
232     user_map users;
233 
234     // encrypted master key
235     string k;
236 
237     // version of the account
238     int accountversion;
239 
240     // salt of the account (for v2 accounts)
241     string accountsalt;
242 
243     // timestamp of the creation of the account
244     m_time_t accountsince;
245 
246     // Global Multi-Factor Authentication enabled
247     bool gmfa_enabled;
248 
249     // Server-Side Rubbish-bin Scheduler enabled (autopurging)
250     bool ssrs_enabled;
251 
252     // New Secure Registration method enabled
253     bool nsr_enabled;
254 
255     // Account has VOIP push enabled (only for Apple)
256     bool aplvp_enabled;
257 
258     // Use new format to generate Mega links
259     bool mNewLinkFormat = false;
260 
261     // 2 = Opt-in and unblock SMS allowed 1 = Only unblock SMS allowed 0 = No SMS allowed  -1 = flag was not received
262     SmsVerificationState mSmsVerificationState;
263 
264     // the verified account phone number, filled in from 'ug'
265     string mSmsVerifiedPhone;
266 
267     // pseudo-random number generator
268     PrnGen rng;
269 
270     bool ephemeralSession = false;
271 
272     static string getPublicLink(bool newLinkFormat, nodetype_t type, handle ph, const char *key);
273 
274 #ifdef ENABLE_CHAT
275     // all chats
276     textchat_map chats;
277 #endif
278 
279     // process API requests and HTTP I/O
280     void exec();
281 
282     // wait for I/O or other events
283     int wait();
284 
285     // splitted implementation of wait() for a better thread management
286     int preparewait();
287     int dowait();
288     int checkevents();
289 
290     // abort exponential backoff
291     bool abortbackoff(bool = true);
292 
293     // ID tag of the next request
294     int nextreqtag();
295 
296     // corresponding ID tag of the currently executing callback
297     int restag;
298 
299     // ephemeral session support
300     void createephemeral();
301     void resumeephemeral(handle, const byte*, int = 0);
302     void cancelsignup();
303 
304     // full account confirmation/creation support
305     void sendsignuplink(const char*, const char*, const byte*);
306 
307     string sendsignuplink2(const char*, const char *, const char*);
308     void resendsignuplink2(const char*, const char *);
309 
310     void querysignuplink(const byte*, unsigned);
311     void confirmsignuplink(const byte*, unsigned, uint64_t);
312     void confirmsignuplink2(const byte*, unsigned);
313     void setkeypair();
314 
315     // prelogin: e-mail
316     void prelogin(const char*);
317 
318     // user login: e-mail, pwkey
319     void login(const char*, const byte*, const char* = NULL);
320 
321     // user login: e-mail, password, salt
322     void login2(const char*, const char*, string *, const char* = NULL);
323 
324     // user login: e-mail, derivedkey, 2FA pin
325     void login2(const char*, const byte*, const char* = NULL);
326 
327     // user login: e-mail, pwkey, emailhash
328     void fastlogin(const char*, const byte*, uint64_t);
329 
330     // session login: binary session, bytecount
331     void login(const byte*, int);
332 
333     // check password
334     error validatepwd(const byte *);
335 
336     // get user data
337     void getuserdata();
338 
339     // get miscelaneous flags
340     void getmiscflags();
341 
342     // get the public key of an user
343     void getpubkey(const char* user);
344 
345     // check if logged in
346     sessiontype_t loggedin();
347 
348     // check if logged in a folder link
349     bool loggedinfolderlink();
350 
351     // check the reason of being blocked
352     void whyamiblocked();
353 
354     // sets block state: stops querying for action packets, pauses transfer & removes transfer slot availability
355     void block(bool fromServerClientResponse = false);
356 
357     // unsets block state
358     void unblock();
359 
360     // dump current session
361     int dumpsession(byte*, size_t);
362 
363     // create a copy of the current session
364     void copysession();
365 
366     // resend the verification email to the same email address as it was previously sent to
367     void resendverificationemail();
368 
369     // reset the verified phone number
370     void resetSmsVerifiedPhoneNumber();
371 
372     // get the data for a session transfer
373     // the caller takes the ownership of the returned value
374     // if the second parameter isn't NULL, it's used as session id instead of the current one
375     string *sessiontransferdata(const char*, string* = NULL);
376 
377     // Kill session id
378     void killsession(handle session);
379     void killallsessions();
380 
381     // extract public handle and key from a public file/folder link
382     error parsepubliclink(const char *link, handle &ph, byte *key, bool isFolderLink);
383 
384     // set folder link: node, key
385     error folderaccess(const char*folderlink);
386 
387     // open exported file link (op=0 -> download, op=1 fetch data)
388     void openfilelink(handle ph, const byte *key, int op);
389 
390     // decrypt password-protected public link
391     // the caller takes the ownership of the returned value in decryptedLink parameter
392     error decryptlink(const char* link, const char* pwd, string *decryptedLink);
393 
394     // encrypt public link with password
395     // the caller takes the ownership of the returned value
396     error encryptlink(const char* link, const char* pwd, string *encryptedLink);
397 
398     // change login password
399     error changepw(const char *password, const char *pin = NULL);
400 
401     // load all trees: nodes, shares, contacts
402     void fetchnodes(bool nocache = false);
403 
404     // fetchnodes stats
405     FetchNodesStats fnstats;
406 
407     // load cryptographic keys: RSA, Ed25519, Cu25519 and their signatures
408     void fetchkeys();
409 
410     // check existence and integrity of keys and signatures, initialize if missing
411     void initializekeys();
412 
413     // to be called after resumption from cache (user attributes loaded)
414     void loadAuthrings();
415 
416     // load cryptographic keys for contacts: RSA, Ed25519, Cu25519
417     void fetchContactsKeys();
418 
419     // fetch keys related to authrings for a given contact
420     void fetchContactKeys(User *user);
421 
422     // track a public key in the authring for a given user
423     error trackKey(attr_t keyType, handle uh, const std::string &key);
424 
425     // track the signature of a public key in the authring for a given user
426     error trackSignature(attr_t signatureType, handle uh, const std::string &signature);
427 
428     // set the Ed25519 public key as verified for a given user in the authring (done by user manually by comparing hash of keys)
429     error verifyCredentials(handle uh);
430 
431     // reset the tracking of public keys in the authrings for a given user
432     error resetCredentials(handle uh);
433 
434     // check credentials are verified for a given user
435     bool areCredentialsVerified(handle uh);
436 
437     // retrieve user details
438     void getaccountdetails(AccountDetails*, bool, bool, bool, bool, bool, bool, int source = -1);
439 
440     // check if the available bandwidth quota is enough to transfer an amount of bytes
441     void querytransferquota(m_off_t size);
442 
443     // update node attributes
444     error setattr(Node*, const char* prevattr = NULL);
445 
446     // prefix and encrypt attribute json
447     void makeattr(SymmCipher*, string*, const char*, int = -1) const;
448 
449     // convenience version of the above (frequently we are passing a NodeBase's attrstring)
450     void makeattr(SymmCipher*, const std::unique_ptr<string>&, const char*, int = -1) const;
451 
452     // check node access level
453     int checkaccess(Node*, accesslevel_t);
454 
455     // check if a move operation would succeed
456     error checkmove(Node*, Node*);
457 
458     // delete node
459     error unlink(Node*, bool = false);
460 
461     // delete all versions
462     void unlinkversions();
463 
464     // move node to new parent folder
465     error rename(Node*, Node*, syncdel_t = SYNCDEL_NONE, handle = UNDEF, const char *newName = nullptr);
466 
467     // start/stop/pause file transfer
468     bool startxfer(direction_t, File*, DBTableTransactionCommitter&, bool skipdupes = false, bool startfirst = false, bool donotpersist = false);
469     void stopxfer(File* f, DBTableTransactionCommitter* committer);
470     void pausexfers(direction_t, bool pause, bool hard, DBTableTransactionCommitter& committer);
471 
472     // maximum number of connections per transfer
473     static const unsigned MAX_NUM_CONNECTIONS = 6;
474 
475     // set max connections per transfer
476     void setmaxconnections(direction_t, int);
477 
478     // enqueue/abort direct read
479     void pread(Node*, m_off_t, m_off_t, void*);
480     void pread(handle, SymmCipher* key, int64_t, m_off_t, m_off_t, void*, bool = false,  const char* = NULL, const char* = NULL, const char* = NULL);
481     void preadabort(Node*, m_off_t = -1, m_off_t = -1);
482     void preadabort(handle, m_off_t = -1, m_off_t = -1);
483 
484     // pause flags
485     bool xferpaused[2];
486 
487 #ifdef ENABLE_SYNC
488     // active syncs
489     sync_list syncs;
490 
491     // indicates whether all startup syncs have been fully scanned
492     bool syncsup;
493 
494     // A collection of sync configs backed by a database table
495     std::unique_ptr<SyncConfigBag> syncConfigs;
496 
497     // whether we allow the automatic resumption of syncs
498     bool allowAutoResumeSyncs = true;
499 #endif
500 
501     // if set, symlinks will be followed except in recursive deletions
502     // (give the user ample warning about possible sync repercussions)
503     bool followsymlinks;
504 
505     // number of parallel connections per transfer (PUT/GET)
506     unsigned char connections[2];
507 
508     // generate & return next upload handle
509     handle uploadhandle(int);
510 
511     // helper function for preparing a putnodes call for new folders
512     void putnodes_prepareOneFolder(NewNode* newnode, std::string foldername);
513 
514     // add nodes to specified parent node (complete upload, copy files, make
515     // folders)
516     void putnodes(handle, NewNode*, int, const char * = NULL);
517 
518     // send files/folders to user
519     void putnodes(const char*, NewNode*, int);
520 
521     // attach file attribute to upload or node handle
522     void putfa(handle, fatype, SymmCipher*, std::unique_ptr<string>, bool checkAccess = true);
523 
524     // queue file attribute retrieval
525     error getfa(handle h, string *fileattrstring, const string &nodekey, fatype, int = 0);
526 
527     // notify delayed upload completion subsystem about new file attribute
528     void checkfacompletion(handle, Transfer* = NULL);
529 
530     // attach/update/delete a user attribute
531     void putua(attr_t at, const byte* av = NULL, unsigned avl = 0, int ctag = -1, handle lastPublicHandle = UNDEF, int phtype = 0, int64_t ts = 0);
532 
533     // attach/update multiple versioned user attributes at once
534     void putua(userattr_map *attrs, int ctag = -1);
535 
536     // queue a user attribute retrieval
537     void getua(User* u, const attr_t at = ATTR_UNKNOWN, int ctag = -1);
538 
539     // queue a user attribute retrieval (for non-contacts)
540     void getua(const char* email_handle, const attr_t at = ATTR_UNKNOWN, const char *ph = NULL, int ctag = -1);
541 
542     // retrieve the email address of a user
543     void getUserEmail(const char *uid);
544 
545 #ifdef DEBUG
546     // queue a user attribute removal
547     void delua(const char* an);
548 
549     // send dev command for testing
550     void senddevcommand(const char *command, const char *email);
551 #endif
552 
553     // delete or block an existing contact
554     error removecontact(const char*, visibility_t = HIDDEN);
555 
556     // add/remove/update outgoing share
557     void setshare(Node*, const char*, accesslevel_t, const char* = NULL);
558 
559     // Add/delete/remind outgoing pending contact request
560     void setpcr(const char*, opcactions_t, const char* = NULL, const char* = NULL, handle = UNDEF);
561     void updatepcr(handle, ipcactions_t);
562 
563     // export node link or remove existing exported link for this node
564     error exportnode(Node*, int, m_time_t);
565     void getpubliclink(Node* n, int del, m_time_t ets); // auxiliar method to add req
566 
567     // add timer
568     error addtimer(TimerWithBackoff *twb);
569 
570     // add/delete sync
571     error isnodesyncable(Node*, bool* = NULL);
572 
573     error addsync(SyncConfig, const char*, string*, int = 0, void* = NULL);
574 
575     void delsync(Sync*, bool = true);
576 
577     // close all open HTTP connections
578     void disconnect();
579 
580     // close server-client HTTP connection
581     void catchup();
582     // abort lock request
583     void abortlockrequest();
584 
585     // abort session and free all state information
586     void logout();
587 
588     // free all state information
589     void locallogout(bool removecaches);
590 
591     // SDK version
592     const char* version();
593 
594     // get the last available version of the app
595     void getlastversion(const char *appKey);
596 
597     // get a local ssl certificate for communications with the webclient
598     void getlocalsslcertificate();
599 
600     // send a DNS request to resolve a hostname
601     void dnsrequest(const char*);
602 
603     // send a GeLB request for a service with a timeout (in ms) and a number of retries
604     void gelbrequest(const char*, int, int);
605 
606     // send chat stats
607     void sendchatstats(const char*, int port);
608 
609     // send chat logs with user's annonymous id
610     void sendchatlogs(const char*, const char*, int port);
611 
612     // send a HTTP request
613     void httprequest(const char*, int, bool = false, const char* = NULL, int = 1);
614 
615     // maximum outbound throughput (per target server)
616     int putmbpscap;
617 
618     // User-Agent header for HTTP requests
619     string useragent;
620 
621     // Issuer of a detected fake SSL certificate
622     string sslfakeissuer;
623 
624     // shopping basket
625     handle_vector purchase_basket;
626 
627     // enumerate Pro account purchase options
628     void purchase_enumeratequotaitems();
629 
630     // clear shopping basket
631     void purchase_begin();
632 
633     // add item to basket
634     void purchase_additem(int, handle, unsigned, const char *, unsigned, const char *, handle = UNDEF, int = 0, int64_t = 0);
635 
636     // submit purchased products for payment
637     void purchase_checkout(int);
638 
639     // submit purchase receipt for verification
640     void submitpurchasereceipt(int, const char*, handle lph = UNDEF, int phtype = 0, int64_t ts = 0);
641 
642     // store credit card
643     error creditcardstore(const char *);
644 
645     // get credit card subscriptions
646     void creditcardquerysubscriptions();
647 
648     // cancel credit card subscriptions
649     void creditcardcancelsubscriptions(const char *reason = NULL);
650 
651     // get payment methods
652     void getpaymentmethods();
653 
654     // store user feedback
655     void userfeedbackstore(const char *);
656 
657     // send event
658     void sendevent(int, const char *);
659     void sendevent(int, const char *, int tag);
660 
661     // create support ticket
662     void supportticket(const char *message, int type);
663 
664     // clean rubbish bin
665     void cleanrubbishbin();
666 
667     // change the storage status
668     bool setstoragestatus(storagestatus_t);
669 
670     // get info about a folder link
671     void getpubliclinkinfo(handle h);
672 
673     // send an sms to verificate a phone number (returns EARGS if phone number has invalid format)
674     error smsverificationsend(const string& phoneNumber, bool reVerifyingWhitelisted = false);
675 
676     // check the verification code received by sms is valid (returns EARGS if provided code has invalid format)
677     error smsverificationcheck(const string& verificationCode);
678 
679 #ifdef ENABLE_CHAT
680 
681     // create a new chat with multiple users and different privileges
682     void createChat(bool group, bool publicchat, const userpriv_vector *userpriv = NULL, const string_map *userkeymap = NULL, const char *title = NULL);
683 
684     // invite a user to a chat
685     void inviteToChat(handle chatid, handle uh, int priv, const char *unifiedkey = NULL, const char *title = NULL);
686 
687     // remove a user from a chat
688     void removeFromChat(handle chatid, handle uh);
689 
690     // get the URL of a chat
691     void getUrlChat(handle chatid);
692 
693     // process object arrays by the API server (users + privileges)
694     userpriv_vector * readuserpriv(JSON* j);
695 
696     // grant access to a chat peer to one specific node
697     void grantAccessInChat(handle chatid, handle h, const char *uid);
698 
699     // revoke access to a chat peer to one specific node
700     void removeAccessInChat(handle chatid, handle h, const char *uid);
701 
702     // update permissions of a peer in a chat
703     void updateChatPermissions(handle chatid, handle uh, int priv);
704 
705     // truncate chat from message id
706     void truncateChat(handle chatid, handle messageid);
707 
708     // set title of the chat
709     void setChatTitle(handle chatid, const char *title = NULL);
710 
711     // get the URL of the presence server
712     void getChatPresenceUrl();
713 
714     // register a token device to route push notifications
715     void registerPushNotification(int deviceType, const char *token = NULL);
716 
717     void archiveChat(handle chatid, bool archived);
718 
719     // request meta information from an url (title, description, icon)
720     void richlinkrequest(const char*);
721 
722     // create/get or delete chat-link
723     void chatlink(handle chatid, bool del, bool createifmissing);
724 
725     // get the URL for chat-link
726     void chatlinkurl(handle publichandle);
727 
728     // convert public chat into private chat
729     void chatlinkclose(handle chatid, const char *title);
730 
731     // auto-join publicchat
732     void chatlinkjoin(handle publichandle, const char *unifiedkey);
733 
734     // set retention time for a chatroom in seconds, after which older messages in the chat are automatically deleted
735     void setchatretentiontime(handle chatid, int period);
736 #endif
737 
738     // get mega achievements
739     void getaccountachievements(AchievementsDetails *details);
740 
741     // get mega achievements list (for advertising for unregistered users)
742     void getmegaachievements(AchievementsDetails *details);
743 
744     // get welcome pdf
745     void getwelcomepdf();
746 
747     // toggle global debug flag
748     bool toggledebug();
749 
750     bool debugstate();
751 
752     // report an event to the API logger
753     void reportevent(const char*, const char* = NULL);
754     void reportevent(const char*, const char*, int tag);
755 
756     // set max download speed
757     bool setmaxdownloadspeed(m_off_t bpslimit);
758 
759     // set max upload speed
760     bool setmaxuploadspeed(m_off_t bpslimit);
761 
762     // get max download speed
763     m_off_t getmaxdownloadspeed();
764 
765     // get max upload speed
766     m_off_t getmaxuploadspeed();
767 
768     // get the handle of the older version for a NewNode
769     handle getovhandle(Node *parent, string *name);
770 
771     // use HTTPS for all communications
772     bool usehttps;
773 
774     // use an alternative port for downloads (8080)
775     bool usealtdownport;
776 
777     // select the download port automatically
778     bool autodownport;
779 
780     // use an alternative port for uploads (8080)
781     bool usealtupport;
782 
783     // select the upload port automatically
784     bool autoupport;
785 
786     // finish downloaded chunks in order
787     bool orderdownloadedchunks;
788 
789     // disable public key pinning (for testing purposes)
790     static bool disablepkp;
791 
792     // retry API_ESSL errors
793     bool retryessl;
794 
795     // flag to request an extra loop of the SDK to finish something pending
796     bool looprequested;
797 
798     // timestamp until the bandwidth is overquota in deciseconds, related to Waiter::ds
799     m_time_t overquotauntil;
800 
801     // storage status
802     storagestatus_t ststatus;
803 
804     // warning timestamps related to storage overquota in paywall mode
805     vector<m_time_t> mOverquotaWarningTs;
806 
807     // deadline timestamp related to storage overquota in paywall mode
808     m_time_t mOverquotaDeadlineTs;
809 
810     // minimum bytes per second for streaming (0 == no limit, -1 == use default)
811     int minstreamingrate;
812 
813     // root URL for API requests
814     static string APIURL;
815 
816     // root URL for GeLB requests
817     static string GELBURL;
818 
819     // root URL for chat stats
820     static string CHATSTATSURL;
821 
822     // account auth for public folders
823     string accountauth;
824 
825     // file that is blocking the sync engine
826     LocalPath blockedfile;
827 
828     // stats id
829     static std::string statsid;
830 
831     // number of ongoing asynchronous fopen
832     int asyncfopens;
833 
834     // list of notifications to display to the user; includes items already seen
835     UserAlerts useralerts;
836 
837     // true if user data is cached
838     bool cachedug;
839 
840     // backoff for the expiration of cached user data
841     BackoffTimer btugexpiration;
842 
843 private:
844     BackoffTimer btcs;
845     BackoffTimer btbadhost;
846     BackoffTimer btworkinglock;
847 
848     vector<TimerWithBackoff *> bttimers;
849 
850     // server-client command trigger connection
851     std::unique_ptr<HttpReq> pendingsc;
852     std::unique_ptr<HttpReq> pendingscUserAlerts;
853     BackoffTimer btsc;
854 
855     // account is blocked: stops querying for action packets, pauses transfer & removes transfer slot availability
856     bool mBlocked = false;
857 
858     bool pendingscTimedOut = false;
859 
860 
861     // badhost report
862     HttpReq* badhostcs;
863 
864     // Working lock
865     HttpReq* workinglockcs;
866 
867     // notify URL for new server-client commands
868     string scnotifyurl;
869 
870     // unique request ID
871     char reqid[10];
872 
873     // auth URI component for API requests
874     string auth;
875 
876     // lang URI component for API requests
877     string lang;
878 
879     // public handle being used
880     handle publichandle;
881 
882     // API response JSON object
883     JSON response;
884 
885     // response record processing issue
886     bool warned;
887 
888     // next local user record identifier to use
889     int userid;
890 
891     // backoff for file attributes
892     BackoffTimer btpfa;
893     bool faretrying;
894 
895     // next internal upload handle
896     handle nextuh;
897 
898     // just one notification after fetchnodes and catch-up actionpackets
899     bool notifyStorageChangeOnStateCurrent = false;
900 
901     // maximum number of concurrent transfers (uploads + downloads)
902     static const unsigned MAXTOTALTRANSFERS;
903 
904     // maximum number of concurrent transfers (uploads or downloads)
905     static const unsigned MAXTRANSFERS;
906 
907     // maximum number of queued putfa before halting the upload queue
908     static const int MAXQUEUEDFA;
909 
910     // maximum number of concurrent putfa
911     static const int MAXPUTFA;
912 
913 #ifdef ENABLE_SYNC
914     // Resumes all resumable syncs
915     void resumeResumableSyncs();
916 #endif
917 
918     // update time at which next deferred transfer retry kicks in
919     void nexttransferretry(direction_t d, dstime*);
920 
921     // a TransferSlot chunk failed
922     bool chunkfailed;
923 
924     // fetch state serialize from local cache
925     bool fetchsc(DbTable*);
926 
927     // remove old (2 days or more) transfers from cache, if they were not resumed
928     void purgeOrphanTransfers(bool remove = false);
929 
930     // close the local transfer cache
931     void closetc(bool remove = false);
932 
933     // server-client command processing
934     void sc_updatenode();
935     Node* sc_deltree();
936     handle sc_newnodes();
937     void sc_contacts();
938     void sc_keys();
939     void sc_fileattr();
940     void sc_userattr();
941     bool sc_shares();
942     bool sc_upgrade();
943     void sc_paymentreminder();
944     void sc_opc();
945     void sc_ipc();
946     void sc_upc(bool incoming);
947     void sc_ph();
948     void sc_se();
949 #ifdef ENABLE_CHAT
950     void sc_chatupdate(bool readingPublicChat);
951     void sc_chatnode();
952     void sc_chatflags();
953 #endif
954     void sc_uac();
955     void sc_la();
956     void sc_ub();
957 
958     void init();
959 
960     // remove caches
961     void removeCaches();
962 
963     // add node to vector and return index
964     unsigned addnode(node_vector*, Node*) const;
965 
966     // add child for consideration in syncup()/syncdown()
967     void addchild(remotenode_map*, string*, Node*, list<string>*, FileSystemType fsType) const;
968 
969     // crypto request response
970     void cr_response(node_vector*, node_vector*, JSON*);
971 
972     // read node tree from JSON object
973     void readtree(JSON*);
974 
975     // used by wait() to handle event timing
976     void checkevent(dstime, dstime*, dstime*);
977 
978     // converts UTF-8 to 32-bit word array
979     static char* utf8_to_a32forjs(const char*, int*);
980 
981     // was the app notified of a retrying CS request?
982     bool csretrying;
983 
984     // encode/query handle type
985     void encodehandletype(handle*, bool);
986     bool isprivatehandle(handle*);
987 
988     // add direct read
989     void queueread(handle, bool, SymmCipher*, int64_t, m_off_t, m_off_t, void*, const char* = NULL, const char* = NULL, const char* = NULL);
990 
991     // execute pending direct reads
992     bool execdirectreads();
993 
994     // maximum number parallel connections for the direct read subsystem
995     static const int MAXDRSLOTS = 16;
996 
997     // abort queued direct read(s)
998     void abortreads(handle, bool, m_off_t, m_off_t);
999 
1000     static const char PAYMENT_PUBKEY[];
1001 
1002 public:
1003     void enabletransferresumption(const char *loggedoutid = NULL);
1004     void disabletransferresumption(const char *loggedoutid = NULL);
1005 
1006     // application callbacks
1007     struct MegaApp* app;
1008 
1009     // event waiter
1010     Waiter* waiter;
1011 
1012     // HTTP access
1013     HttpIO* httpio;
1014 
1015     // directory change notification
1016     struct FileSystemAccess* fsaccess;
1017 
1018     // bitmap graphics handling
1019     GfxProc* gfx;
1020 
1021     // enable / disable the gfx layer
1022     bool gfxdisabled;
1023 
1024     // DB access
1025     DbAccess* dbaccess = nullptr;
1026 
1027     // state cache table for logged in user
1028     DbTable* sctable;
1029 
1030     // there is data to commit to the database when possible
1031     bool pendingsccommit;
1032 
1033     // transfer cache table
1034     DbTable* tctable;
1035 
1036     // during processing of request responses, transfer table updates can be wrapped up in a single begin/commit
1037     DBTableTransactionCommitter* mTctableRequestCommitter = nullptr;
1038 
1039     // scsn as read from sctable
1040     handle cachedscsn;
1041 
1042     // initial state load in progress?  initial state can come from the database cache or via an 'f' command to the API.
1043     // Either way there can still be a lot of historic actionpackets to follow since that snaphot, especially if the user has not been online for a long time.
1044     bool fetchingnodes;
1045     int fetchnodestag;
1046 
1047     // have we just completed fetching new nodes?  (ie, caught up on all the historic actionpackets since the fetchnodes)
1048     bool statecurrent;
1049 
1050     // pending file attribute writes
1051     putfa_list queuedfa;
1052 
1053     // current file attributes being sent
1054     putfa_list activefa;
1055 
1056     // API request queue double buffering:
1057     // reqs[r] is open for adding commands
1058     // reqs[r^1] is being processed on the API server
1059     HttpReq* pendingcs;
1060 
1061     // pending HTTP requests
1062     pendinghttp_map pendinghttp;
1063 
1064     // record type indicator for sctable
1065     enum { CACHEDSCSN, CACHEDNODE, CACHEDUSER, CACHEDLOCALNODE, CACHEDPCR, CACHEDTRANSFER, CACHEDFILE, CACHEDCHAT } sctablerectype;
1066 
1067     // open/create state cache database table
1068     void opensctable();
1069 
1070     // initialize/update state cache referenced sctable
1071     void initsc();
1072     void updatesc();
1073     void finalizesc(bool);
1074 
1075     // flag to pause / resume the processing of action packets
1076     bool scpaused;
1077 
1078     // MegaClient-Server response JSON
1079     JSON json;
1080 
1081     // Server-MegaClient request JSON and processing state flag ("processing a element")
1082     JSON jsonsc;
1083     bool insca;
1084     bool insca_notlast;
1085 
1086     // no two interrelated client instances should ever have the same sessionid
1087     char sessionid[10];
1088 
1089     // session key to protect local storage
1090     string sessionkey;
1091 
1092     // key protecting non-shareable GPS coordinates in nodes
1093     string unshareablekey;
1094 
1095     // application key
1096     char appkey[16];
1097 
1098     // incoming shares to be attached to a corresponding node
1099     newshare_list newshares;
1100 
1101     // current request tag
1102     int reqtag;
1103 
1104     // user maps: by handle and by case-normalized e-mail address
1105     uh_map uhindex;
1106     um_map umindex;
1107 
1108     // mapping of pending contact handles to their structure
1109     handlepcr_map pcrindex;
1110 
1111     // pending file attributes
1112     fa_map pendingfa;
1113 
1114     // upload waiting for file attributes
1115     handletransfer_map faputcompletion;
1116 
1117     // file attribute fetch channels
1118     fafc_map fafcs;
1119 
1120     // generate attribute string based on the pending attributes for this upload
1121     void pendingattrstring(handle, string*);
1122 
1123     // active/pending direct reads
1124     handledrn_map hdrns;   // DirectReadNodes, main ownership.  One per file, each with one DirectRead per client request.
1125     dsdrn_map dsdrns;      // indicates the time at which DRNs should be retried
1126     dr_list drq;           // DirectReads that are in DirectReadNodes which have fectched URLs
1127     drs_list drss;         // DirectReadSlot for each DR in drq, up to Max
1128 
1129     // merge newly received share into nodes
1130     void mergenewshares(bool);
1131     void mergenewshare(NewShare *s, bool notify);    // merge only the given share
1132 
1133     // transfer queues (PUT/GET)
1134     transfer_map transfers[2];
1135     BackoffTimerGroupTracker transferRetryBackoffs[2];
1136 
1137     // transfer list to manage the priority of transfers
1138     TransferList transferlist;
1139 
1140     // cached transfers (PUT/GET)
1141     transfer_map cachedtransfers[2];
1142 
1143     // cached files and their dbids
1144     vector<string> cachedfiles;
1145     vector<uint32_t> cachedfilesdbids;
1146 
1147     // database IDs of cached files and transfers
1148     // waiting for the completion of a putnodes
1149     pendingdbid_map pendingtcids;
1150 
1151     // path of temporary files
1152     // waiting for the completion of a putnodes
1153     pendingfiles_map pendingfiles;
1154 
1155     // transfer tslots
1156     transferslot_list tslots;
1157 
1158     // keep track of next transfer slot timeout
1159     BackoffTimerGroupTracker transferSlotsBackoff;
1160 
1161     // next TransferSlot to doio() on
1162     transferslot_list::iterator slotit;
1163 
1164     // FileFingerprint to node mapping
1165     Fingerprints mFingerprints;
1166 
1167     // flag to skip removing nodes from mFingerprints when all nodes get deleted
1168     bool mOptimizePurgeNodes = false;
1169 
1170     // send updates to app when the storage size changes
1171     int64_t mNotifiedSumSize = 0;
1172 
1173     // asymmetric to symmetric key rewriting
1174     handle_vector nodekeyrewrite;
1175     handle_vector sharekeyrewrite;
1176 
1177     static const char* const EXPORTEDLINK;
1178 
1179     // default number of seconds to wait after a bandwidth overquota
1180     static dstime DEFAULT_BW_OVERQUOTA_BACKOFF_SECS;
1181 
1182     // number of seconds to invalidate the cached user data
1183     static dstime USER_DATA_EXPIRATION_BACKOFF_SECS;
1184 
1185     // total number of Node objects
1186     long long totalNodes;
1187 
1188     // tracks how many nodes have had a successful applykey()
1189     long long mAppliedKeyNodeCount = 0;
1190 
1191     // server-client request sequence number
1192     SCSN scsn;
1193 
1194     void purgenodes(node_vector* = NULL);
1195     void purgeusers(user_vector* = NULL);
1196     bool readusers(JSON*, bool actionpackets);
1197 
1198     user_vector usernotify;
1199     void notifyuser(User*);
1200 
1201     pcr_vector pcrnotify;
1202     void notifypcr(PendingContactRequest*);
1203 
1204     node_vector nodenotify;
1205     void notifynode(Node*);
1206 
1207     // update transfer in the persistent cache
1208     void transfercacheadd(Transfer*, DBTableTransactionCommitter*);
1209 
1210     // remove a transfer from the persistent cache
1211     void transfercachedel(Transfer*, DBTableTransactionCommitter* committer);
1212 
1213     // add a file to the persistent cache
1214     void filecacheadd(File*, DBTableTransactionCommitter& committer);
1215 
1216     // remove a file from the persistent cache
1217     void filecachedel(File*, DBTableTransactionCommitter* committer);
1218 
1219 #ifdef ENABLE_CHAT
1220     textchat_map chatnotify;
1221     void notifychat(TextChat *);
1222 #endif
1223 
1224 #ifdef USE_MEDIAINFO
1225     MediaFileInfo mediaFileInfo;
1226 #endif
1227 
1228     // write changed/added/deleted users to the DB cache and notify the
1229     // application
1230     void notifypurge();
1231 
1232     // remove node subtree
1233     void deltree(handle);
1234 
1235     Node* nodebyhandle(handle);
1236     Node* nodebyfingerprint(FileFingerprint*);
1237 #ifdef ENABLE_SYNC
1238     Node* nodebyfingerprint(LocalNode*);
1239 #endif /* ENABLE_SYNC */
1240 
1241     node_vector *nodesbyfingerprint(FileFingerprint* fingerprint);
1242     void nodesbyoriginalfingerprint(const char* fingerprint, Node* parent, node_vector *nv);
1243 
1244     // get up to "maxcount" nodes, not older than "since", ordered by creation time
1245     node_vector getRecentNodes(unsigned maxcount, m_time_t since, bool includerubbishbin);
1246 
1247     // get a vector of recent actions in the account
1248     recentactions_vector getRecentActions(unsigned maxcount, m_time_t since);
1249 
1250     // determine if the file is a video, photo, or media (video or photo).  If the extension (with trailing .) is not precalculated, pass null
1251     bool nodeIsMedia(const Node*, bool* isphoto, bool* isvideo) const;
1252 
1253     // generate & return upload handle
1254     handle getuploadhandle();
1255 
1256     // maps node handle to public handle
1257     std::map<handle, handle> mPublicLinks;
1258 
1259 #ifdef ENABLE_SYNC
1260     // sync debris folder name in //bin
1261     static const char* const SYNCDEBRISFOLDERNAME;
1262 
1263     // we are adding the //bin/SyncDebris/yyyy-mm-dd subfolder(s)
1264     bool syncdebrisadding;
1265 
1266     // minute of the last created folder in SyncDebris
1267     m_time_t syncdebrisminute;
1268 
1269     // activity flag
1270     bool syncactivity;
1271 
1272     // syncops indicates that a sync-relevant tree update may be pending
1273     bool syncops;
1274 
1275     // app scanstate flag
1276     bool syncscanstate;
1277 
1278     // scan required flag
1279     bool syncdownrequired;
1280 
1281     bool syncuprequired;
1282 
1283     // block local fs updates processing while locked ops are in progress
1284     bool syncfsopsfailed;
1285 
1286     // retry accessing temporarily locked filesystem items
1287     bool syncfslockretry;
1288     BackoffTimer syncfslockretrybt;
1289 
1290     // retry of transiently failed local filesystem ops
1291     bool syncdownretry;
1292     BackoffTimer syncdownbt;
1293 
1294     // sync PUT Nagle timer
1295     bool syncnagleretry;
1296     BackoffTimer syncnaglebt;
1297 
1298     // timer for extra notifications
1299     // (workaround for buggy network filesystems)
1300     bool syncextraretry;
1301     BackoffTimer syncextrabt;
1302 
1303     // rescan timer if fs notification unavailable or broken
1304     bool syncscanfailed;
1305     BackoffTimer syncscanbt;
1306 
1307     // vanished from a local synced folder
1308     localnode_set localsyncnotseen;
1309 
1310     // maps local fsid to corresponding LocalNode*
1311     handlelocalnode_map fsidnode;
1312 
1313     // local nodes that need to be added remotely
1314     localnode_vector synccreate;
1315 
1316     // number of sync-initiated putnodes() in progress
1317     int syncadding;
1318 
1319     // total number of LocalNode objects
1320     long long totalLocalNodes;
1321 
1322     // sync id dispatch
1323     handle nextsyncid();
1324     handle currsyncid;
1325 
1326     // SyncDebris folder addition result
1327     void putnodes_syncdebris_result(error, NewNode*);
1328 
1329     // if no sync putnodes operation is in progress, apply the updates stored
1330     // in syncadded/syncdeleted/syncoverwritten to the remote tree
1331     void syncupdate();
1332 
1333     // create missing folders, copy/start uploading missing files
1334     bool syncup(LocalNode*, dstime*);
1335 
1336     // sync putnodes() completion
1337     void putnodes_sync_result(error, NewNode*, int);
1338 
1339     // start downloading/copy missing files, create missing directories
1340     bool syncdown(LocalNode*, LocalPath&, bool);
1341 
1342     // move nodes to //bin/SyncDebris/yyyy-mm-dd/ or unlink directly
1343     void movetosyncdebris(Node*, bool);
1344 
1345     // move queued nodes to SyncDebris (for syncing into the user's own cloud drive)
1346     void execmovetosyncdebris();
1347     node_set todebris;
1348 
1349     // unlink queued nodes directly (for inbound share syncing)
1350     void execsyncunlink();
1351     node_set tounlink;
1352 
1353     // commit all queueud deletions
1354     void execsyncdeletions();
1355 
1356     // process localnode subtree
1357     void proclocaltree(LocalNode*, LocalTreeProc*);
1358 
1359     // unlink the LocalNode from the corresponding node
1360     // if the associated local file or folder still exists
1361     void unlinkifexists(LocalNode*, FileAccess*, LocalPath& reuseBuffer);
1362 #endif
1363 
1364     // recursively cancel transfers in a subtree
1365     void stopxfers(LocalNode*, DBTableTransactionCommitter& committer);
1366 
1367     // update paths of all PUT transfers
1368     void updateputs();
1369 
1370     // determine if all transfer slots are full
1371     bool slotavail() const;
1372 
1373     // transfer queue dispatch/retry handling
1374     void dispatchTransfers();
1375 
1376     void defer(direction_t, int td, int = 0);
1377     void freeq(direction_t);
1378 
1379     dstime transferretrydelay();
1380 
1381     // client-server request double-buffering
1382     RequestDispatcher reqs;
1383 
1384     // returns if the current pendingcs includes a fetch nodes command
1385     bool isFetchingNodesPendingCS();
1386 
1387     // upload handle -> node handle map (filled by upload completion)
1388     handlepair_set uhnh;
1389 
1390     // transfer chunk failed
1391     void setchunkfailed(string*);
1392     string badhosts;
1393 
1394     bool requestLock;
1395     dstime disconnecttimestamp;
1396     dstime lastDispatchTransfersDs = 0;
1397 
1398     // process object arrays by the API server
1399     int readnodes(JSON*, int, putsource_t = PUTNODES_APP, NewNode* = NULL, int = 0, int = 0, bool applykeys = false);
1400 
1401     void readok(JSON*);
1402     void readokelement(JSON*);
1403     void readoutshares(JSON*);
1404     void readoutshareelement(JSON*);
1405 
1406     void readipc(JSON*);
1407     void readopc(JSON*);
1408 
1409     error readmiscflags(JSON*);
1410 
1411     void procph(JSON*);
1412 
1413     void readcr();
1414     void readsr();
1415 
1416     void procsnk(JSON*);
1417     void procsuk(JSON*);
1418 
1419     void procmcf(JSON*);
1420     void procmcna(JSON*);
1421 
1422     void setkey(SymmCipher*, const char*);
1423     bool decryptkey(const char*, byte*, int, SymmCipher*, int, handle);
1424 
1425     void handleauth(handle, byte*);
1426 
1427     bool procsc();
1428 
1429     // API warnings
1430     void warn(const char*);
1431     bool warnlevel();
1432 
1433     Node* childnodebyname(Node*, const char*, bool = false);
1434     vector<Node*> childnodesbyname(Node*, const char*, bool = false);
1435 
1436     // purge account state and abort server-client connection
1437     void purgenodesusersabortsc(bool keepOwnUser);
1438 
1439     static const int USERHANDLE = 8;
1440     static const int PCRHANDLE = 8;
1441     static const int NODEHANDLE = 6;
1442     static const int CHATHANDLE = 8;
1443     static const int SESSIONHANDLE = 8;
1444     static const int PURCHASEHANDLE = 8;
1445     static const int CONTACTLINKHANDLE = 6;
1446     static const int CHATLINKHANDLE = 6;
1447 
1448     // max new nodes per request
1449     static const int MAX_NEWNODES = 2000;
1450 
1451     // session ID length (binary)
1452     static const unsigned SIDLEN = 2 * SymmCipher::KEYLENGTH + USERHANDLE * 4 / 3 + 1;
1453 
1454     void proccr(JSON*);
1455     void procsr(JSON*);
1456 
1457     // account access: master key
1458     // folder link access: folder key
1459     SymmCipher key;
1460 
1461     // dummy key to obfuscate non protected cache
1462     SymmCipher tckey;
1463 
1464     // account access (full account): RSA private key
1465     AsymmCipher asymkey;
1466     string mPrivKey;    // serialized version for apps
1467 
1468     // RSA public key
1469     AsymmCipher pubk;
1470 
1471     // EdDSA signing key (Ed25519 private key seed).
1472     EdDSA *signkey;
1473 
1474     // ECDH key (x25519 private key).
1475     ECDH *chatkey;
1476 
1477     // set when keys for every current contact have been checked
1478     AuthRingsMap mAuthRings;
1479 
1480     // used during initialization to accumulate required updates to authring (to send them all atomically)
1481     AuthRingsMap mAuthRingsTemp;
1482 
1483     // true while authrings are being fetched
1484     bool mFetchingAuthrings;
1485 
1486     // actual state of keys
1487     bool fetchingkeys;
1488 
1489     // invalidate received keys (when fail to load)
1490     void clearKeys();
1491 
1492     // delete chatkey and signing key
1493     void resetKeyring();
1494 
1495     // binary session ID
1496     string sid;
1497 
1498     // distinguish activity from different MegaClients in logs
1499     string clientname;
1500 
1501     // number our http requests so we can distinguish them (and the curl debug logging for them) in logs
1502     unsigned transferHttpCounter = 0;
1503 
1504     // apply keys
1505     void applykeys();
1506 
1507     // send andy key rewrites prepared when keys were applied
1508     void sendkeyrewrites();
1509 
1510     // symmetric password challenge
1511     int checktsid(byte* sidbuf, unsigned len);
1512 
1513     // locate user by e-mail address or by handle
1514     User* finduser(const char*, int = 0);
1515     User* finduser(handle, int = 0);
1516     User* ownuser();
1517     void mapuser(handle, const char*);
1518     void discarduser(handle, bool = true);
1519     void discarduser(const char*);
1520     void mappcr(handle, PendingContactRequest*);
1521     bool discardnotifieduser(User *);
1522 
1523     PendingContactRequest* findpcr(handle);
1524 
1525     // queue public key request for user
1526     void queuepubkeyreq(User*, std::unique_ptr<PubKeyAction>);
1527     void queuepubkeyreq(const char*, std::unique_ptr<PubKeyAction>);
1528 
1529     // rewrite foreign keys of the node (tree)
1530     void rewriteforeignkeys(Node* n);
1531 
1532     // simple string hash
1533     static void stringhash(const char*, byte*, SymmCipher*);
1534     static uint64_t stringhash64(string*, SymmCipher*);
1535 
1536     // set authentication context, either a session ID or a exported folder node handle
1537     void setsid(const byte*, unsigned);
1538     void setrootnode(handle);
1539 
1540     bool setlang(string *code);
1541 
1542     // returns the handle of the root node if the account is logged into a public folder, otherwise UNDEF.
1543     handle getrootpublicfolder();
1544 
1545     // returns the public handle of the folder link if the account is logged into a public folder, otherwise UNDEF.
1546     handle getpublicfolderhandle();
1547 
1548     //returns the top-level node for a node
1549     Node *getrootnode(Node*);
1550 
1551     //returns true if the node referenced by the handle belongs to the logged-in account
1552     bool isPrivateNode(handle h);
1553 
1554     //returns true if the node referenced by the handle belongs to other account than the logged-in account
1555     bool isForeignNode(handle h);
1556 
1557     // process node subtree
1558     void proctree(Node*, TreeProc*, bool skipinshares = false, bool skipversions = false);
1559 
1560     // hash password
1561     error pw_key(const char*, byte*) const;
1562 
1563     // convert hex digit to number
1564     static int hexval(char);
1565 
1566     // Since it's quite expensive to create a SymmCipher, these are provided to use for quick operations - just set the key and use.
1567     SymmCipher tmpnodecipher;
1568     SymmCipher tmptransfercipher;
1569 
1570     void exportDatabase(string filename);
1571     bool compareDatabases(string filename1, string filename2);
1572 
1573     // request a link to recover account
1574     void getrecoverylink(const char *email, bool hasMasterkey);
1575 
1576     // query information about recovery link
1577     void queryrecoverylink(const char *link);
1578 
1579     // request private key for integrity checking the masterkey
1580     void getprivatekey(const char *code);
1581 
1582     // confirm a recovery link to restore the account
1583     void confirmrecoverylink(const char *code, const char *email, const char *password, const byte *masterkey = NULL, int accountversion = 1);
1584 
1585     // request a link to cancel the account
1586     void getcancellink(const char *email, const char* = NULL);
1587 
1588     // confirm a link to cancel the account
1589     void confirmcancellink(const char *code);
1590 
1591     // get a link to change the email address
1592     void getemaillink(const char *email, const char *pin = NULL);
1593 
1594     // confirm a link to change the email address
1595     void confirmemaillink(const char *code, const char *email, const byte *pwkey);
1596 
1597     // create contact link
1598     void contactlinkcreate(bool renew);
1599 
1600     // query contact link
1601     void contactlinkquery(handle);
1602 
1603     // delete contact link
1604     void contactlinkdelete(handle);
1605 
1606     // multi-factor authentication setup
1607     void multifactorauthsetup(const char* = NULL);
1608 
1609     // multi-factor authentication get
1610     void multifactorauthcheck(const char*);
1611 
1612     // multi-factor authentication disable
1613     void multifactorauthdisable(const char*);
1614 
1615     // fetch time zone
1616     void fetchtimezone();
1617 
1618     void keepmealive(int, bool enable = true);
1619 
1620     void getpsa();
1621 
1622     // tells the API the user has seen existing alerts
1623     void acknowledgeuseralerts();
1624 
1625     // manage overquota errors
1626     void activateoverquota(dstime timeleft, bool isPaywall);
1627 
1628     // achievements enabled for the account
1629     bool achievements_enabled;
1630 
1631     // non-zero if login with user+pwd was done (reset upon fetchnodes completion)
1632     bool isNewSession;
1633 
1634     // timestamp of the last login with user and password
1635     m_time_t tsLogin;
1636 
1637     // true if user has disabled fileversioning
1638     bool versions_disabled;
1639 
1640     // the SDK is trying to log out
1641     int loggingout = 0;
1642 
1643     // the logout request succeeded, time to clean up localy once returned from CS response processing
1644     bool loggedout = false;
1645 
1646     // true if the account is a master business account, false if it's a sub-user account
1647     BizMode mBizMode;
1648 
1649     // -1: expired, 0: inactive (no business subscription), 1: active, 2: grace-period
1650     BizStatus mBizStatus;
1651 
1652     // list of handles of the Master business account/s
1653     std::set<handle> mBizMasters;
1654 
1655     // timestamp when a business account will enter into Grace Period
1656     m_time_t mBizGracePeriodTs;
1657 
1658     // timestamp when a business account will finally expire
1659     m_time_t mBizExpirationTs;
1660 
1661     // whether the destructor has started running yet
1662     bool destructorRunning = false;
1663 
1664     MegaClientAsyncQueue mAsyncQueue;
1665 
1666     // Keep track of high level operation counts and times, for performance analysis
1667     struct PerformanceStats
1668     {
1669         CodeCounter::ScopeStats execFunction = { "MegaClient_exec" };
1670         CodeCounter::ScopeStats transferslotDoio = { "TransferSlot_doio" };
1671         CodeCounter::ScopeStats execdirectreads = { "execdirectreads" };
1672         CodeCounter::ScopeStats transferComplete = { "transfer_complete" };
1673         CodeCounter::ScopeStats prepareWait = { "MegaClient_prepareWait" };
1674         CodeCounter::ScopeStats doWait = { "MegaClient_doWait" };
1675         CodeCounter::ScopeStats checkEvents = { "MegaClient_checkEvents" };
1676         CodeCounter::ScopeStats applyKeys = { "MegaClient_applyKeys" };
1677         CodeCounter::ScopeStats dispatchTransfers = { "dispatchTransfers" };
1678         CodeCounter::ScopeStats csResponseProcessingTime = { "cs batch response processing" };
1679         CodeCounter::ScopeStats scProcessingTime = { "sc processing" };
1680         uint64_t transferStarts = 0, transferFinishes = 0;
1681         uint64_t transferTempErrors = 0, transferFails = 0;
1682         uint64_t prepwaitImmediate = 0, prepwaitZero = 0, prepwaitHttpio = 0, prepwaitFsaccess = 0, nonzeroWait = 0;
1683         CodeCounter::DurationSum csRequestWaitTime;
1684         CodeCounter::DurationSum transfersActiveTime;
1685         std::string report(bool reset, HttpIO* httpio, Waiter* waiter, const RequestDispatcher& reqs);
1686     } performanceStats;
1687 
1688     std::string getDeviceid() const;
1689 
1690 #ifdef ENABLE_SYNC
1691     void resetSyncConfigs();
1692 #endif
1693 
1694     MegaClient(MegaApp*, Waiter*, HttpIO*, FileSystemAccess*, DbAccess*, GfxProc*, const char*, const char*, unsigned workerThreadCount);
1695     ~MegaClient();
1696 };
1697 } // namespace
1698 
1699 #if __cplusplus < 201100L
1700 #define char_is_not_digit std::not1(std::ptr_fun(static_cast<int(*)(int)>(std::isdigit)))
1701 #define char_is_not_space std::not1(std::ptr_fun<int, int>(std::isspace))
1702 #else
1703 #define char_is_not_digit [](char c) { return !std::isdigit(c); }
1704 #define char_is_not_space [](char c) { return !std::isspace(c); }
1705 #endif
1706 
1707 #endif
1708