Contents
=========
   I - Introduction
  II - compilation
 III - linking
  IV - API usage
   V - No exceptions wrappers
  VI - tree reading
 VII - Libdar tools

   I - Introduction
====================

  The API is the APplication Interface. It is composed of a set of functions
present in the libdar library and available to external programs. The features
currently provided correspond the features of the dar program only. There is
actually nothing concerning dar_slave dar_xform or dar_manager functions.
This will maybe come in the future.

Unless you plan to add dar's feature to your software application (in
particular a Graphical User Interface), you are not concerned by Dar's API.

This documentation applies to API Version 2.x . API version 2.x is not
compatible with version 1.x as not all calls from version 1 exist and those
with the same name may have different arguments. This is the reason why the
major number has changed from 1 to 2. However, API version 2 is very similar
to version 1 in the way to use it. This document thus assumes version 1 is
know (thus you have completely read DOC_API_V1) thus we can focus on the new
features and minor changes brought by API version 2.

  II - Compilation (minor change !)
===================
If you plane to link against the libdar32 or libdar64 version you need to add
either -DLIBDAR_MODE=32 or -DLIBDAR_MODE=64 to CPPFLAGS. (This changes from
API version 1, you must no more use the MODE macro, but the LIBDAR_MODE macro
instead). For the rest, see DOC_API_V1.

 III - linking (same as version 1)
===============
see DOC_API_V1


  IV - API usage
=================
A - Overview
B - Prerequisite for the C++ version of the API
C - Dynamic memory allocation
D - Libdar user interaction calls
E - Libdar action calls
F - exception set usage
G - libdar exceptions


A - Overview
----------------

At the difference of version 1, API version 2 proposes
two equivalent sets of functions. The first may throw
exceptions and is very similar (but with some changes) to the
functions found in API version 1. The second will never throw exceptions.

A function of this second set is in fact a wrapper to
a function of the first set, that catches any exception and
convert them in error code, which are passed in additional arguments
of the wrapper. Theses additional parameter allow you to know if the
call succeeded or if not what type of error have occured.

 -------------------------------------------------------------------
 IMPORTANT !
 The additional parameter of this second set of functions
 must be checked after every call to libdar, to know if the call
 has succeeded or not, you must never ignore them !
 -------------------------------------------------------------------

Else you may miss a major error and loose your backup without
any notice from your application (GUI etc.), problem you may then be
faced when you will need to recover your data after a crash disk or
other similar disaster.


B - Prerequisite for the C++ version of the API
-----------------------------------------------

read DOC_API_V1 for having more information on the 6 following topics:

1 - namespaces
2 - introduction to C++ unfamiliar programmers
3 - Macros
4 - C++ classes
5 - standard C++ classes
6 - detailed list of classes brought by the API

the following chapter extends the chapter 6 found in DOC_API_V1:

7 - the archive class (API V2 only)
.......................

The API version 2 introduces a new C++ class called "archive"
you don't have to bother about include files, and still only need libdar.hpp
file as for version 1.

The role of this class is to extract in virtual memory all required information
needed to operate on an existing archive, may it be for restoring files from
it, listing its contents, testing it, may it be to take it as reference for
another backup, or isolation, etc. You then have to extract only once, and you
can chain listing, diff, test, extraction, from a given "archive" object, which
will make your application faster, as the extraction of the catalogue and other
important informations about an archive is not a always very quick.

class archive has only one constructor which has the following arguments:

        archive(const path & chem, const std::string & basename, const std::string & extension, crypto_algo crypto, const std::string &pass, const std::string & input_pipe, const std::string & output_pipe, const std::string & execute, bool info_details);

where:

      	const path & chem
is the path of the archive to read, the argument can be substituted by a
std::string

	const std::string & basename
this is the slice name of the archive

	const std::string & extension
this is the extension of the archive (should be "dar")

	crypto_algo crypto,
is the crypto algorithm to use to read the archive (crypto_none or
crypto_scrambling for now)

	const std::string &pass
is the necessary pass string to unscramble the archive (not use if the previous
argument "crypto" is "crypto_none)

	const std::string & input_pipe
if the archive is to be read from a pipe input_pipe receive the named pipe
(this implies basename is equal to "-" meaning read from stdin/stdout) where
from to receive archive portions sent by dar_slave

	const std::string & output_pipe
if the archive is to be read from a pipe output_pipe receive the named pipe
where to send orders to dar_slave

	const std::string & execute
command to execute between slices

	bool info_details
set it to true for libdar tell what it does (information is sent to
user_interaction.hpp calls).

Given theses parameter to the constructor, an archive object is created that
is then required as first argument of the op_listing(), op_test(), op_diff()
and op_extract() API calls. This archive object may also be given to
op_create() and op_isolate() for the corresponding archive be used as reference
(-A option in command-line). As you see, archive objects cannot be use to
create an archive, they are built based an already existing archive.


C - Dynamic memory allocation
---------------------------------
see DOC_API_V1

D - Libdar user interaction calls
------------------------------------
- Dar's Version
- User interaction
- Getting compile time feature status

- Dar's Version (same as version 1)
.................

This is a very important point to respect.
See DOC_API_V1 !


          -------------------------------------------------
          |                                               |
          |             !!! WARNING !!!                   |
          |                                               |
          |   NO ASCENDING OR DESCENDING COMPATIBILITY    |
          |              MUST BE ASSUMED                  |
          |     BETWEEN TWO DIFFERENT MAJOR VERSIONS      |
          |                   OF                          |
          |               LIBDAR API !                    |
          |                                               |
          -------------------------------------------------

- User interaction (same as version 1)
....................
Important too,
read DOC_API_V1


- Getting compile time feature status (same as version 1)
.........................................
read DOC_API_V1


E - Libdar action calls
-------------------------

Dar command-line is able to perform 6 different operations:
- create an archive
- extract data from an archive
- list archive contents
- test an archive integrity
- compare an archive with a filesystem
- isolate a catalogue of an archive

for each action is defined a function in the API, which we will
revue, detailing and explaining its arguments,
and giving the command-line option that correspond to each argument.

///////
// in the following check the libdar.hpp file for up to date headers
// some minor changes may occur along the software cycle after documentation
// which is done as early as possible.
///////

- CREATION
.............

           statistics op_create(const path &fs_root,
                                const path &sauv_path,
                                archive *ref_arch,
                                const mask &selection,
                                const mask &subtree,
                                const std::string &filename,
                                const std::string & extension,
                                bool allow_over,
                                bool warn_over,
                                bool info_details,
                                bool pause,
                                bool empty_dir,
                                compression algo,
                                U_I compression_level,
                                const infinint & file_size,
                                const infinint & first_file_size,
                                bool root_ea,
                                bool user_ea,
                                const std::string & execute,
				crypto_algo crypto,
                                const std::string & pass,
                                const mask &compr_mask,
                                const infinint & min_compr_size,
                                bool nodump,
                                bool ignore_owner,
                                const infinint & hourshift,
				bool empty);

explaination about the arguments:

        const path &fs_root,
this is the path for the subdirectory to save (-R option)

        const path &sauv_path,
this is the path to where archive slices will be created

        archive *ref_arch,
if NULL the libdar does a full backup. Else takes the
given archive as reference

        const mask &selection,
this is the mask of the files to save. (-I and -X options).
this mask is applied only to filename (not including path)
and does not concerns directories' names. If you want
to include any files you could give "bool_mask(true)" as value,
but you could also build something much more complex than
-I/-X paradigm using any combination of et_mask ou_mask,
not_mask, etc.

        const mask &subtree,
this mask applied to any file including path part.
(-P option and [list of path]). As above, if you want
to include all files, you can use "bool_mask(true)" as argument,
but could also give something more complex than the
-P/[list of path] paradigm.

        const string &filename,
this is the basename of the archive (With sauv_path
--- see above --- it makes the argument given to -c option).

        const string & extension,
this is the extension to the archive. It is left as parametrable,
but is is strongly recommended to always use "dar" as argument.

        bool allow_over,
if set to true, overwriting slice is allowed, but a confirmation
is asked to the user first. If set to true, no overwriting is
allowed. (-n option = false).

        bool warn_over,
this option is only useful if overwriting is allowed. if set to
false it then avoids any complain before overwriting.
(-w option = false).

        bool info_details,
if set to true, display more information about what is done.
(-v options).

        bool pause,
if set to true, libdar pauses before writing a new slice. it also
pauses before the first slice, if the slices of the archive of
reference (if applicable), share the same path as the archive to be
created (-p option).

        bool empty_dir,
if set to true, any directory that get ignored by the subtree mask
is replaced by an empty directory (-D option).

        compression algo,
this is the compression algorithm to use:
none, gzip (-z option), bzip2 (-y option) are the only possible
values.

        U_I compression_level,
this is the compression level. Possible values are integers from
0 to 9.

        const infinint & file_size,
if set to zero, the archive will be generated in one slice. Else
if a strictly positive value is given, the archive will have slices
of that value in byte. Be aware that the slice header takes around
20 bytes, thus a value below 20 bytes will generate an error (-s option).

        const infinint & first_file_size,
defines the size in byte of the first slice. If set to zero, it is
assumed that the first slice has the same size of the following. Note
that if file_size = 0 first_file_size must also be equal to zero
(-S option).

        bool root_ea,
set to true, if you want to save root or system Extended Attributes.
Libdar must be compiled with Extended Attribute support activated.
(see -U option).

        bool user_ea,
set to true if you want to save user Extended Attributes. Libdar must
be compiled with Extended Attribute support activated. (see -u option).

        const string & execute,
if a non empty string is given, dar will execute the given command after
each new slice created. This uses the % substitution as described in man
pages

	crypto_algo crypto
this is the cryptographic algorithm used. Currently possible values are
crypto_none (no encryption) and crypto_scrambling (very weak encryption
scheme), the following argument "pass" receive in this later case the
passphrase.

        const string & pass,
if the previous argument "crypto" is not equal to "crypto_none" , this argument
receive the passphrase to use for encryption, (-K option for dar).

        const mask &compr_mask,
the given mask only apply to filenames, and determines which files must be
compressed (-Z and -Y options).

        const infinint & min_compr_size,
this determines a minimal size (in bytes) for a file to be elected to
compression. file smaller will never be compressed (-m option).

        bool nodump,
if set to true, do not save files which have the ext2/3 nodump flag set.
This option is available if activated at compilation time. (--nodump option)

        bool ignore_owner,
if set, do not compare ownership of files between filesystem to be saved
and archive of reference (-O option).

        const infinint & hourshift,
if set to a positive value assumes two dates are identical if they differ
by an integer number of hour, which number is less or equal than hourshift
(-H option). this is used when comparing files for a differential backup.

	bool empty
if set, do not perform the backup, but show all messages and warnings as
if it was for real.

this function returns a statistics C structure which interesting fields are:

        statistics st = op_create(...);

        st.treated              is the number inode saved
        st.hard_links   is the number of hard link recorded
        st.skipped              is the number of file not saved (no file change)
        st.errored              is the number of file failed to save (filesystem error)
        st.ignored              is the number of file excluded by any filter.
        st.deleted              is the number of file recored as deleted since reference backup
        st.ea_treated   is the number of file that get their EA saved.


- Extraction
...............

    extern statistics op_extract(archive *arch,
				 const path &fs_root,     // where to restore
                                 const mask &selection,   // filename based filter
                                 const mask &subtree,     // directory tree concerned by restoration
                                 bool allow_over,
                                 bool warn_over,
                                 bool info_details,
                                 bool detruire,
                                 bool only_more_recent,
                                 bool restore_ea_root,
                                 bool restore_ea_user,
                                 bool flat,              // if set, don't restore directory tree (all files are restored directly in fs_root)
                                 bool ignore_owner,      // don't try to restore ownership
				 bool warn_remove_no_match, // don't warn before removing a file which type does not match the one expected as (type of the file that was present in the archive of reference)
                                 const infinint & hourshift, // when only_more_recent is set, hourshift can be used to don't restore files
	                                                      // that have an integer number of hour of difference with the stored file in archive
	                                                      // see dar man page, option -H
				 bool empty);          // "dry run" option, -e for command-line

   not much to say, here, except that the first argument is an archive object that
   contains in memory all the necessary information to exploit the corresponding archive.

- LISTING
.............

    extern void op_listing(archive *arch,
                           bool info_details,
                           bool tar_format,
                           const mask &selection,
			   bool filter_unsaved);

    same remark here about the first argument. Selection is a filename filter
of file to list or not to list


- DIFFERENCE
.............

    extern statistics op_diff(archive *arch,
			      const path & fs_root,
                              const mask &selection,
                              const mask &subtree,
                              bool info_details,
                              bool check_ea_root,
                              bool check_ea_user,
                              bool ignore_owner);

- TESTING
.............

    extern statistics op_test(archive *arch,
                              const mask &selection,
                              const mask &subtree,
                              bool info_details);

- ISOLATION
.............

    extern void op_isolate(const path &sauv_path,
			   archive *ref_arch,
			   const std::string & filename,
			   const std::string & extension,
			   bool allow_over,
			   bool warn_over,
			   bool info_details,
			   bool pause,
			   compression algo,
			   U_I compression_level,
			   const infinint &file_size,
			   const infinint &first_file_size,
			   const std::string & execute,
		           crypto_algo crypto,
			   const std::string & pass);

	here we can note that the reference must be given by an archive object
(second argument).


F - exception set usage
-------------------------

For the exception generating calls, the general patern is then:

     try
     {
        archive arch = archive(chem, basename, ....);
        op_test(&arch, ...);
        ...
     }
     catch(...)
     {
        do something or not
        ...
     }



G - libdar exceptions
------------------------
see DOC_API_V1



   V - No exceptions wrappers
===============================

the version 2.0 will bring the open/close paradigm, which in the exception side
is implemented by the archive class. open is equivalent to creating an archive
object, and close is equivalent to destroying it. But, as the construction of
an archive object may throw exception, on the non exception side of the API,
there *are* open_archive_noexcept and close_archive_noexcept calls, which wrap
the construction and transparently destroy an archive object:

	archive* open_archive_noexcept(const path & chem, const std::string & basename,
                              const std::string & extension, crypto_algo crypto, const std::string &pass,
                              const std::string & input_pipe, const std::string & output_pipe,
                              const std::string & execute, bool info_details,
			      U_16 &exception,
			      std::string &except_msg);

        void close_archive_noexcept(archive *ptr, U_16 *exception, std::string &except_msg);


the resulting archive object (known by its address), can of course be used in
the previously seen op_extract(), op_test(), op_diff(), etc. but you may still
get exceptions thrown by these later functions.

So, to each of theses op_... calls, there is a 'no exception' wrapper, which
receive two additional arguments (in last positions):
- an exception indicator that tell which exception has been seen or if no
  exception needed to be trapped by the wrapper (which means the call
  succeeded), theses value have to be compared with the LIBDAR_NOEXCEPT,
  LIBDAR_EMEMORY, ... macros as defined in libdar.hpp
- if an exception occured (exception != LIBDAR_NOEXCEPT), the second new
  argument, receive the message that was carried by the exception, describing
  the nature of the error. This argument is set to an empty string if no
  exception has been caught.

for example:

     statistics op_create_noexcept(.... same as op_create...., U_16 &exception, std::string &except_msg);

you can see first the '_noexcept' suffix and the the two additional parameters
"exception" and "except_msg". Here follows a very basic example of use of
the _noexcept calls:

NO EXCEPTION WAY

    U_16 status;
    std::string msg;
    archive *arch = open_archive_noexcept("/tmp", "toto", "dar", "", "", "", "", true, status, msg);

    if(status != LIBDAR_NOEXCEPT)
    {
 	ui_printf("error openning archive: %S\n", &msg);
    }
    else
	if(arch == NULL)
	   printf("incoherence in libdar, report the bug to maintainer with sample code example that reproduce it, Thanks\n");
	else
        {
            op_listing_noexcept(arch, true, true, bool_mask(true), false, status, msg);

	    if(status != LIBDAR_NOEXCEPT)
               ui_printf("error listing archive content:%S\n", &msg);

            close_archive_noexcept(arch, status, msg);
            if(status != LIBDAR_NOEXCEPT)
               ui_printf("error closing the archive:%S\n", &msg);
        }

EXCEPTION WAY
by comparison follows the same example but using exception routines, this time:

    try
    {
       archive arch = archive("/tmp", "toto", "dar", "", "", "", "", true);
       op_listing(&arch, true, true, bool_mask(true), false);
    }
    catch(Egeneric & e)
    {
	string tmp = e.get_message();
	ui_printf("exception caught: %S\n", &tmp);
    }


VI - tree reading
=====================

in case of a huge archive listing, and with a GUI, it may be very time and
memory consuming to build the whole tree with graphical objects. Thus, instead
of calling op_listing() or op_listing_noexcept(), the following call is
available:

	bool get_children_of(archive *arch, const string & dir);

this will imply the call of set_op_tar_listing_callback() for each files or
directory children of "dir" path (which is a relative path to the store root
directory, or an empty string to get the children files of the root directory
in the archive). If the given path does not exist or is not a directory no
call to set_op_tar_listing_callback() will be done, but the return value of
get_children_of will be false meaning no children found. Of course there is
the _noexcept variant for that call.

	bool get_children_of_noexcept(archive *arch, path & dir, U_16 & exception, std::string & except_msg);

example (exception side):

	void my_list_function(const std::string & flag,
                              const std::string & perm,
                              const std::string & uid,
                              const std::string & gid,
                              const std::string & size,
                              const std::string & date,
                              const std::string & filename)
        {
            // for example, create graphical object for the given file
	    // you can throw inherited exception of Egeneric if you wish.
        }

	archive arch = archive(...);
	set_op_tar_listing_callback(&my_function);
        if(get_children_of(arch, ""); // get children of root
          printf("children found, and my_list_function has been called\n");
	else
	  printf("no children found, my_list_function has not been called\n");

        if(get_children_of(arch, "etc"); // get children of root
          printf("children found, and my_list_function has been called\n");
	else
	  printf("no children found, my_list_function has not been called\n");


VII - Libdar tools
======================

Libdar internally uses a special module called tools.hpp/tools.cpp. It is a
set of mostly autonomous functions that may also be useful for external
software. As requested for KDAR, this has been added in the API starting
version 1.0 but not been documented at that time. Thus here comes a
documentation of the most interesting calls for an external software. Note that
to use them, you will need to include the following:

   #include <dar/tools.hpp>


Note that quite all of theses calls may throw exceptions. For some very useful
function a _noexcept wrapper function is provided in libdar.hpp and is
mentionned in the following.

char *tools_str2charptr(std::string x);

	allocates a char * with new operator and fill it with the contents of
        the std::string argument. in case of error an exception is issued. In
        case of success the returned char * after use must be deleted with the
        delete operator.

        char *ptr = tools_str2charptr(....);
        ... do something with it ...
        delete ptr;

        a _noexception call is provided in the API: libdar_str2charptr_noexcept(),
        see libdar.hpp

char *tools_extract_basename(const char *command_name);
        allocates a char * with the new operator (thus this must be releaed
        using the delete operator as previously seen. The allocated array
        contains the basename of the argument. This is does the same as the
        standart command "basename".

void tools_split_path_basename(const char *all, path * &chemin, std::string & base);
void tools_split_path_basename(const std::string &all, std::string & chemin, std::string & base);
        both calls split the first argument in the path and basename part
        (second and third argument). for the first form, the second argument
        is dynamically allocated and must be released with the delete operator.

std::string tools_name_of_uid(U_16 uid);
std::string tools_name_of_gid(U_16 gid);
        convert uid or gid in the corresponding name (relies on the getpwuid()
        and getgrgid()
        system calls

std::string tools_int2str(S_I x);
        convert signed integer in its decimal representation

std::string tools_addspacebefore(std::string s, unsigned int expected_size);
        prefix the given string by as much necessary spaces to have the
        expected size

std::string tools_display_date(infinint date);
        give a string representing the given date (in seconds since Jan 1st,
        1970).

const char *tools_get_from_env(const char **env, char *clef);
       extract from environment (the third argument of the main() function),
       the given key and return the value found. If nothing is found the call
       return NULL. Note that the returned pointer does not point to a newly
       allocated memory, but to a portion of the system provided environment
       variable, thus you must never free by any mean the memory pointed to by
       the returned value of this call.

       this call does not throw any exception.

template <class T> extern T tools_rotate_right_one_bit(T v)
       this is a template, which must be used with integer agregates, which is
       a continuous bit field, which size is returned by the sizeof() operator.
       Example int, long, short, long long.

       the operator emulate the assembler right rotation of a single bit.

There is several other calls that should not be necessary for external program.
However, if some interest you, send me an email, for I add a note about it in
this document. Note that most of the time, theses "tools" are simple and not
have a very long code, thus if you know C or C++ having a look at the code in
tools.cpp should give you much informations (this does not avoid you to send
me an email for I update this documentation).
