### lftpget usage examples Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/lftpget.md Example invocations of lftpget covering download, resume, verbose with multiple URLs, and debug output. The -v option prints 'Retrieving ...' for each URL, and -d prepends 'debug 8;' to the generated lftp script. ```sh $ lftpget http://example.com/file.bin # download $ lftpget -c http://example.com/file.bin # resume $ lftpget -v ftp://user@host/pub/a.tar.gz b.tar.gz # verbose, multiple URLs $ lftpget -d https://example.com/dir/ # debug to stderr ``` -------------------------------- ### Building a single get job (as cmd_get does) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/transfer-jobs.md Shows how to construct a GetJob for a single 'get' operation, simplified from CMD(get)/CMD(put) in src/commands.cc:1716. Sets the operation name to 'get', optionally deletes files or reverses the job, and adds it to the parent job list. ```cpp // simplified from CMD(get)/CMD(put) in src/commands.cc:1716 Ref a(args->Copy()); a->setarg(0, "get"); // op name shown in status GetJob *job = new GetJob(session, a, cont /* -c */); if(delete_remote) job->DeleteFiles(); if(reverse) job->Reverse(); parent->AddNewJob(job); return job; ``` -------------------------------- ### Example variable registration with ResDecls Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/resmgr.md Shows how all variables are declared using ResDecls with an array of ResType entries. The array is terminated with a null entry. ```cpp // src/resource.cc:193-428 static ResType lftp_vars[] = { {"ftp:abor-max-wait", "15s", ResMgr::TimeIntervalValidate, 0}, {"ftp:passive-mode", "on", ResMgr::BoolValidate, 0}, ... {0} }; static ResDecls lftp_vars_register(lftp_vars); ``` -------------------------------- ### torrent command macro (src/Torrent.cc:4137) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/torrent.md Defines the torrent command. Options include -O/--output-directory, --force-valid, --dht-bootstrap, --share, --only-new, --only-incomplete. Positional args are .torrent files, torrent URLs, or magnet URIs. --only-new stops after metadata fetch; --share builds metadata from the given path and starts seeding. ```cpp CMD(torrent) // src/Torrent.cc:4137 ``` -------------------------------- ### TorrentBuild class public interface (src/Torrent.h:59) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/torrent.md Creates .torrent metadata from a local file tree (the torrent --share path). The constructor starts scanning top; piece SHA-1 hashes are computed asynchronously. GetMetadata() returns the finished bencoded .torrent contents. ```cpp public: TorrentBuild(const char *top); int Do(); bool Done() const { return done || error; } bool Failed() const { return error; } const char *ErrorText() const { return error->Text(); } BeNode *GetFilesNode() const { return info->lookup("files"); } void SetPiece(unsigned p,const xstring& sha1); const xstring& GetMetadata(); const char *GetBaseDirectory() const { return dirname(top_path); } const xstring& Status() const; ``` -------------------------------- ### Seed a directory and create metadata with lftp torrent --share Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/torrent.md Use --share to create a .torrent file from a directory and start seeding. The -O option specifies the output directory for the metadata file. ```lftp lftp> torrent --share -O /srv/torrents ./my-distro # creates my-distro.torrent in /srv/torrents and starts seeding ``` -------------------------------- ### Open Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Starts an operation on the specified file with the given mode and optional resume offset. The operation status can be checked via Done() and GetErrorCode(). ```APIDOC ## Open ### Description Starts an operation on the specified file with the given mode and optional resume offset. The operation status can be checked via Done() and GetErrorCode(). ### Method Open ### Parameters - `file` (const char*) - Required - Path to the file. - `mode` (int) - Required - Operation mode (e.g., READ, WRITE, REMOVE). - `pos` (off_t) - Optional - Resume offset (REST). Default is 0. ### Request Example ```cpp Open("/remote/file", READ, 0); ``` ### Response No return value. Use Done() and GetErrorCode() to check status. ``` -------------------------------- ### ftpget generated lftp script pattern Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/lftpget.md Shows the pattern of the lftp command generated by ftpget. The script passes user, port, host, and a command string to lftp -e. The command string includes settings and the actual get or listing command with flags and file arguments. ```sh lftp -u "$user" -p "$port" "$host" -e "set ...; $cmd $flags \"$file\" ...;" ``` -------------------------------- ### FileAccess::Open Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Opens a remote file for retrieval or storage. Supports optional starting position and open modes. ```APIDOC ## FileAccess::Open ### Description Opens a remote file for retrieval or storage. Supports optional starting position and open modes. ### Method Member function ### Signature ```cpp void FileAccess::Open(const char *path, int open_mode, long long pos = 0); ``` ### Parameters - **path** (string) - Required - The remote file path. - **open_mode** (int) - Required - The open mode (e.g., `FileAccess::RETRIEVE` for downloading). - **pos** (long long) - Optional - The starting position (byte offset) for the operation. Default is 0. ### Return Value None. ### Example ```cpp fa->Open("dir/file.bin", FileAccess::RETRIEVE, 0 /*pos*/); ``` ``` -------------------------------- ### Create FileAccess instance with protocol and host Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/protocols.md Creates a FileAccess object for a given protocol, host, and port. The protocol must be registered in the FileAccess::Protocol registry. ```cpp FileAccess *fa = FileAccess::New("sftp", "example.com", "22"); ``` -------------------------------- ### queue command usage Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/commands.md Shows the syntax for the lftp `queue` command, including adding, deleting, moving, and waiting for jobs. Each site has its own queue, and `cmd:queue-parallel` controls concurrent execution. ```text queue [-n num] add command before queue item num queue --delete|-d [index|wildcard] delete items (default: last) queue --move|-m [index] move items -q quiet -v verbose -Q re-queueable output queue wait queue a running job ``` -------------------------------- ### Equivalent manual lftpget and lftp invocations Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/lftpget.md Shows that lftpget -c is equivalent to a manual lftp -e command with 'set cmd:verbose y; get1 -c "";'. This demonstrates the wrapper's behavior and how to achieve the same result directly with lftp. ```sh # equivalent manual invocations lftpget -c http://example.com/big.tgz lftp -e 'set cmd:verbose y; get1 -c "http://example.com/big.tgz";' ``` -------------------------------- ### Programmatic mirror construction (as cmd_mirror does) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/mirror-job.md Constructs a MirrorJob with options like delete, verbose, exclude, parallel, pget, script file, max error count, and on-change callback, then adds it as a child job to the executing command. ```cpp MirrorJob *m = new MirrorJob(0, source_session, target_session, source_dir, target_dir); m->SetFlags(MirrorJob::DELETE, delete_flag); if(verbose) m->SetVerbose(verbose); m->SetExclude(exclude); // PatternSet built from -X options m->SetParallel(parallel); // --parallel m->SetPGet(use_pget); // --use-pget-n if(script_file) m->SetScriptFile(script_file); m->SetMaxErrorCount(max_error_count); m->SetOnChange(on_change); parent->AddNewJob(m); // becomes a child of the executing CmdExec return m; ``` -------------------------------- ### Create FileAccess instance from URL Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/protocols.md Parses a URL and creates a FileAccess object from it. Used by the `user` command and `open URL` path. ```cpp ParsedURL u("ftp://user:pass@host:2121/pub"); FileAccessRef fa2(FileAccess::New(&u)); ``` -------------------------------- ### Reading a setting with ResMgr::Query and QueryBool Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/resmgr.md Demonstrates two ways to query a resource value: directly via ResMgr::Query with a closure host, or through ResClient's QueryBool which applies the prefix and closure automatically. ```cpp // closure-scoped query as done by FileAccess ResValue v = ResMgr::Query("ftp:passive-mode", host); // closure = current host bool passive = v.to_bool(); // or through ResClient: bool passive = QueryBool("passive-mode"); // prefix "ftp:" + closure applied automatically ``` -------------------------------- ### Dry-run to a script (mirror --script) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/mirror-job.md Runs mirror in script-only mode, writing transfer commands to /tmp/mirror.sh without touching the network. Equivalent to --just-print or --dry-run. ```bash lftp> mirror --script=/tmp/mirror.sh ftp.example.com/pub/mirror ./local # writes the transfer commands to /tmp/mirror.sh without touching the network # (script_only; --just-print / --dry-run behave identically) ``` -------------------------------- ### Mkdir Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Creates a directory. If allpath is true, behaves like mkdir -p. ```APIDOC ## Mkdir ### Description Creates a directory. If allpath is true, behaves like mkdir -p. ### Method Mkdir ### Parameters - `rfile` (const char*) - Required - Directory path to create. - `allpath` (bool) - Optional - Create all intermediate directories. Default is false. ### Request Example ```cpp Mkdir("/remote/dir", true); ``` ### Response No return value. ``` -------------------------------- ### SMTaskInit class definition Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/smtask.md Internal bootstrap task used to initialize the scheduler. Not part of the public user-facing API. ```cpp class SMTaskInit : public SMTask { int Do(); public: SMTaskInit(); ~SMTaskInit(); }; ``` -------------------------------- ### Connect Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Establishes a connection to the specified host and port. This is the initial step in the session lifecycle. ```APIDOC ## Connect ### Description Establishes a connection to the specified host and port. This is the initial step in the session lifecycle. ### Method Connect ### Parameters - `h` (const char*) - Required - Hostname or IP address. - `p` (const char*) - Required - Port number as a string. ### Request Example ```cpp Connect("example.com", "21"); ``` ### Response No return value. ``` -------------------------------- ### Resolver class declaration (src/Resolver.h) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/protocols.md Async DNS resolver task with caching. Honors dns:* settings such as dns:cache-enable, dns:order, and dns:max-retries. Provides Done(), GetAddr(), and GetError() methods. ```cpp class Resolver : public SMTask { public: Resolver(const char *host,const char *port); ... int Done() const; // true when resolution finished sockaddr_u *GetAddr(); // next address int GetError(); // 0 on success ... }; ``` -------------------------------- ### Creating and launching a job with CmdExec::AddNewJob Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/job.md Pattern used across lftp commands to create a job via CmdExec::AddNewJob. The job is prepared, added to the parent, and returned; if run in background, the job stays alive. ```cpp // inside a CMD() handler FileCopy *c = new FileCopy(session, src, dst); if(!c->Prepare()) { ...error... return 0; } Job *j = new CopyJob(c, src_name, "get"); parent->AddNewJob(j); // gives it a jobno and a parent return j; // if the command was run in background, j stays alive ``` -------------------------------- ### Programmatic Torrent engine construction in C++ Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/torrent.md Pattern used by cmd_torrent and TorrentJob. Constructs a Torrent object, optionally skips validation, stops when complete, bootstraps DHT, and adds a TorrentJob to the parent. ```cpp // pattern used by cmd_torrent and TorrentJob Torrent *t = new Torrent(metainfo_or_magnet, cwd, output_dir); t->ForceValid(); // skip validation t->StopIfComplete(); if(dht_bootstrap) Torrent::BootstrapDHT(dht_bootstrap); TorrentJob *job = new TorrentJob(t); parent->AddNewJob(job); // job owns the engine ``` -------------------------------- ### Handling a redirection (FILE_MOVED) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Demonstrates how to detect a FILE_MOVED error and follow the new location by creating a new FileAccess session with the returned URL. Requires reopening at the new location file and mode. ```cpp fa->Open("file", FileAccess::RETRIEVE); for(;;) { SMTask::Schedule(); if(fa->Done()) break; } if(fa->GetErrorCode()==FileAccess::FILE_MOVED && fa->GetNewLocation()) { // follow the new location: open a new session for the returned URL FileAccessRef next(FileAccess::New(new ParsedURL(fa->GetNewLocation()))); ... /* reopen at fa->GetNewLocationFile() with GetNewLocationMode() */ } ``` -------------------------------- ### ftpget usage message Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/lftpget.md Shows the command-line usage and options for the ftpget compatibility script. Options include -p for port, -u for user/pass, -l for listing, -c for reget, -q for quiet, -v for verbose, and -o for output file. ```sh Usage: $0 [OPTS] host filename [-o local] [filename...] -p set port number -u login as user using pass as password -l get listing of specified directory(ies) -c reget specified file(s) -q quiet (no output) -v verbose (lots of output) -o output to this file (default - base name of filename) ``` -------------------------------- ### Downloading a file via the API Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Shows how to create a FileAccess object, log in, open a file for retrieval, read data in a loop, and close. Requires scheduling SMTask until Done() is true. Read returns bytes read or <=0 at EOF. ```cpp FileAccessRef fa(FileAccess::New("ftp","example.com","21")); fa->Login("user","pass"); while(!fa->Done()) { SMTask::Schedule(); } if(fa->GetErrorCode() != FileAccess::OK && fa->GetErrorCode() != FileAccess::SEE_ERRNO) error(...); fa->Open("dir/file.bin", FileAccess::RETRIEVE, 0 /*pos*/); while(!fa->Done()) { SMTask::Schedule(); int r = fa->Read(buf, sizeof(buf)); // r>0 bytes, r<=0 EOF if(r>0) write(fd, buf, r); } fa->Close(); ``` -------------------------------- ### Execute a command string with CmdExec (scripting API style) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/cmd-exec.md Shows how to create a CmdExec instance, feed it commands via FeedCmd, and run until the queue is empty with WaitDone. The exit code is retrieved via ExitCode(). This mirrors what main() uses for lftp -c "...". ```cpp CmdExec *exec = new CmdExec(0, 0); exec->SetCmdFeeder(lftp_feeder); // or a custom CmdFeeder exec->FeedCmd("open ftp.example.com\n"); exec->FeedCmd("get file.bin\n"); exec->WaitDone(); // run until the queue is empty int rc = exec->ExitCode(); ``` -------------------------------- ### lftpget usage message Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/lftpget.md Shows the command-line usage and options for the lftpget wrapper script. Options include -c for continue/reget, -d for debug output, and -v for verbose messages. ```sh Usage: $0 [-c] [-d] [-v] URL [URL...] -c continue, reget -d debug output -v verbose messages ``` -------------------------------- ### TorrentJob class declaration (src/Torrent.h:976) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/torrent.md Wraps a Torrent in a Job so torrent works like any other background job: job numbering, jobs listing, Ctrl-C handling, and process-exit join. ```cpp class TorrentJob : public Job { SMTaskRef torrent; bool completed; bool done; public: TorrentJob(Torrent *); ~TorrentJob(); int Do(); int Done() { return done; } xstring& FormatStatus(xstring&,int v,const char *tab); void ShowRunStatus(const SMTaskRef& s); int AcceptSig(int); void PrepareToDie(); }; ``` -------------------------------- ### pget with continuation Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/transfer-jobs.md Two invocations of pget on the same file require the status file. The first splits into pget:default-n chunks and saves big.iso.lftp-pget-status; the second with -c reuses the status file to fetch only missing ranges. ```lftp lftp> pget big.iso # splits into pget:default-n chunks, saves big.iso.lftp-pget-status lftp> pget -c big.iso # reuses the status file; only missing ranges are fetched ``` -------------------------------- ### Register a module command with CmdExec::RegisterCommand Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/cmd-exec.md Shows how module authors expose a C function via module_init to register a new command. The command handler uses parent->args and parent->eprintf, sets parent->exit_code, and returns a Job. RegisterCommand takes the command name, handler, usage string, and help text. ```cpp // module authors implement a C function exposed via module_init #include "CmdExec.h" static Job *cmd_myget(CmdExec *parent) { #define args (parent->args) parent->exit_code = 1; const char *file = args->getarg(1); if(!file) { parent->eprintf("usage: myget \n"); return 0; } args->rewind(); ... // build a Job and return it parent->exit_code = 0; return job; } #undef args void myget_module_init(int argc,const char *const *argv) { CmdExec::RegisterCommand("myget", cmd_myget, "myget ", "myget - example module command\n"); } ``` -------------------------------- ### IOReady Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Checks if the I/O is ready for reading or writing. ```APIDOC ## IOReady ### Description Checks if the I/O is ready for reading or writing. ### Method IOReady ### Parameters None. ### Request Example ```cpp bool ready = IOReady(); ``` ### Response Returns true if I/O is ready, false otherwise. ``` -------------------------------- ### Download a torrent with lftp torrent command Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/torrent.md Use the torrent command to download from a .torrent file or a magnet link. The -O option specifies the output directory. The jobs command shows progress. ```lftp lftp> torrent ubuntu-24.04.iso.torrent lftp> torrent -O /mnt/data magnet:?xt=urn:btih:... lftp> jobs # [0] torrent : 45.2% (123.4 MiB, 2.1 MiB/s, ETA 1:02) ``` -------------------------------- ### SMTask scheduling pattern with Block and TimeoutS Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/smtask.md A common pattern in lftp (e.g., src/FileCopy.cc, src/commands.cc) that waits for socket readability or a deadline, then advances a state machine. Uses SMTask::Ready, SMTask::Block, SMTask::now.Passed, and SMTask::TimeoutS to stall until work is available. ```cpp // inside a FileAccess::Do() implementation if(sock_valid && !SMTask::Ready(sock, POLLIN)) { SMTask::Block(sock, POLLIN); // wake when readable return STALL; } if(SMTask::now.Passed(10)) { SMTask::TimeoutS(5); // wake after 5 s return STALL; } ... /* do work */ return MOVED; // or STALL when finished with this slice ``` -------------------------------- ### Login Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Performs authentication with the given username and password. If both are null, anonymous login is attempted. ```APIDOC ## Login ### Description Performs authentication with the given username and password. If both are null, anonymous login is attempted. ### Method Login ### Parameters - `u` (const char*) - Required - Username. - `p` (const char*) - Required - Password. ### Request Example ```cpp Login("user", "pass"); ``` ### Response No return value. ``` -------------------------------- ### Do Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Advances the state machine. Pure virtual; must be implemented by subclasses. ```APIDOC ## Do ### Description Advances the state machine. Pure virtual; must be implemented by subclasses. ### Method Do ### Parameters None. ### Request Example ```cpp int result = Do(); ``` ### Response Returns an int indicating progress or status. ``` -------------------------------- ### LocalAccess class declaration (src/LocalAccess.h) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/protocols.md Declares the LocalAccess class for the 'file' protocol. Connect and login methods are no-ops; IsConnected() reports level 2 (local). Settings include file:charset, file:use-lock, and file:use-fallocate. ```cpp class LocalAccess : public FileAccess { Ref stream; bool done; void errno_handle(); void fill_array_info(); public: void Init(); LocalAccess(); LocalAccess(const LocalAccess *); void Connect(const char *host,const char *port) {} // no-op void AnonymousLogin() {} void Login(const char *u,const char *p) {} void ResetLocationData() {} const char *GetProto() const { return "file"; } FileAccess *Clone() const { return new LocalAccess(this); } static FileAccess *New(); bool SameLocationAs(const FileAccess *fa) const; int Read(Buffer *buf,int size); int Write(const void *buf,int size); int StoreStatus(); int Do(); int Done(); void Close(); const char *CurrentStatus(); static void ClassInit(); ListInfo *MakeListInfo(const char *path); Glob *MakeGlob(const char *pattern); DirList *MakeDirList(ArgV *a); }; ``` -------------------------------- ### GetJob class declaration (src/GetJob.h) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/transfer-jobs.md Defines the multi-file transfer job used by get/put/mget/mput/pget. Constructor parses command-line args; c=true enables continue/resume. Methods control deletion, direction, and target removal. ```cpp class GetJob : public CopyJobEnv, ResClient { FileCopyPeer *SrcLocal(const char *src); FileCopyPeer *DstLocal(const char *dst); FileCopyPeer *CreateCopyPeer(const ParsedURL &url,const char *path,FA::open_mode mode); FileCopyPeer *CreateCopyPeer(const char *path,FA::open_mode mode); bool IsRemoteNonURL(const ParsedURL &url,FA::open_mode mode); bool IsLocalNonURL(const ParsedURL &url,FA::open_mode mode); static bool IsLocal(const ParsedURL &url); protected: FileCopyPeer *CreateCopyPeer(FileAccess *session,const char *path,FA::open_mode mode); FileCopyPeer *CreateCopyPeer(const FileAccessRef& session,const char *path,FA::open_mode mode); void NextFile(); bool make_dirs; bool delete_files; bool remove_target_first; bool truncate_target_first; bool reverse; public: GetJob(FileAccess *s,ArgV *a,bool c=false); void DeleteFiles() { delete_files=true; } void RemoveSourceLater() { delete_files=true; } void Reverse() { reverse=true; } // put void RemoveTargetFirst() { remove_target_first=true; } }; ``` -------------------------------- ### Signal and kill semantics for jobs Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/job.md Shows foreground interruption via AcceptSig(SIGINT) and interactive kill commands Job::Kill and Job::KillAll. Job::Kill calls SMTask::Delete; death is synchronous only if the job is not running. ```cpp // foreground interruption: CmdExec forwards SIGINT to its running job if(job->AcceptSig(SIGINT) == ...) { } // job may die (WANTDIE) or ignore // from the interactive side Job::Kill(jobno); // delete job while it is running Job::KillAll(); // used by sig_term() in src/lftp.cc ``` -------------------------------- ### Http, HFtp, Https class declarations (src/Http.h:31) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/protocols.md Declares the Http class and its subclasses HFtp (FTP over HTTP proxy) and Https. Http implements HTTP behaviors such as keep-alive, chunked transfer, gzip/deflate decoding, auth, cookies, redirects, partial WebDAV, range requests, and content-type/charset sniffing. ```cpp class Http : public NetAccess { enum state_t { DISCONNECTED, CONNECTING, CONNECTED, RECEIVING_HEADER, RECEIVING_BODY, DONE }; enum tunnel_state_t { NO_TUNNEL, TUNNEL_WAITING, TUNNEL_ESTABLISHED }; public: static void ClassInit(); Http(); Http(const Http *); ~Http(); const char *GetProto() const { return "http"; } FileAccess *Clone() const { return new Http(this); } static FileAccess *New(); FileSet *ParseLongList(const char *buf,int len,int *err=0) const; int Do(); int Done(); int Read(Buffer *,int); int Write(const void *,int); int StoreStatus(); int SendEOT(); int Buffered(); void ResetLocationData(); void Close(); const char *CurrentStatus(); void Reconfig(const char *name=0); bool SameSiteAs(const FileAccess *fa) const; bool SameLocationAs(const FileAccess *fa) const; DirList *MakeDirList(ArgV *a); Glob *MakeGlob(const char *pattern); ListInfo *MakeListInfo(const char *path); void UseCache(bool use); bool NeedSizeDateBeforehand() { return true; } void SuspendInternal(); void ResumeInternal(); static const time_t ATOTM_ERROR = -1; static time_t atotm (const char *time_string); }; class HFtp : public Http { // FTP over HTTP (via proxy) public: HFtp(); HFtp(const HFtp *); ~HFtp(); const char *GetProto() const { return "hftp"; } FileAccess *Clone() const { return new HFtp(this); } static FileAccess *New(); virtual void Login(const char *,const char *); virtual void Reconfig(const char *); }; class Https : public Http { public: Https(); Https(const Https *); ~Https(); const char *GetProto() const { return "https"; } FileAccess *Clone() const { return new Https(this); } static FileAccess *New(); }; ``` -------------------------------- ### Ftp class declaration (src/ftpclass.h:41) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/protocols.md Flagship FTP protocol class derived from NetAccess. Includes state machine enum, connection internals, and public API methods. Behavior is driven by ftp:* settings such as PASV/EPSV, FTPS, MODE Z, PRET, TVFS, UTF-8, FXP, and proxy forms. ```cpp class Ftp : public NetAccess { enum automate_state { EOF_STATE, INITIAL_STATE, CONNECTING_STATE, HTTP_PROXY_CONNECTED, CONNECTED_STATE, WAITING_STATE, ACCEPTING_STATE, DATA_OPEN_STATE, CWD_CWD_WAITING_STATE, USER_RESP_WAITING_STATE, DATASOCKET_CONNECTING_STATE, WAITING_150_STATE, WAITING_CCC_SHUTDOWN }; class Connection { int control_sock; SMTaskRef control_recv; SMTaskRef control_send; IOBufferTelnet *telnet_layer_send; DirectedBuffer send_cmd_buffer; int data_sock; ... }; ... public: static void ClassInit(); Ftp(); Ftp(const Ftp *); ~Ftp(); const char *GetProto() const { return "ftp"; } FileAccess *Clone() const { return new Ftp(this); } static FileAccess *New(); int Do(); int Done(); int Read(Buffer *,int); int Write(const void *,int); int StoreStatus(); int Buffered(); ... }; ``` -------------------------------- ### ConnectVerify Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Verifies the connection after establishing it. Ensures the connection is valid and ready for use. ```APIDOC ## ConnectVerify ### Description Verifies the connection after establishing it. Ensures the connection is valid and ready for use. ### Method ConnectVerify ### Parameters None. ### Request Example ```cpp ConnectVerify(); ``` ### Response No return value. ``` -------------------------------- ### xstring class definition (src/xstring.h) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/types.md Main growable string class. Supports printf-style formatting, temporary scratch strings via get_tmp(), and buffer borrowing. Cloning is disabled. ```cpp class xstring : public xstring0 { size_t size; size_t len; void init(); void init(const char *s,int l); void init(const char *s); xstring& operator=(char *); const char *operator=(const char *s) { return set(s); } const char *operator=(const xstring& s) { return set(s); } xstring(const xstring&); // disable cloning public: xstring(); xstring(const char *s); xstring(const char *s,int l); xstring(const xstring_clonable& c); const xstring_clonable& copy() const; void get_space(size_t s); void get_space2(size_t s,size_t g); void shrink_space(); char *add_space(size_t s); void add_commit(int new_len); size_t length() const { return len; } xstring& set(const xstring &s); xstring& set(const char *s); xstring& nset(const char *s,int len); xstring& set_allocated(char *s); xstring& move_here(xstring&); xstring& move_here(xstring_c& s); void swap(xstring& o); xstring& set_substr(int start,size_t sublen,const char *,size_t); xstring& set_substr(int start,size_t sublen,const char *); xstring& set_substr(int start,size_t sublen,const xstring &s); xstring& prepend(const char *s,size_t len); xstring& prepend(const xstring &s); xstring& prepend(char c); xstring& append(const char *s); xstring& append(char c); xstring& append(const char *s,size_t len); xstring& append(const xstring &s); xstring& append_padding(int len,char ch); xstring& vappend(va_list); xstring& vappend(...) ATTRIBUTE_SENTINEL; xstring& vset(...) ATTRIBUTE_SENTINEL; xstring& vsetf(const char *fmt, va_list ap); xstring& setf(const char *fmt,...) PRINTF_LIKE(2,3); xstring& vappendf(const char *fmt, va_list ap); xstring& appendf(const char *fmt,...) PRINTF_LIKE(2,3); static xstring& get_tmp(); static xstring& get_tmp(const char *s); static xstring& get_tmp(const char *s,int n); static char *tmp_buf(int n); static xstring& vformat(const char *fmt,va_list ap); static xstring& format(const char *fmt,...) PRINTF_LIKE(1,2); static xstring& cat(const char *first,...) ATTRIBUTE_SENTINEL; static xstring& join(const char *sep,int n,...); void truncate(); void truncate(size_t n); void truncate_at(char c); void set_length(size_t n); void set_length_no_z(size_t n); char *borrow() { size=len=0; return replace_value(buf,(char*)0); } bool begins_with(const char *o_buf,size_t o_len) const; bool begins_with(const char *s) const; bool ends_with(const char *o_buf,size_t o_len) const; bool ends_with(const char *s) const; ... // find/replace/trim helpers, url_decode, operator[], get(), operator const char* }; ``` -------------------------------- ### FileAccess::Path::ExpandTilde Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Expands a tilde in the path to the home directory. This method is part of the FileAccess::Path nested class and is used to expand user home directory references. ```APIDOC ## FileAccess::Path::ExpandTilde ### Description Expands a tilde in the path to the home directory. This method is part of the FileAccess::Path nested class and is used to expand user home directory references. ### Method ExpandTilde ### Signature void ExpandTilde(const Path &home); ### Parameters - **home** (const Path&) - Required - The home directory path to use for expansion. ### Returns void ``` -------------------------------- ### FileAccess::New Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Creates a new FileAccess instance for the specified protocol, host, and port. This is the entry point for accessing remote files. ```APIDOC ## FileAccess::New ### Description Creates a new FileAccess instance for the specified protocol, host, and port. ### Method Constructor / Factory ### Signature ```cpp static FileAccessRef FileAccess::New(const char *protocol, const char *host, const char *port); ``` ### Parameters - **protocol** (string) - Required - The protocol to use (e.g., "ftp"). - **host** (string) - Required - The hostname or IP address of the server. - **port** (string) - Required - The port number as a string (e.g., "21"). ### Return Value Returns a `FileAccessRef` (smart pointer) to the new FileAccess instance. ### Example ```cpp FileAccessRef fa(FileAccess::New("ftp","example.com","21")); ``` ``` -------------------------------- ### Symlink Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Creates a symbolic link from f1 to f2. ```APIDOC ## Symlink ### Description Creates a symbolic link from f1 to f2. ### Method Symlink ### Parameters - `f1` (const char*) - Required - Source file path. - `f2` (const char*) - Required - Destination file path. ### Request Example ```cpp Symlink("/src", "/dst"); ``` ### Response No return value. ``` -------------------------------- ### ResClient class definition Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/resmgr.md Base class for components that query settings with an automatic prefix and closure. Override ResPrefix() and ResClosure() to customize; Reconfig(name) is called on settings changes. ```cpp class ResClient { static xlist_head list; xlist node; protected: virtual const char *ResPrefix() const { return 0; } virtual const char *ResClosure() const { return 0; } virtual void Reconfig(const char *) {} ResValue Query(const char *name,const char *closure=0) const; bool QueryBool(const char *name,const char *closure=0) const; bool QueryTriBool(const char *name,const char *closure,bool a) const; ResClient(); virtual ~ResClient(); public: static void ReconfigAll(const char *); }; ``` -------------------------------- ### CurrentStatus Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Returns a string describing the current status of the session. ```APIDOC ## CurrentStatus ### Description Returns a string describing the current status of the session. ### Method CurrentStatus ### Parameters None. ### Request Example ```cpp const char* status = CurrentStatus(); ``` ### Response Returns a const char* containing the status description. ``` -------------------------------- ### ResMgr::QueryNext Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/resmgr.md Iterates over resources matching a name pattern. Returns the next resource name and optionally a pointer to the Resource object. ```APIDOC ## ResMgr::QueryNext ### Description Iterates over resources matching a name pattern. Returns the next resource name and optionally a pointer to the Resource object. ### Method Static member function ### Signature ```cpp static const char *QueryNext(const char *name, const char **closure, Resource **ptr); ``` ### Parameters - **name** (const char*) - Required - The resource name pattern to match. - **closure** (const char**) - Required - Pointer to a closure string for iteration state; pass NULL to start. - **ptr** (Resource**) - Optional - Output parameter; if non-NULL, receives a pointer to the Resource object. ### Returns - **const char*** - The next matching resource name, or NULL if no more matches. ``` -------------------------------- ### Command registration API and CMD macro Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/cmd-exec.md Declares the static registration functions and the CMD macro used to define command handlers. A handler reads parsed arguments from parent->args, sets parent->exit_code, and returns a Job* or 0 for built-in work. ```cpp static void RegisterCommand(const char *name,cmd_creator_t creator, const char *short_name=0,const char *long_name=0); static const char *CmdByIndex(int i); #define CMD(name) Job *cmd_##name(CmdExec *parent) typedef Job * (*cmd_creator_t)(class CmdExec *parent); ``` -------------------------------- ### StoreStatus Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Returns the status of the store operation. Pure virtual; must be implemented by subclasses. ```APIDOC ## StoreStatus ### Description Returns the status of the store operation. Pure virtual; must be implemented by subclasses. ### Method StoreStatus ### Parameters None. ### Request Example ```cpp int status = StoreStatus(); ``` ### Response Returns an int representing the store status. ``` -------------------------------- ### NetAccess class declaration (src/NetAccess.h:19) Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/protocols.md Base class for network protocols, deriving from FileAccess and Networker. Adds DNS resolution, per-site connection limits, and rate limiting. The SiteData nested class tracks per-site connection limits. ```cpp class NetAccess : public FileAccess, public Networker { protected: class SiteData { /* per-site connection limit bookkeeping */ }; static xmap_p site_data; SiteData *GetSiteData() const; int GetConnectionLimit(); SMTaskRef resolver; xarray peer; int peer_curr; void ClearPeer(); ... }; ``` -------------------------------- ### Link Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Creates a hard link from f1 to f2. ```APIDOC ## Link ### Description Creates a hard link from f1 to f2. ### Method Link ### Parameters - `f1` (const char*) - Required - Source file path. - `f2` (const char*) - Required - Destination file path. ### Request Example ```cpp Link("/src", "/dst"); ``` ### Response No return value. ``` -------------------------------- ### Open2 Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Performs two-argument operations such as rename, link, symlink, or array-info. ```APIDOC ## Open2 ### Description Performs two-argument operations such as rename, link, symlink, or array-info. ### Method Open2 ### Parameters - `f1` (const char*) - Required - First file path. - `f2` (const char*) - Required - Second file path. - `m` (open_mode) - Required - Operation mode (e.g., LINK, SYMLINK). ### Request Example ```cpp Open2("/src", "/dst", LINK); ``` ### Response No return value. ``` -------------------------------- ### SMTask class definition Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/smtask.md Core abstract task class with pure virtual Do(), static scheduling and blocking helpers, reference counting, and error handling. Subclasses implement Do() returning STALL, MOVED, or WANTDIE. ```cpp class SMTask { virtual int Do() = 0; ... protected: enum { STALL=0, MOVED=1, WANTDIE=2 }; virtual void SuspendInternal() {} virtual void ResumeInternal(); virtual void PrepareToDie() {} bool Deleted() const { return deleting; } virtual ~SMTask(); public: static void Block(int fd,int mask) { block.AddFD(fd,mask); } static void TimeoutU(int us) { block.AddTimeoutU(us); } static void Timeout(int ms) { TimeoutU(1000*ms); } static void TimeoutS(int s) { TimeoutU(1000000*s); } static bool Ready(int fd,int mask) { return block.FDReady(fd,mask); } static void SetNotReady(int fd,int mask) { block.FDSetNotReady(fd,mask); } static TimeDate now; static void UpdateNow() { now.SetToCurrentTime(); } static void Schedule(); static int CollectGarbage(); static void Block(); static time_t last_block; void Suspend(); void Resume(); void SuspendSlave(); void ResumeSlave(); bool IsSuspended() { return suspended|suspended_slave; } virtual const char *GetLogContext() { return 0; } static const char *GetCurrentLogContext() { return current->GetLogContext(); } SMTask(); void DeleteLater(); static void Delete(SMTask *); void IncRefCount() { ref_count++; } void DecRefCount() { if(ref_count>0) ref_count--; } static SMTask *_MakeRef(SMTask *task) { if(task) task->IncRefCount(); return task; } static void _DeleteRef(SMTask *task) { if(task) { task->DecRefCount(); Delete(task); } } static SMTask *_SetRef(SMTask *task,SMTask *new_task); template static T *MakeRef(T *task) { _MakeRef(task); return task; } static int Roll(SMTask *); int Roll() { return Roll(this); } static void RollAll(const TimeInterval &max_time); static SMTask *current; static void Enter(SMTask *task); static void Leave(SMTask *task); void Enter() { Enter(this); } void Leave() { Leave(this); } static int TaskCount(); static void PrintTasks(); static bool NonFatalError(int err); static bool TemporaryNetworkError(int err) { return temporary_network_error(err); } static Error *SysError(int e=errno) { return new Error(e,strerror(e),!NonFatalError(e)); } static void Cleanup(); }; ``` -------------------------------- ### Task lifecycle with references Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/smtask.md Keep a task alive across scheduling slices using SMTaskRef. The loop runs the task with SMTask::Schedule(), checks for errors, and blocks until the next wake-up event. The destructor drops the reference count, and SMTask::Delete fires when the task finishes. ```cpp // internal pattern — keep a task alive across scheduling slices SMTaskRef li(new ListInfo(session, path)); while(!li->Done()) { SMTask::Schedule(); // run the task if(li->Error()) break; SMTask::Block(); // sleep until the next wake-up event } // li destructor drops the count; SMTask::Delete fires when the task finishes ``` -------------------------------- ### Catching and handling Error with IsFatal Source: https://github.com/lavv17/lftp/blob/master/_autodocs/errors.md Shows how consumers test IsFatal() to decide whether to give up or schedule a retry. Non-fatal errors trigger automatic reconnect-and-retry; fatal errors abort the operation. ```cpp Ref e = ...; if(e) { if(e->IsFatal()) /* give up, show e->Text() */; else /* schedule a retry */; } ``` -------------------------------- ### Chdir Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Changes the current working directory. If verify is true, issues STAT and may trigger FILE_MOVED. ```APIDOC ## Chdir ### Description Changes the current working directory. If verify is true, issues STAT and may trigger FILE_MOVED. ### Method Chdir ### Parameters - `dir` (const char*) - Required - Directory path. - `verify` (bool) - Optional - Whether to verify the directory. Default is true. ### Request Example ```cpp Chdir("/remote/dir", true); ``` ### Response No return value. ``` -------------------------------- ### SetFragile Source: https://github.com/lavv17/lftp/blob/master/_autodocs/api-reference/file-access.md Marks the session as fragile, indicating that errors may be more likely. ```APIDOC ## SetFragile ### Description Marks the session as fragile, indicating that errors may be more likely. ### Method SetFragile ### Parameters None. ### Request Example ```cpp SetFragile(); ``` ### Response No return value. ```