diff options
author | jkh <jkh@FreeBSD.org> | 1995-04-25 15:05:11 +0000 |
---|---|---|
committer | jkh <jkh@FreeBSD.org> | 1995-04-25 15:05:11 +0000 |
commit | 02ace706173509b7d8549494277ff682b7cefb8a (patch) | |
tree | 437a6d909f192743fe7d26def0fdfae947754209 /lib/libftp/doc | |
download | FreeBSD-src-02ace706173509b7d8549494277ff682b7cefb8a.zip FreeBSD-src-02ace706173509b7d8549494277ff682b7cefb8a.tar.gz |
A programmatic interface to ftp. I need this for several other
components of the system.
The license is poorly worded, though I have an (email only) release
from the author for unlimited FreeBSD use. I will try to get something
more concrete, though the author's remote location makes this difficult.
Submitted by: Oleg Orel <orel@oea.ihep.su>
Diffstat (limited to 'lib/libftp/doc')
-rw-r--r-- | lib/libftp/doc/Makefile | 2 | ||||
-rw-r--r-- | lib/libftp/doc/example.c | 51 | ||||
-rw-r--r-- | lib/libftp/doc/example.tex | 59 | ||||
-rw-r--r-- | lib/libftp/doc/libftp.tex | 571 | ||||
-rw-r--r-- | lib/libftp/doc/rus.tex | 521 |
5 files changed, 1204 insertions, 0 deletions
diff --git a/lib/libftp/doc/Makefile b/lib/libftp/doc/Makefile new file mode 100644 index 0000000..82fe3e0 --- /dev/null +++ b/lib/libftp/doc/Makefile @@ -0,0 +1,2 @@ +all clean cleandist install: + @echo -n diff --git a/lib/libftp/doc/example.c b/lib/libftp/doc/example.c new file mode 100644 index 0000000..7f09287 --- /dev/null +++ b/lib/libftp/doc/example.c @@ -0,0 +1,51 @@ + +/* Include standard libftp's header */ + +#include <FtpLibrary.h> + + + +main(int argc, char *argv[]) +{ + + FILE *input,*output; + int c; + + + if (argc<3) + exit(fprintf(stderr,"Usage: %s input-file output-file\n",argv[0])); + + FtplibDebug(yes); + + if ((input=Ftpfopen(argv[1],"r"))==NULL) + { + perror(argv[1]); + exit(1); + } + + if ((output=Ftpfopen(argv[2],"w"))==NULL) + { + perror(argv[2]); + exit(1); + } + + while ( (c=getc(input)) != EOF && (putc(c,output)!=EOF) ); + + if (ferror(input)) + { + perror(argv[1]); + exit(1); + } + + if (ferror(output)) + { + perror(argv[1]); + exit(1); + } + + Ftpfclose(input); + Ftpfclose(output); + + exit(0); + +} diff --git a/lib/libftp/doc/example.tex b/lib/libftp/doc/example.tex new file mode 100644 index 0000000..47c4a9d --- /dev/null +++ b/lib/libftp/doc/example.tex @@ -0,0 +1,59 @@ +%% +%% Creator: ansic2latex (from <stdin>) +%% Date: Tue Dec 27 16:14:26 1994 +%% +\expandafter\ifx\csname indentation\endcsname\relax +\newlength{\indentation}\fi +\setlength{\indentation}{0.5em} +\begin{flushleft} +\mbox{}\\ +{\em /$\ast$\hspace*{1\indentation}Include\hspace*{1\indentation}standard\hspace*{1\indentation}libftp's\hspace*{1\indentation}header\hspace*{1\indentation}$\ast$/}\mbox{}\\ +\mbox{}\\ +{\tt\#include} $<${\tt FtpLibrary.h}$>$ \mbox{}\\ +\mbox{}\\ +\mbox{}\\ +main({\bf int\/} argc, {\bf char\/} $\ast$argv[])\mbox{}\\ +\{\mbox{}\\ +\mbox{}\\ +\hspace*{2\indentation}FILE $\ast$input,$\ast$output;\mbox{}\\ +\hspace*{2\indentation}{\bf int\/} c;\mbox{}\\ +\hspace*{2\indentation}\mbox{}\\ +\mbox{}\\ +\hspace*{2\indentation}{\bf if\/} (argc$<$3)\mbox{}\\ +\hspace*{4\indentation}exit(fprintf(stderr,{\tt "Usage: \%s input-file output-file$\backslash$n"},argv[0]));\mbox{}\\ +\mbox{}\\ +\hspace*{2\indentation}FtplibDebug(yes);\mbox{}\\ +\hspace*{2\indentation}\mbox{}\\ +\hspace*{2\indentation}{\bf if\/} ((input=Ftpfopen(argv[1],{\tt "r"}))==NULL)\mbox{}\\ +\hspace*{4\indentation}\{\mbox{}\\ +\hspace*{6\indentation}perror(argv[1]);\mbox{}\\ +\hspace*{6\indentation}exit(1);\mbox{}\\ +\hspace*{4\indentation}\}\mbox{}\\ +\hspace*{2\indentation}\mbox{}\\ +\hspace*{2\indentation}{\bf if\/} ((output=Ftpfopen(argv[2],{\tt "w"}))==NULL)\mbox{}\\ +\hspace*{4\indentation}\{\mbox{}\\ +\hspace*{6\indentation}perror(argv[2]);\mbox{}\\ +\hspace*{6\indentation}exit(1);\mbox{}\\ +\hspace*{4\indentation}\}\mbox{}\\ +\hspace*{2\indentation}\mbox{}\\ +\hspace*{2\indentation}{\bf while\/} ( (c=getc(input)) $\neq$ EOF \&\& (putc(c,output)$\neq$EOF) );\mbox{}\\ +\mbox{}\\ +\hspace*{2\indentation}{\bf if\/} (ferror(input))\mbox{}\\ +\hspace*{4\indentation}\{\mbox{}\\ +\hspace*{6\indentation}perror(argv[1]);\mbox{}\\ +\hspace*{6\indentation}exit(1);\mbox{}\\ +\hspace*{4\indentation}\}\mbox{}\\ +\hspace*{2\indentation}\mbox{}\\ +\hspace*{2\indentation}{\bf if\/} (ferror(output))\mbox{}\\ +\hspace*{4\indentation}\{\mbox{}\\ +\hspace*{6\indentation}perror(argv[1]);\mbox{}\\ +\hspace*{6\indentation}exit(1);\mbox{}\\ +\hspace*{4\indentation}\}\mbox{}\\ +\mbox{}\\ +\hspace*{2\indentation}Ftpfclose(input);\mbox{}\\ +\hspace*{2\indentation}Ftpfclose(output);\mbox{}\\ +\mbox{}\\ +\hspace*{2\indentation}exit(0);\mbox{}\\ +\hspace*{2\indentation}\mbox{}\\ +\}\mbox{}\\ +\end{flushleft} diff --git a/lib/libftp/doc/libftp.tex b/lib/libftp/doc/libftp.tex new file mode 100644 index 0000000..f7d14e8 --- /dev/null +++ b/lib/libftp/doc/libftp.tex @@ -0,0 +1,571 @@ +\documentstyle[cxx,fancyheadings,twoside,epsf,indentfirst]{article} +% Vertical sizes +%\vsize=20cm +%\voffset=-2.3cm +%\topmargin=0cm +%\headheight=0.9cm +%\footskip=1cm +%\footheight=0.9cm +%\textheight=16cm +%\headrulewidth 0.01cm +%\footrulewidth 0.0cm +% 0 sizes +%\hsize=30cm +%\hoffset=-4.3cm +%\hoffset=-2.3cm +%\textwidth=13cm +% Modes +% \special{landscape} +\pagestyle{empty} +\pagestyle{fancyplain} +\newcommand{\tit}[1]{#1} +\rhead[\fancyplain{}{\tit{\leftmark}}]{\fancyplain{}{\tit{\rightmark}}} +\lhead[\fancyplain{}{\tit{\rightmark}}]{\fancyplain{}{\tit{\leftmark}}} +\chead{\hfill} +\lfoot[\fancyplain{}{\tit{\thepage}}]{\fancyplain{}{\hfill}} +\rfoot[\fancyplain{}{\hfill}]{\fancyplain{}{\tit{\thepage}}} +\cfoot{\hfill} +\renewcommand{\sectionmark}[1]{\markboth{#1}{\ }} +\renewcommand{\subsectionmark}[1]{\markright{\ }} +\newcommand{\look}[1]{(Chapter~\ref{#1}, page~\pageref{#1})} +\newcommand{\toindex}[1]{\underline{\bf#1}\index{#1}} +\newcommand{\add}[1]{\symbol{64}} +\newcommand{\ps}[1]{\symbol{37}s} +\newcommand{\twcol}[4]{ +\noindent\parbox[t]{#1\textwidth}{#3} \hfill \parbox[t]{#2\textwidth}{#4\hfill}\\ +} +\newcommand{\tc}[2]{\twcol{0.49}{0.49}{#1}{#2}} +\newcommand{\tcc}[2]{\twcol{0.49}{0.49}{\toindex{#1}}{#2}} +\newcommand{\ttt}[2]{\bigskip + +{\bf#1} + +#2} +\newcommand{\ts}[1]{{\underline{\bf#1}}} +\newcommand{\dl}[2]{\parbox[t]{0.4\textwidth}{#1\hfill}\hfill + \parbox[t]{0.4\textwidth}{#2\hfill}} +\makeindex +\begin{document} +\title{\bf\it{LIBFTP User's guide}} +\author{Oleg Orel} +\date{\today} +\newpage +\maketitle + +\section*{License} + +This library is designed for free, non-commercial software creation. +It is changeable and can be improved. The author would greatly appreciate +any advises, new components and patches of the existing programs. +Commercial usage is also possible with participation of it's author. + +\section*{Introduction} + +The basic orientation of this library is making user's programs which transport +files via TCP/IP network. It contains set of functions, +starting from primitive, such as opening FTP connection to the server, +and finishing by high-level functions, such as functions which retrieve files + via network, making and closing channels to the server. All functions have +prototypes in common header file named \toindex{FtpLibrary.h}, +which must be +available in standard headers directory +\footnote{for example ``/usr/include''}. +Those prototypes almost fully +describe orientation and arguments of all functions, +but common ideology and library components should be mentioned. + +This library is a client and uses standard FTPD from the other side. + +There are problems of errors processing in many operating systems including input/output errors. +The mutual mechanism of value returning of all functions is used in this library. +(EXIT macros, defined in file FtpLibrary.h). This mechanism allows, + after the definition of the error processing functions, write programs, +considering the conditions to be ideal. +Data transfer functions have possibility to preset data stream +expectation timeout. +When the set time expires, previously set function will be called. + +\section{Variables and definitions} + +\subsection{Some definitions in libftp's header file (FtpLibrary.h)} + +\ttt{\toindex{EXIT}}{Main macro for return value from library's functions with +calling handlers if it's need} + +\ttt{\toindex{MAX\_ANSWERS}}{Number of possible answers from FTPD for one request} + +\ttt{\toindex{NFDS}}{Maximum numbers of one-time opened files in your system, if this +value higher than need isn't important. } + +\ttt{\toindex{FTPBUFSIZE}}{Size of block for transmit data via network. By default equivalence \toindex{BUSIZ}} + +\ttt{\toindex{LQUIT}}{Error status of local functions. If you give this status from libftp's function you must use perror for expand diagnostic.} + +\ttt{\toindex{QUIT}}{Error status of network operation. Use perror.} + +\ttt{\toindex{Ctrl}(char)}{Return control character code} + +\ttt{\toindex{FREE}(data)}{Full data by zero} + +\ttt{\toindex{FtpError}(libftp's call)}{Special macro for diagnostic bad conditions} + +\ttt{\toindex{FtpAssert}(libftp's call}{Special macro for automatically return from +this function if status is bad} + +\subsection{Libftp's file specification} + +All files wich must be interprets as local interprets as libftp's files. +Libftp responds to three types of files such + as local file, ftp files and program +pipes. All files can be described as next syntax: + +\ttt{$\mid$string}{interprets string as shell command, which must be + executed with appropriate input/output for file. It depends where + this file is specified.} + +\ttt{hostname:filename}{interprets as file, which must be taken + using ftp protocol with anonymous access} + +\ttt{user@hostname:filename\\ +user/pass@hostname:filename +}{interprets as file accesses via ftp + with password yourname@your\_host.your\_domain} + + +\ttt{*STDIN*, *STDOUT*, *STDERR* or char '-'}{opened standard streams} + +\ttt{anything else}{local file} + + + + +\subsection{The FTP data structure} + +\subsubsection{The members of FTP structure} + +\tc{FILE *\toindex{sock}\footnote{You can use macro FTPCMD(ftp) for extract +this members, using this macro for making your program more compatibility +with next versions of this library}} +{--- command channel to the server;} + +\tc{FILE *\toindex{data}\footnote{You can use macro FTPDATA(ftp) for extract +this members, using this macro for making your program more compatibility +with next versions of this library}} +{--- pointer to data structure, which describes data channel to the server;} + +\tc{int \toindex{errno}}{ --- last returned value. When value is lower than 1, an error occurred;} + +\tc{char \toindex{mode}}{--- type of transfer (valid values: 'A' 'I' ....);} + +\tc{int \toindex{ch}}{--- help variable. Is used to convert ASCII files, user of library for cleaning your problems must forget about this member;} + +\tc{STATUS (*\toindex{error})()}{--- pointer to an error handler. It is called + when status from the server is bad;} +\tc{STATUS (*\toindex{debug})()}{--- pointer to a debug handler. Is called from + functions of sending/receiving messages to/from server;} + +\tc{STATUS (*\toindex{IO})()}{--- pointer to Input/Output error handler. Is called when channel to server is broken.} + +\tc{STATUS (*\toindex{hash})()}{--- pointer to function, which must compute +summary traffic. This function can take one argument which describe + how many bytes +now received of sended to/from server. If the argument is equivalence +to zero, then counter must be reset to zero. But of course user can use +this handler for another properties of herself program, for example for +perriodicaly called anything else for checking other conditions, because +the transfer procedure can take large time from user's program.} + +\tc{int \toindex{seek}}{--- the first byte in file for transfer. This option +can use for retransfer file again after connection is broken} + +\tc{int \toindex{flags}}{--- the option list for transfer procedures such as: +\\ +\begin{itemize} +\item[FTP\_REST] Turn on retransfer file using method of compare size of files +in both sides. +\item[FTP\_NOEXIT] Don't exit from standard error and IO handlers +\end{itemize}} + +\tc{struct timeval \toindex{timeout}}{--- Timeout for send/receive procedures} + +\tc{int \toindex{port}}{--- Port for making command connection} + +\tc{String \toindex{title}}{--- Connection identification} + +\tc{unsigned long \toindex{counter}}{--- counter of already transferred bytes} + +\subsubsection{Initialization of FTP structure} + +This library have two special objects: procedure FtpCreateObject and external +static structure FtpInit. The procedure FtpCreateObject called from +FtpConnect. The structure FtpInit can be modified by hand or by using special +macros such as \toindex{FtpSetFlag}, \toindex{FtpClearFlag}, \toindex{FtpSetPort}, \toindex{FtpSetTimeout}, \toindex{FtpSetErrorHandler}, \toindex{FtpSetDebugHandler}, \toindex{FtpSetIOHandler}, \\ +\toindex{FtpSetHashHandler}. + +\subsection{The \toindex{ARCHIE} data structure} + +The \ts{ARCHIE} data structure using only with function FtpArchie for extract +result of works one. This structure have four members such as: + +\tc{struct tm \toindex{createtime}}{Time of file creation.} + +\tc{unsigned long \toindex{size}}{size of file.} + +\tc{String \toindex{host}}{Host which file is located} + +\tc{String \toindex{file}}{Full path in pointed host of this file} + + +\section{Library's routines} + +\subsection{Connection/Disconnection with server} + +\ttt{STATUS \toindex{FtpConnect}(FTP~**, char~*hostname +\footnote{The name of the host may be symbolic (for example \ts{dxcern.cern.ch}) or numeric (for example \ts{128.141.201.96})} +)} +{ + Makes channel to the server, at the ``hostname'' machine. + Creates FTP data structure and returns pointer to it. If the procedure \toindex{FtplibDebug}(1) +was previously called, \ts{FtpConnect} calls automatically \ts{FtpDebug} for the \ts{debug mode} to be turned on. + \look{debug}. +} +\ttt{STATUS \toindex{FtpUser}(FTP~*, char~*user)} +{ + Sends the name of the user to the server. The connection must be done before it. +} + +\ttt{STATUS \toindex{FtpPassword}(FTP~*, char~*password)} +{ + Sends \ts{password} to the server. The function \ts{FtpUser} must be called before it. +} + +\ttt{STATUS \toindex{FtpAccount}(FTP~*, char~*account)} +{ + Sends a name of the account to the server. The name of the account is not standard + attribute for many systems, so this function is used very seldom. + The function \ts{FtpPassword} must be called before it. +} + +\ttt{ +STATUS \toindex{FtpLogin}(FTP~**, char~*hostname, char~*user, char~*password, char~*account)} +{ + Executes functions \ts{FtpConnect}, \ts{FtpUser}, \ts{FtpPassword}, + \ts{FtpAccount} (if necessary) consistently. If the name of the account is absent, + replaces it with the \ts{NULL} value. +} + +\ttt{STATUS \toindex{FtpBye}(FTP~*)} +{ Finishes work with the server and closes all channels. +\footnote{You can see from the description of connect/disconnect functions, that you can create +more than one connection to servers simultaneously.} +} + +\ttt{STATUS \toindex{FtpQuickBye}(FTP~*)} +{ Fast close data and command connection to server without delays for waiting +server's confirmation and destroying the FTP object. +} + +\ttt{STATUS \toindex{FtpAbort}(FTP~*)} +{ Abort last command passed to server} + + +\subsection{The debugging} \label{debug} + +There is a possibility to predefine few functions, +such as:~\footnote{If the \ts{NULL} value is transferred as a parameter \ts{``function''} to the functions, described below, +the handling will be turned off.} + +\ttt{\toindex{FtpSetDebugHandler}(FTP *,function)} +{ Predefines function of protocol debugging. + After the function is predefined, it is called with every + sending/receiving messages from the server. + The function, defined as a debug handler must do returns to the calling +functions (\ts{FtpSendMessage}/\ts{FtpGetMessage}), but can also abort the program. + +} + +\ttt{\toindex{FtpSetErrorHandler}(FTP *,function)} +{ + Predefines error handler. If the server's answer means, that the operation is not finished + correctly, this function will be called. + The result code is negative, if an error is occurs. +} +\ttt{\toindex{FtpSetIOHandler}(FTP *,function)} +{ + Predefines handler of Input/Output processing. This function is called, when a connection to the + server is broken. For example, when the network or the remote host is down. This handler also is + called after the \toindex{timeout} of one character waiting expires. +} + +\ttt{\toindex{FtpDebug}(FTP *)} +{ +Turns on all standard debugging functions. + +\tc{\toindex{FtpDebugError}}{--- prints a string, taken from the server, and aborts the program;} +\tc{\toindex{FtpDebugDebug}}{--- prints a string, taken from the server;} +\tc{\toindex{FtpDebugIO}}{--- prints string \ts{strerror(errno)} and aborts the program.} +} + +\ttt{\toindex{FtpSetHashHandler}(FTP *,function)} +{ + Predefines handler of function which must compute traffic size. This +function have only one argument which describe number of transferred bytes. +If this argument is zero counter must be reset to zero. +} + + +All function for debugging have three arguments:\\ +1. Pointer to FTP data structure;\\ +2. Last returned value from the server. When errors occur, the value is less than 1;\\ +3. Diagnostic string.(char *) + +\ttt{\toindex{FtplibDebug}(yes|no)} +{ Turns on/off autostart debug mode, when connection is established. +} + +\ttt{\toindex{FtpLog}(char *name\_of\_log, char *message)} +{ Print message to user's screen in libftp's standard format, + name\_of\_log must be your program name (if this function called +from standard handlers then this string is title from FTP structure) and +message with diagnostic string from anywhere.} + + +\subsection{Data transfer procedures} + +\ttt{STATUS \toindex{FtpRetr}(FTP~*, char~*command, char~*inp, char~*out)} +{ + This is basically and single procedure in the library with transfer + file from the server. One check many option with customizing its style + of working. This options basically is members of FTP structure such + as timeout, all handlers, mode, seek. If in continue of working this + function happen timeout or network broked then this function + automatically called I/O handler which can restart this function + again or broken procedure. If handler is not set then FtpRetr return + status QUIT or LQUIT as signal of type of error (LQUIT is specify + error happen with local filesystem). \\ + {\bf Warring!} All receive function described bellow working by + called this procedure and described rules is right for them. +} + +\ttt{\toindex{FtpGet}(FTP~*, char~*in, char~*out)} +{ + Calls \ts{FtpRetr} with adaptation arguments to transfer file +} + +\ttt{\toindex{FtpDirectory}(FTP~*, char~*pat\footnote{This is the first argument for \ts{``ls''} command}, char~*out)} +{ + Transfers files listing from the server, described by \ts{pat}, to the local file \ts{out}. +} + +\ttt{\toindex{FtpDir}(FTP~*, char~*out)} +{ + Transfers files listing of the current directory from the server to the local file \ts{out}. +} + +\ttt{\toindex{FtpStor}(FTP~*, char~*command, char~*inp, char*~out)} +{ + Store file to the server. Works like FtpRetr. +} + +\ttt{\toindex{FtpPut}(FTP~*, char~*in, char~*out)} +{ + Calls \ts{FtpStor} adaptation arguments to transfer file +} + +\ttt{\toindex{FtpCopy}(FTP~*ftp\_from, FTP~*ftp\_to, char~*in, char~*out)} +{ + Transfer file between two server without connection to client's host +} + +\ttt{\toindex{FtpPassiveTransfer}(FTP~*ftp\_from, FTP~*ftp\_to, char~*in, char~*out)} +{ + Transfer file between two server via client's cache. +} + +\subsection{Server's files read/write procedures} + +This library contains special functions for remote files reading and +writing, without precopying them to local files. The functions, +which are described below, do it. After the data channel +to a remote file is created, it becomes possible to read and write + characters using standard Input/Output functions +or using special functions \ts{FtpRead}/\ts{FtpWrite} and/or +\ts{FtpGetc}/\ts{FtpPutc}, which reorganize stream for standard text file, +under condition that the \ts{ASCII} mode is set. +\footnote{Of course, such functions as \ts{seek}, \ts{ioctl}, .... +can not be used.} + +\ttt{\toindex{FtpData}(FTP~*, char~*command, char~*param, char~*mode)} +{ Makes data transfer channel, with presending command composed from \ts{command} and \ts{param}. +The mode must be \ts{``r''} or \ts{``w''}} + +\ttt{\toindex{FtpOpenRead}(FTP~*,char~*filename)} +{ Opens file named \ts{filename} for reading on server} + +\ttt{\toindex{FtpOpenWrite}(FTP~*,char~*filename)} +{ Creats and opens file named \ts{filename} for writing on server} + +\ttt{\toindex{FtpOpenAppend}(FTP~*,char~*filename)} +{ Creats and opens file named \ts{filename} for appending on server} + +\ttt{\toindex{FtpOpenDir}(FTP~*, char~*files)} +{ + Creats channel for directory list reading, described by argument \ts{files}. +} + +\ttt{STATUS \toindex{FtpRead}(FTP~*)}{ +Reads character from data stream. If \ts{ASCII} mode is set\footnote{By default} converts new line markers. +When the end of file is detected or channel is broken, returns \toindex{EOF}} + +\ttt{\toindex{FtpWrite}(FTP~*, char~c)}{ +Writes single character to stream, if \ts{ASCII} mode is set converts new line markers. +When channel is broken, returns \toindex{EOF}} + +\ttt{int \toindex{FtpGetc}(FTP~*,FILE~*fp)}{ +Reads character from data stream specified by fp. Using macros FTPDATA and FTPCMD you can specify stream need for reading. \footnote{Functions FtpGetc and FtpPutc ignories data stream mode, works as binary always} +} + +\ttt{STATUS \toindex{FtpPutc}(FTP~*,FILE~*fp, char c)}{ +Writes character to data stream specified by fp. Using macros FTPDATA and +FTPCMD you can specify stream need for reading. \footnote{Functions +FtpGetc and FtpPutc ignores data stream mode, works as binary always} +} + + +\ttt{\toindex{FtpClose}(FTP~*)} +{Closes opened channel to server} + +\subsection{Other commands for server} + +\ttt{\toindex{FtpCommand}(FTP~*, char~*command, char~*param, int~ok1, ok2, ok3, ..., okN, EOF)} +{ Sends a command, composed from \ts{command} and \ts{param} using \ts{sprintf} function. +Reads an answer from the server. +When return code from the server is not included to \ts{ok-list}(\ts{ok1},\ts{ok2}...) the sign of code +will be inverted.} + + +\ttt{\toindex{FtpType}(FTP~*,char~mode)} +{Sets transfer mode, such as \ts{'A'},\ts{'I'},\ts{'S'},etc...} + +\ttt{\toindex{FtpBinary}(FTP~*)} +{Sets binary mode} + +\ttt{\toindex{FtpAscii}(FTP~*)} +{Sets \ts{ASCII} mode} + + +\ttt{\toindex{FtpMkdir}(FTP~*,char *dirname)} +{Makes directory on server} + +\ttt{\toindex{FtpChdir}(FTP~*,char *dirname)} +{Changes working directory on server} + +\ttt{\toindex{FtpRm}(FTP~*,char *filename)} +{Removes file on server} + +\ttt{char~*\toindex{FtpPwd}(FTP~*)} +{Returns the name of working directory on server} + +\ttt{int \toindex{FtpSize}(FTP~*,char *filename)} +{Returned size (in bytes) of description's file.} + +\ttt{\toindex{FtpMove}(FTP~*,char *oldfilename, char *newfilename)} +{Renames file from \ts{oldfilename} to \ts{newfilename}} + +\ttt{\toindex{FtpPort}(FTP~*, int~a, int~b, int~c, int~d, int~e, int~f) +\footnote{Recommended in non-trivial situations} +} +{ A command for the server for making a new data channel. \ts{a.b.c.d} is an IP address of a client(i.e. your IP address), +\ts{e*256+f} is a port number} + + +\ttt{struct hostent *\toindex{FtpGetHost}(char *hostname) +\footnote{Extension of standard function ``gethostbyname''} +} +{Returned pointer to structure \ts{hostent} creating using string +\ts{hostname}, which contains name of the computer or its IP +address~\footnote{For example''dxunk8.oea.ihep.su'' or ``192.102.229.71''} +} + + +\subsection{Functions for sending/receiving control messages to/from server} + +\ttt{\toindex{FtpSendMessage}(FTP~*, char~*message)} +{Sends a message to the server} + +\ttt{int \toindex{FtpGetMessage}(FTP~*)} +{Receives a message from the server.} + +\ttt{\toindex{FtpMessage}(int Number)} +{Gets a message by code.} + +\ttt{\toindex{FtpNumber}(char *Message)} +{Extract message's number from string.} + +\subsection{High-level functions} + +\ttt{FILE *\toindex{FtpFullOpen}(char *filename,char *mode)} +{ +Parses string \ts{filename}, which must contain a string in format or \\ +\ts{host/user/password:filename} or \ts{filename}, +what corresponds to remote or local file. The second argument is the type of opening, divided into two characters: +first --- the mode of opening \ts{``r''}, \ts{``w''} or \ts{``a''}, second is the transfer type , if contains character \ts{``b''}, + then the mode is binary. +} + +\ttt{STATUS \toindex{FtpFullSyntax}(String source,String host,String user,String password,String file)} +{Make out string ``source'' for next four parameters.} + +\ttt{FILE *\toindex{Ftpfopen}(char *file, char *mode)} +{ + Open file specified in libftp's file specification. Works like + \ts{fopen}. See description of libftp's file specification in the + top of paper. +} + +\ttt{STATUS \toindex{Ftpfclose}(FILE *fp)} +{ + Close file which opened using Ftpfopen. Works like fclose. +} + +\ttt{STATUS \toindex{FtpArchie}(char *what, ARCHIE *result, int number)}{ +Find \ts{number} entrys in archie's database enrolls described by \ts{what} +argument. \ts{result} must be pointer to array of ARCHIE's structures number +of which must be equivalence or higher than \ts{number}. This call return +number of entrys which found in database. If FtpArchie return value lower +than zero then pointed target not found or archie isn't works} + + +\section{Example of using libftp} + +Next example demonstrate very simple using library calls only Ftpfopen +and Ftpfclose functions which discriminate libftp's file specification: + +\input example + +For tests works this program you can try run one as: + +\bigskip + +\% example username/password@hostname:filename myfile.out + +\% example myfile.input username/password@hostname:filename.out + + +\newpage +\input libftp.ind +\newpage +\tableofcontents +\end{document} + + + + + + + + + + + + diff --git a/lib/libftp/doc/rus.tex b/lib/libftp/doc/rus.tex new file mode 100644 index 0000000..2361c11 --- /dev/null +++ b/lib/libftp/doc/rus.tex @@ -0,0 +1,521 @@ +\documentstyle[russian,fancyheadings,twoside,epsf,indentfirst]{article} +% Vertical sizes +%\vsize=20cm +%\voffset=-2.3cm +%\topmargin=0cm +%\headheight=0.9cm +%\footskip=1cm +%\footheight=0.9cm +%\textheight=16cm +%\headrulewidth 0.01cm +%\footrulewidth 0.0cm +% horisontal sizes +%\hsize=30cm +%\hoffset=-4.3cm +%\hoffset=-2.3cm +%\textwidth=13cm +% Modes +% \special{landscape} +\pagestyle{empty} +\pagestyle{fancyplain} +\newcommand{\tit}[1]{#1} +\rhead[\fancyplain{}{\tit{\leftmark}}]{\fancyplain{}{\tit{\rightmark}}} +\lhead[\fancyplain{}{\tit{\rightmark}}]{\fancyplain{}{\tit{\leftmark}}} +\chead{\hfill} +\lfoot[\fancyplain{}{\tit{\thepage}}]{\fancyplain{}{\hfill}} +\rfoot[\fancyplain{}{\hfill}]{\fancyplain{}{\tit{\thepage}}} +\cfoot{\hfill} +\renewcommand{\sectionmark}[1]{\markboth{#1}{\ }} +\renewcommand{\subsectionmark}[1]{\markright{\ }} +\newcommand{\look}[1]{(Глава~\ref{#1}, стр.~\pageref{#1})} +\newcommand{\toindex}[1]{\underline{\bf#1}\index{#1}} +\newcommand{\add}[1]{\symbol{64}} +\newcommand{\ps}[1]{\symbol{37}s} +\newcommand{\twcol}[4]{ +\noindent\parbox[t]{#1\textwidth}{#3} \hfill \parbox[t]{#2\textwidth}{#4\hfill}\\ +} +\newcommand{\tc}[2]{\twcol{0.49}{0.49}{#1}{#2}} +\newcommand{\tcc}[2]{\twcol{0.49}{0.49}{\toindex{#1}}{#2}} +\newcommand{\ttt}[2]{\bigskip + +{\bf#1} + +#2} +\newcommand{\ts}[1]{{\bf#1}} +\newcommand{\dl}[2]{\parbox[t]{0.4\textwidth}{#1\hfill}\hfill + \parbox[t]{0.4\textwidth}{#2\hfill}} +\makeindex +\begin{document} +\title{\bf\it РУКОВОДСТВО ПОЛЬЗОВАТЕЛЯ БИБЛИОТЕКИ "LIBFTP"} +\author{Олег Орел} +\date{\today} +\newpage +\maketitle + +\section*{Лицензия} + +Продукт предназначен для написания свободного некоммерческого программного +обеспечения. Он может исправляться и дописываться. +Автор будет благодарен за получение советов, новых компонент и правок +существующих подпрограмм. + +Коммерческое использование этой библиотеки возможно с привлечением +е\"е автора. + +\section*{Причины создания и история развития} + +Для людей, которые хотя бы один раз писали программу с использованием +системных вызовов типа socket, connect, bind.... не секрет, что почти всегда +последовательность вызовов функций для создания соединения по протоколу TCP одна и та же. Отсюда возникает резонный +вопрос ``А почему собственно не иметь библиотеки более высокого +уровня, для упрощения процесса программирования?''. +Это послужило причиной создания \ts{libftp}. + +После реализации ``нижней'' части библиотеки, были созданы +функции более высокого уровня, такие как +передача целого файла или чтение списка файлов. При написании +этих процедур возникла необходимость удобной отладки сбойных случаев, +для освобождения программы от бесконечного числа условий +(обработка возвращаемого +библиотечными функциями статуса). +Для этого был создан макрос \ts{EXIT}, который при возврате функциями статуса, +проверяет его, и в случае необходимости вызывает заранее установленные +функции. + +При передачи файлов по сети, которая в основном состоит из dialup-slip'ов +(типичная ситуация для exUSSR) +часто возникают ситуации ``поломки сети'' и файл большого размера передать +становится практически невозможно\footnote{Конечно можно периодически +запускать ftp, и говорить в нем ``reget filename''}, это послужило причиной +написания программы \toindex{ftptry}\footnote{Программа \ts{ftptry} будет описана ниже} с использованием библиотеки libftp. +Для е\"е реализации в библиотеку были добавлены функции +\toindex{FtpRestorTimeout} и \toindex{FtpReretrTimeout}, +которые в отличии от функций \ts{FtpStorTimeout} и \ts{FtpRetrTimeout} +не передают а докачивают файлы. + +\section*{Недостатки - для исправления в следующих версиях} + +\begin{itemize} + +\item В процедурах чтения потока из socket'ов используется механизмы +setjmp-longjmp, alarm+SIGALRM, SIGIO, которые будут заменены на select. +Этот недостаток (использование SIGALRM) проявляется при работе с X11 +\footnote{там тоже используется alarm} + +\item Переменная FtpDataStart\footnote{С какого байта передавать файлы} не принадлежит структуре FTP, а является обшей для всех. + +\item Отсутствие работы с \toindex{site-specific} ftpd командами +\end{itemize} + +\section*{Идеи для дальнейших реализации} + +\begin{itemize} + +\item Разработка программы дублирования дерева +директорий одной машины на другую. \footnote{Разработка идет в данный момент} + +\item Разработка интерфейса в окружении X-window's для манипуляции +файлами находящихся на разных машинах с возможностью неинтерактивной передачи +(для медленных сетей) + +\item Создание мультиплексирующего аппарата для одновременной +обработки нескольких потоков данных. + +\item Создание объекта FTP для C++ + +\end{itemize} + +\section*{Введение} + +Библиотека ``libftp'' предназначена для написания прикладных программ в которых +существует необходимость передавать файлы по сети TCP/IP. Oна +является набором функций начиная от примитивных функций, таких как открытие соединения по протоколу FTP на удаленную машину, до функций высокого уровня, которые передают +файлы сами производя соединение/разъединение с сервером. +Все функции имеют прототипы в файле \toindex{FtpLibrary.h}, +который должен быть помещен +в каталог стандартных заголовков\footnote{Например /usr/include}. +Эти прототипы практически полностью описывают +назначение функций и их аргументы, но тем не менее необходимо сказать об общей идеологии +построения библиотеки и ее компонент. + +Вся библиотека, являясь клиентом, использует +с противоположной стороны соединения стандартный \toindex{FTPD} +\footnote{Для работы функций FtpRertrTimeout, FtpRestorTimeout необходимо +чтобы сервер отрабатывал команду REST}. + +Во многих операционных системах существует проблема обработки +разного рода ошибок, в том числе ошибок +ввода/вывода, в данном инструментарии использован единый механизм возврата +результата работы любой функции (макрокоманда \ts{EXIT}, определенная в \ts{FtpLibrary.h}) +который позволяет +предварительно установив свои или стандартные функции обработки +ошибок и функции +отладки, писать смысловую часть программы, думая только о ее методе работы +в идеальных условиях. В функциях передачи данных в обе стороны существует +возможность установить максимальное время ожидания потока данных, по истечении которого, возможно вызвать определенную процедуру. + + +При работе с библиотекой, первой всегда вызывается процедура +соединения с сервером\footnote{За исключением FtplibDebug} (\ts{FtpLogin} или \ts{FtpConnect}) +которая возвращает указатель на вновь созданную структуру данных (типа \ts{FTP}) +о соединении с сервером. + + + + +\section{Структура данных FTP} + + +\tc{int \toindex{sock}}{--- дескриптор канала передачи команд на сервер;} +\tc{FILE *\toindex{data}}{--- описание канала для передачи данных на сервер;} +\tc{int \toindex{errno}}{ --- значение последнего возвращенного библиотекой значения. + В случае если оно отрицательно или равно нулю, + то произошла ошибка;} +\tc{char \toindex{mode}}{--- тип передачи данных;} +\tc{int ch}{--- вспомогательная переменная используемая для преобразования + потока в режиме передачи текстовых файлов;} +\tc{STATUS (*func)()}{--- адрес функции, которая вызывается в случае когда от сервера + получен ответ об ошибке;} +\tc{STATUS (*debug)()}{--- адрес функции, которая вызывается для отладки протокола;} +\tc{STATUS (*IO)()}{--- функция вызываемая в случае потери связи с сервером, или + по истечению максимального времени на прием/передачу одного + символа.} + + +\section{ Процедуры соединения/разъединения с сервером} + +\ttt{STATUS \toindex{FtpConnect}(FTP~**, char~*hostname +\footnote{Имя машины может быть как символьное так и цифровое, например +\ts{dxcern.cern.ch} или \ts{128.141.201.96}} +)} +{ + Создает канал соединения с сервером, находящимся на машине hostname, + и создает структуру FTP, возвращая на нее указатель. Если предварительно + была выполнена процедура \toindex{FtplibDebug}(1), + то до соединения с сервером включает стандартные + подпрограммы обработки ошибок \toindex{FtpDebugDebug}, \toindex{FtpDebugError}, + \toindex{FtpDebugIO} \look{debug}. +} +\ttt{STATUS \toindex{FtpUser}(FTP~*, char~*user)} +{ + Посылает серверу имя пользователя. Ранее должно было быть произведено соединение +} + +\ttt{STATUS \toindex{FtpPassword}(FTP~*, char~*password)} +{ + Посылает серверу пароль. Ранее должна была быть выполнена процедура \ts{FtpUser} +}\ttt{STATUS \toindex{FtpAccount}(FTP~*, char~*acct)} +{ + Посылает серверу имя account'a Эта функция сделана для полного соответствия + библиотеки протоколу \ts{FTP}, но т.к. мало таких операционных систем в которых необходим этот + атрибут пользователя то функция \ts{FtpAccount} в общем то не нужна. + Предварительно должна была быть выполнена процедура + \ts{FtpUser}. +} + +\ttt{ +STATUS \toindex{FtpLogin}(FTP~**, char~*hostname, char~*user, char~*password, char~*account)} +{ + Последовательно выполняет процедуры \ts{FtpConnect}, \ts{FtpUser}, \ts{FtpPassword}, \ts{FtpAccount} +(если параметр account равен NULL, то процедура FtpAccount не вызывается)} + +\ttt{STATUS \toindex{FtpBye}(FTP~*)} +{ Завершает сеанс работы с сервером \footnote{Как видно из описания процедур соединения/разъединения из одной программы можно одновременно соединятся с несколькими серверами} } + + + + +\section{Процедуры отладки программы} \label{debug} + +Существует возможность предварительно определить три +процедуры:~\footnote{Если в любую из функций, описанных ниже, вместо параметра function передать значение \ts{NULL}, то это будет означать +отключение отладки. При отключенной отладке результат работы можно +определить или же по возвращаемому функцией значению (Если она типа \toindex{STATUS}) или +по переменной errno в структуре \ts{FTP}} + +\ttt{\toindex{FtpSetDebugHandler}(FTP *,function)} +{ Устанавливает процедуру отладки протокола с удаленным сервером. + Если ее определить, то она всегда будет вызывается из стандартной функции + приема/передачи сообщения с/на сервера. Должна делать возврат, но в принципе + имеет полное право прерывать выполнение программы в случае необходимости. +} + +\ttt{\toindex{FtpSetErrorHandler}(FTP *,function)} +{ + Определяет функцию обработки ошибок. + После ее определения, в случае возвращения сервером + неудовлетворительного ответа, будет вызываться указанная функция. + При этом знак у кода ошибки меняется на '-', и т.о. результат + становится меньше нуля. +} +\ttt{\toindex{FtpSetIOHandler}(FTP *,function)} +{ + Определение функции обработки ошибок ввода/вывода. + При передаче данных или команд на сервер, может возникнуть ситуация когда + связь с сервером будет потеряна (сюда входят практически все сбои сети + и сбои при работе сервера на удаленной машине) при этом будет вызвана + указанная функция. Она вызывается так же по истечению + максимального времени при ожидании очередного символа с сервера во время + передачи данных. (\toindex{timeout}) +} + +\ttt{\toindex{FtpDebug}(FTP *)} +{ +Подключение стандартных функций отладки протокола таких как +\tc{\toindex{FtpDebugError}}{--- печатает строку возвращенную сервером и прерывает программу;} +\tc{\toindex{FtpDebugDebug}}{--- печатает строку возвращенную сервером;} +\tc{\toindex{FtpDebugIO}}{--- печатает строку \ts{strerror(errno)} и прерывает программу.} +} + +Во все процедуры передаются три аргумента:\\ +1. Структура \ts{FTP};\\ +2. Значение возвращенное функцией, если оно меньше единицы то произошла ошибка;\\ +3. Символьное сообщение об ошибке (char *). + +\ttt{\toindex{FtplibDebug}(\ts{on} or \ts{off})} +{ Включает/выключает автоматическое включение всех видов отладки при + выполнении функции \ts{FtpConnect(FtpLogin)}} +\section{Процедуры передачи данных с сервера} + +\ttt{STATUS \toindex{FtpRetrTimeout}(FTP~*, char~*command, char~*inp, char~*out +\footnote{Если имя локального файла \ts{out} совпадет со строками \ts{*STDIN*}, \ts{*STDOUT*}, \ts{*STDERR*} то +вместо открытия нового файла произойдет дублирование потока соответственно с каналами +\ts{stdin}, \ts{stdout}, \ts{stderr} (Обработку данной спецификации файлов +производит функция \toindex{Ftpfopen}, которая при необходимости может быть вызвана самостоятельно, с такими же аргументами, как системная функция fopen)}, + long~time)} +{ + Посылает команду \ts{command} на сервер, причем если в команде + встретится подстрока \ps, то на ее место будет подставлена строка \ts{inp}. + Создает канал для передачи данных, и то что будет передано + сервером в этот канал будет скопировано в локальный файл \ts{out}. + Если в течении времени \ts{time}(в секундах) + с сервера не придет не одного символа, то + функция возвратит статус который будет означать ошибку ввода/вывода. + В случае когда \toindex{timeout}=0, + максимальное время ожидания на уровне библиотеки равно + бесконечности, в этом случае ошибка ввода/вывода может возникнуть + по истечению timeout'a в ядре TCP/IP (или системы). Таким образом, если \ts{timeout} в + параметре time больше чем timeout в ядре TCP/IP, он никогда + не прервет передачу данных. \footnote{\ts{Timeout} в ядрах разных TCP/IP(системах) разный} +} + +\ttt{STATUS \toindex{FtpReretrTimeout}(FTP~*, char~*command, char~*inp, char~*out, long~time)} +{ + Производит тo же сaмое действие что и функция \ts{FtpRetrTimeout}, за +исключение того, что перед передачей проверяется файл \ts{out}, и в случае +его существования передача с сервера начинается с байта с номером \ts{<размер файла out>}+1.} +\ttt{\toindex{FtpRetr}(FTP~*, char~*command, char~*inp, char~*out)} +{ + Вызывает то же действие что и FtpRetrTimeout, но с выключенным timeout'ом. +} + +\ttt{\toindex{FtpGetTimeout}(FTP~*, char~*inp, char~*out, long~time)} +{ + Передает с сервера файл \ts{inp} в локальный файл \ts{out}, при этом устанавливается + \ts{timeout=time}. +} + +\ttt{\toindex{FtpGet}(FTP~*, char~*in, char~*out)} +{ + Вызывает функцию \ts{FtpGetTimeout} с выключенным максимальным временем +ожидания данных} + +\ttt{\toindex{FtpDirectory}(FTP~*, char~*pat\footnote{Это первый аргумент для команды ls(dir)}, char~*out)} +{ + Передает содержимое директории, описанного параметром \ts{pat}, с сервера в файл \ts{out}. +} +\ttt{\toindex{FtpDir}(FTP~*, char~*out)} +{ + Передает содержимое текущей директории с сервера в файл \ts{out}. +} + +\section{Процедуры передачи данных на сервер} + +\ttt{\toindex{FtpStorTimeout}(FTP~*, char~*command, char~*inp, char~*out, long~time)} +{ + Передает содержимое локального файла \ts{inp} на сервер, предварительно послав +ему команду, составленную из \ts{command} и \ts{out}. Параметр \ts{time}, задает максимальное +время на отправку одного символа. +} + +\ttt{STATUS \toindex{FtpRestorTimeout}(FTP~*, char~*command, char~*inp, char~*out, long~time)} +{ + Производит тo же сaмое действие что и функция \ts{FtpStorTimeout}, за +исключение того, что перед передачей проверяется файл \ts{out} на сервере, +и, в случае его существования, передача на сервер начинается с байта с номером \ts{<размер файла out>}+1.} + +\ttt{\toindex{FtpStor}(FTP~*, char~*command, char~*inp, char*~out)} +{ + Вызывает запуск процедуры \ts{FtpStorTimeout} с параметром \ts{time=0}. +} + +\ttt{\toindex{FtpPutTimeout}(FTP~*, char~*in, char~*out, long~time)} +{ Передает локальный файл \ts{in} на сервер в файл с именем \ts{out}, при этом \ts{timeout=time}} + +\ttt{\toindex{FtpPut}(FTP~*, char~*in, char~*out)} +{ + Вызывает процедуру \ts{FtpPutTimeout} с параметром \ts{time=0}} + + +\section{Процедуры чтения/записи в файл на сервере} + +Для того, чтобы производить ввод/вывод из/в файлы которые находятся на сервере, +причем не копируя их предварительно в локальный файл, а работая непосредственно с оригиналом, +существует возможность открыть файл на сервере на чтение/запись/дозапись и +затем с помощью обычных процедур ввода/вывода или же при помощи процедур +\ts{FtpRead} и \ts{FtpWrite}, которые в отличии от первых преобразуют текстовые файлы, +производить необходимые операции. +\footnote{Естественно, такие функции как \ts{seek}, \ts{ioctl}, ... + для этих файлов недопустимы.} + + +\ttt{\toindex{FtpData}(FTP~*, char~*command, char~*param, char~*mode)} +{ Создает канал для передачи данных предварительно послав серверу команду которая +составляется из параметров \ts{command} и \ts{param}. Параметр \ts{mode} указывает может быть +или ``r'' или ``w''} + +\ttt{\toindex{FtpOpenRead}(FTP~*,char~*filename)} +{ Открывает для чтения файл с именем \ts{filename} на сервере } + +\ttt{\toindex{FtpOpenWrite}(FTP~*,char~*filename)} +{ Открывает для записи файл с именем \ts{filename} на сервере } + +\ttt{\toindex{FtpOpenAppend}(FTP~*,char~*filename)} +{ Открывает для дозаписи файл с именем \ts{filename} на сервере } + +\ttt{\toindex{FtpOpenDir}(FTP~*, char~*files)} +{ + Создает канал для чтения удаленного листинга директории, параметр files передается +команде \ts{ls} на сервере в качестве 1-го параметра +} + +\ttt{int \toindex{FtpRead}(FTP~*)}{Читает символ из потока данных, если была установлена + текстовая мода передачи \footnote{Установлена по умолчанию.}, преобразует переходы на новую строку. При обнаружении +конца потока возвращает \toindex{EOF}} + +\ttt{\toindex{FtpGetString}(FTP~*, char~*str)} +{ Чтение одной строки из потока данных при помощи функции \ts{FtpRead}.} + +\ttt{\toindex{FtpWrite}(FTP~*, char~c)}{Пишет символ в поток данных, если была установлена + текстовая мода передачи, преобразует переходы на новую строку. При обнаружении +ошибки ввода/вывода возвращает \toindex{EOF}} + +\ttt{\toindex{FtpClose}(FTP~*)} +{Закрывает ранее открытый поток данных.} + +\section{Команды для сервера и вспомогательные функции} + +\ttt{\toindex{FtpCommand}(FTP~*, char~*command, char~*param, int~ok1, ok2, ok3, ..., okN, EOF)} +{ Посылает команду, составленную из параметров \ts{command} и \ts{param}, и считывает +ответ сервера, если код ответа не совпадает не с одним значением \ts{ok}, то +знак кода ответа меняется на '-'. В случае если установлен handler обработки +ошибок вызывает его. +} + +\ttt{\toindex{FtpType}(FTP~*,char~*mode)} +{Устанавливает моду передачи файлов, mode может быть ``A'', ``I'', ``S'',....} + +\ttt{\toindex{FtpBinary}(FTP~*)} +{Устанавливает двоичную моду передачи файлов} + +\ttt{\toindex{FtpAscii}(FTP~*)} +{Устанавливает текстовую моду передачи файлов} + + +\ttt{\toindex{FtpMkdir}(FTP~*,char *dirname)} +{Создает директорию на сервере} + +\ttt{\toindex{FtpChdir}(FTP~*,char *dirname)} +{Меняет активную директорию на сервере} + +\ttt{\toindex{FtpRm}(FTP~*,char *filename)} +{Удаляет файл на сервере} + +\ttt{char~*\toindex{FtpPwd}(FTP~*)} +{Возвращает активную директорию на сервере} + +\ttt{int \toindex{FtpSize}(FTP~*,char *filename)} +{Возвращает размер файла в байтах, если файл с указанным именем отсутствует, +то возвращается статус ошибки, т.е. значение меньше нуля} + +\ttt{\toindex{FtpMove}(FTP~*,char *oldfilename, char *newfilename)} +{Переименовывает на сервере файл \ts{oldfilename} в файл \ts{newfilename}} + +\ttt{\toindex{FtpPort}(FTP~*, int~a, int~b, int~c, int~d, int~e, int~f)} +{Команда серверу создать канал для передачи данных. Причем \ts{a.b.c.d} это IP адрес +клиента а \ts{e*256+f} номер порта.} + +\ttt{struct hostent *\toindex{FtpGetHost}(char *hostname)} +{Возвращает указатель на структуру типа hostent. + Аргумент -- это строка содержащая или имя машины, +или ее IP адрес в строчном виде\footnote{Например: ``dxunk8.oea.ihep.su'' или +``192.102.229.71''}.} + +\section{Подпрограммы передачи сообщений в/из сервера} + +\ttt{\toindex{FtpSendMessage}(FTP~*, char~*message)} +{Посылает сообщение серверу} + +\ttt{int \toindex{FtpGetMessage}(FTP~*)} +{Принимает сообщение от сервера и возвращает его код} + +\ttt{\toindex{FtpMessage}(int Number)} +{Возвращает по коду сообщения его содержимое} + +\section{Функции полного сеанса работы} + +\ttt{FILE *\toindex{FtpFullOpen}(char *filename,char *mode)} +{ Разбирает строку filename, которая должна быть типа +\\ \ts{host/user/password:filename} или же типа \ts{filename}, в зависимости от этого +открывается файл или на сервере \ts{host} или локальный файл. Параметр mode должен +содержать один или два символа. Первый задает тип открытия файла ``r'',``w'' или +``a''. Второй символ может содержать символ ``b'' что будет задавать двоичную моду передачи} +\ttt{\toindex{FtpFullClose}(FILE *f)} +{Закрытие файла} + + +\section{Описание примеров и прикладных программ} + +\subsection{Программа get}\index{get} + +Копирование файла с сервера в локальный файл с таким же именем с использованием функций полного сеанса. + + +\subsection{Программа fcp}\index{fcp} + +Программа fcp демонстрирует простое использование функций полного сеанса работы +(FtpFullOpen и FtpFullClose). Имя файла передаваемого в качестве +параметра, может описывать и локальный и удаленный файл. Это позволяет +производить передачу как с сервера в локальный файл, так и наоборот, + а также с сервера на сервер. + +\subsection{Программа ftptry}\index{ftptry} + +Предназначена для передачи файлов большого размера по сетям которые +очень часто ``ломаются''. Это прежде всего относится к сетям построенных +на dialup-линиях. + +\ts{ftptry} в основном предназначен для неитерактивной +передачи данных, поэтому необходимая информация для выполнения передачи задаeтся в виде опций при запуске программы. + +При запуске \ts{ftptry} без ключей, на экран выводится список всех допустимых +опций и один пример запуска, поэтому в данном руководстве ключи +и их назначения описывать не имеет смысла. +Необходимо только сказать о том, что +так как некоторые опции необходимо ставить практически всегда, +то можно предварительно +установить переменную окружения ``FTPTRY''\index{FTPTRY enviroment} +по аналогии с тем как это делается +в программе ``less'' +\footnote{Например: \% setenv FTPTRY ``-DBb -u anonymous -s 60 -t 15''}, +и писать в командной строке только те опции которые редко +используются или не писать их вообще. + + +\newpage +\input rus.ind +\newpage +\tableofcontents +\end{document} + + |