gnunet-handbook

The GNUnet Handbook
Log | Files | Refs

tutorial.rst (78112B)


      1 **********
      2 C Tutorial
      3 **********
      4 
      5 This tutorials explains how to install GNUnet on a GNU/Linux system and
      6 gives an introduction on how GNUnet can be used to develop a
      7 Peer-to-Peer application. Detailed installation instructions for various
      8 operating systems and a detailed list of all dependencies can be found
      9 on our website at https://docs.gnunet.org/#Installation and in our
     10 Reference Documentation (GNUnet Handbook).
     11 
     12 Please read this tutorial carefully since every single step is
     13 important, and do not hesitate to contact the GNUnet team if you have
     14 any questions or problems! Visit this link in your webbrowser to learn
     15 how to contact the GNUnet team: https://gnunet.org/en/contact.html
     16 
     17 .. _Introduction-to-GNUnet-Architecture:
     18 
     19 Introduction to GNUnet Architecture
     20 ===================================
     21 
     22 GNUnet is organized in layers and services. Each service is composed of
     23 a main service implementation and a client library for other programs to
     24 use the service's functionality, described by an API. Some services
     25 provide an additional command line tool to enable the user to interact
     26 with the service.
     27 
     28 Very often it is other GNUnet services that will use these APIs to build
     29 the higher layers of GNUnet on top of the lower ones. Each layer expands
     30 or extends the functionality of the service below (for instance, to
     31 build a mesh on top of a DHT).
     32 
     33 The main service implementation runs as a standalone process in the
     34 Operating System and the client code runs as part of the client program,
     35 so crashes of a client do not affect the service process or other
     36 clients. The service and the clients communicate via a message protocol
     37 to be defined and implemented by the programmer.
     38 
     39 .. _First-Steps-with-GNUnet:
     40 
     41 First Steps with GNUnet
     42 =======================
     43 
     44 .. _Configure-your-peer:
     45 
     46 Configure your peer
     47 -------------------
     48 
     49 First of all we need to configure your peer. Each peer is started with a
     50 configuration containing settings for GNUnet itself and its services.
     51 This configuration is based on the default configuration shipped with
     52 GNUnet and can be modified. The default configuration is located in the
     53 ``$PREFIX/share/gnunet/config.d`` directory. When starting a peer, you
     54 can specify a customized configuration using the the ``-c`` command line
     55 switch when starting the ARM service and all other services. When using
     56 a modified configuration the default values are loaded and only values
     57 specified in the configuration file will replace the default values.
     58 
     59 Since we want to start additional peers later, we need some
     60 modifications from the default configuration. We need to create a
     61 separate service home and a file containing our modifications for this
     62 peer:
     63 
     64 .. code-block:: text
     65 
     66    $ mkdir ~/gnunet1/
     67    $ touch peer1.conf
     68 
     69 Now add the following lines to ``peer1.conf`` to use this directory. For
     70 simplified usage we want to prevent the peer to connect to the GNUnet
     71 network since this could lead to confusing output. This modifications
     72 will replace the default settings:
     73 
     74 .. code-block:: text
     75 
     76    [PATHS]
     77    # Use this directory to store GNUnet data
     78    GNUNET_HOME = ~/gnunet1/
     79    [hostlist]
     80    # prevent bootstrapping
     81    SERVERS =
     82 
     83 .. _Start-a-peer:
     84 
     85 Start a peer
     86 ------------
     87 
     88 Each GNUnet instance (called peer) has an identity (peer ID) based on a
     89 cryptographic public private key pair. The peer ID is the printable hash
     90 of the public key.
     91 
     92 GNUnet services are controlled by a master service, the so called
     93 Automatic Restart Manager (ARM). ARM starts, stops and even restarts
     94 services automatically or on demand when a client connects. You interact
     95 with the ARM service using the ``gnunet-arm`` tool. GNUnet can then be
     96 started with ``gnunet-arm -s`` and stopped with ``gnunet-arm -e``. An
     97 additional service not automatically started can be started using
     98 ``gnunet-arm -i <service name>`` and stopped using
     99 ``gnunet-arm -k <servicename>``.
    100 
    101 Once you have started your peer, you can use many other GNUnet commands
    102 to interact with it. For example, you can run:
    103 
    104 .. code-block:: text
    105 
    106    $ gnunet-core -i
    107 
    108 to obtain the public key of your peer.
    109 
    110 You should see an output containing the peer ID similar to:
    111 
    112 .. code-block:: text
    113 
    114    I am peer `0PA02UVRKQTS2C .. JL5Q78F6H0B1ACPV1CJI59MEQUMQCC5G'.
    115 
    116 .. _Monitor-a-peer:
    117 
    118 Monitor a peer
    119 --------------
    120 
    121 In this section, we will monitor the behaviour of our peer's DHT service
    122 with respect to a specific key. First we will start GNUnet and then
    123 start the DHT service and use the DHT monitor tool to monitor the PUT
    124 and GET commands we issue ussing the ``gnunet-dht-put`` and
    125 ``gnunet-dht-get`` commands. Using the "monitor" line given below, you
    126 can observe the behavior of your own peer's DHT with respect to the
    127 specified KEY:
    128 
    129 .. code-block:: text
    130 
    131    # start gnunet with all default services:
    132    $ gnunet-arm -c ~/peer1.conf -s
    133    # start DHT service:
    134    $ gnunet-arm -c ~/peer1.conf -i dht
    135    $ gnunet-dht-monitor -c ~/peer1.conf -k KEY
    136 
    137 Now open a separate terminal and:
    138 
    139 .. code-block:: text
    140 
    141    # put VALUE under KEY in the DHT:
    142    $ gnunet-dht-put -c ~/peer1.conf -k KEY -d VALUE
    143    # get key KEY from the DHT:
    144    $ gnunet-dht-get -c ~/peer1.conf -k KEY
    145    # print statistics about current GNUnet state:
    146    $ gnunet-statistics -c ~/peer1.conf
    147    # print statistics about DHT service:
    148    $ gnunet-statistics -c ~/peer1.conf -s dht
    149 
    150 .. _Starting-Two-Peers-by-Hand:
    151 
    152 Starting Two Peers by Hand
    153 --------------------------
    154 
    155 This section describes how to start two peers on the same machine by
    156 hand. The process is rather painful, but the description is somewhat
    157 instructive. In practice, you might prefer the automated method (see
    158 `Starting Peers Using the Testbed
    159 Service <#Starting-Peers-Using-the-Testbed-Service>`__).
    160 
    161 .. _Setup-a-second-peer:
    162 
    163 Setup a second peer
    164 ~~~~~~~~~~~~~~~~~~~
    165 
    166 We will now start a second peer on your machine. For the second peer,
    167 you will need to manually create a modified configuration file to avoid
    168 conflicts with ports and directories. A peers configuration file is by
    169 default located in ``~/.config/gnunet.conf``. This file is typically
    170 very short or even empty as only the differences to the defaults need to
    171 be specified. The defaults are located in many files in the
    172 ``$PREFIX/share/gnunet/config.d`` directory.
    173 
    174 To configure the second peer, use the files
    175 ``$PREFIX/share/gnunet/config.d`` as a template for your main
    176 configuration file:
    177 
    178 .. code-block:: text
    179 
    180    $ cat $PREFIX/share/gnunet/config.d/*.conf > peer2.conf
    181 
    182 Now you have to edit ``peer2.conf`` and change:
    183 
    184 -  ``GNUNET\_TEST\_HOME`` under ``PATHS``
    185 
    186 -  Every (uncommented) value for "\ ``PORT``\ " (add 10000) in any
    187    section (the option may be commented out if ``PORT`` is prefixed by
    188    \"\#\", in this case, UNIX domain sockets are used and the PORT
    189    option does not need to be touched)
    190 
    191 -  Every value for "\ ``UNIXPATH``\ " in any section (e.g. by adding a
    192    \"-p2\" suffix)
    193 
    194 to a fresh, unique value. Make sure that the PORT numbers stay below
    195 65536. From now on, whenever you interact with the second peer, you need
    196 to specify ``-c peer2.conf`` as an additional command line argument.
    197 
    198 Now, generate the 2nd peer's private key:
    199 
    200 .. code-block:: text
    201 
    202    $ gnunet-core -i -c peer2.conf
    203 
    204 This may take a while, generate entropy using your keyboard or mouse as
    205 needed. Also, make sure the output is different from the gnunet-core
    206 output for the first peer (otherwise you made an error in the
    207 configuration).
    208 
    209 .. _Start-the-second-peer-and-connect-the-peers:
    210 
    211 Start the second peer and connect the peers
    212 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    213 
    214 Then, you can start a second peer using:
    215 
    216 .. code-block:: text
    217 
    218    $ gnunet-arm -c peer2.conf -s
    219    $ gnunet-arm -c peer2.conf -i dht
    220    $ ~/gnunet/src/dht/gnunet-dht-put -c peer2.conf -k KEY -d VALUE
    221    $ ~/gnunet/src/dht/gnunet-dht-get -c peer2.conf -k KEY
    222 
    223 If you want the two peers to connect, you have multiple options:
    224 
    225 -  UDP neighbour discovery (automatic)
    226 
    227 -  Setup a bootstrap server
    228 
    229 -  Connect manually
    230 
    231 To setup peer 1 as bootstrapping server change the configuration of the
    232 first one to be a hostlist server by adding the following lines to
    233 ``peer1.conf`` to enable bootstrapping server:
    234 
    235 .. code-block:: text
    236 
    237    [hostlist]
    238    OPTIONS = -p
    239 
    240 Then change ``peer2.conf`` and replace the "\ ``SERVERS``\ " line in the
    241 "\ ``[hostlist]``\ " section with "\ ``http://localhost:8080/``\ ".
    242 Restart both peers using:
    243 
    244 .. code-block:: text
    245 
    246    # stop first peer
    247    $ gnunet-arm -c peer1.conf -e
    248    # start first peer
    249    $ gnunet-arm -c peer1.conf -s
    250    # start second peer
    251    $ gnunet-arm -c peer2.conf -s
    252 
    253 Note that if you start your peers without changing these settings, they
    254 will use the "global" hostlist servers of the GNUnet P2P network and
    255 likely connect to those peers. At that point, debugging might become
    256 tricky as you're going to be connected to many more peers and would
    257 likely observe traffic and behaviors that are not explicitly controlled
    258 by you.
    259 
    260 .. _How-to-connect-manually:
    261 
    262 How to connect manually
    263 ~~~~~~~~~~~~~~~~~~~~~~~
    264 
    265 If you want to use the ``peerinfo`` tool to connect your peers, you
    266 should:
    267 
    268 -  Set ``IMMEDIATE_START = NO`` in section ``hostlist`` (to not connect
    269    to the global GNUnet)
    270 
    271 -  Start both peers running ``gnunet-arm -c peer1.conf -s`` and
    272    ``gnunet-arm -c peer2.conf -s``
    273 
    274 -  Get ``HELLO`` message of the first peer running
    275    ``gnunet-hello -c peer1.conf --export-hello``
    276 
    277 -  Give the output to the second peer by running
    278    ``echo "gnunet://hello/..." | gnunet-hello -c peer2.conf --import-hello``
    279 
    280 Check that they are connected using ``gnunet-core -s -c peer1.conf``, which
    281 should give you the other peer's peer identity:
    282 
    283 
    284 .. code-block:: text
    285 
    286    $ gnunet-core -s -c peer1.conf
    287    Peer `9TVUCS8P5A7ILLBGO6 [...shortened...] 1KNBJ4NGCHP3JPVULDG'
    288 
    289 .. _Starting-Peers-Using-the-Testbed-Service:
    290 
    291 Starting Peers Using the Testbed Service
    292 ----------------------------------------
    293 
    294 GNUnet's testbed service is used for testing scenarios where a number of
    295 peers are to be started. The testbed can manage peers on a single host
    296 or on multiple hosts in a distributed fashion. On a single affordable
    297 computer, it should be possible to run around tens of peers without
    298 drastically increasing the load on the system.
    299 
    300 The testbed service can be access through its API
    301 ``include/gnunet\_testbed\_service.h``. The API provides many routines
    302 for managing a group of peers. It also provides a helper function
    303 ``GNUNET\_TESTBED\_test\_run()`` to quickly setup a minimalistic testing
    304 environment on a single host.
    305 
    306 This function takes a configuration file which will be used as a
    307 template configuration for the peers. The testbed takes care of
    308 modifying relevant options in the peers' configuration such as
    309 ``SERVICEHOME``, ``PORT``, ``UNIXPATH`` to unique values so that peers
    310 run without running into conflicts. It also checks and assigns the ports
    311 in configurations only if they are free.
    312 
    313 Additionally, the testbed service also reads its options from the same
    314 configuration file. Various available options and details about them can
    315 be found in the testbed default configuration file
    316 ``src/testbed/testbed.conf``.
    317 
    318 With the testbed API, a sample test case can be structured as follows:
    319 
    320 .. code-block:: text
    321 
    322    #include <unistd.h>
    323    #include <gnunet/platform.h>
    324    #include <gnunet/gnunet_util_lib.h>
    325    #include <gnunet/gnunet_testbed_service.h>
    326    #include <gnunet/gnunet_dht_service.h>
    327 
    328    #define NUM_PEERS 20
    329 
    330    static struct GNUNET_TESTBED_Operation *dht_op;
    331 
    332    static struct GNUNET_DHT_Handle *dht_handle;
    333 
    334 
    335    struct MyContext
    336    {
    337      int ht_len;
    338    } ctxt;
    339 
    340 
    341    static int result;
    342 
    343 
    344    static void
    345    shutdown_task (void *cls)
    346    {
    347      if (NULL != dht_op)
    348      {
    349        GNUNET_TESTBED_operation_done (dht_op);
    350        dht_op = NULL;
    351        dht_handle = NULL;
    352      }
    353      result = GNUNET_OK;
    354    }
    355 
    356 
    357    static void
    358    service_connect_comp (void *cls,
    359                          struct GNUNET_TESTBED_Operation *op,
    360                          void *ca_result,
    361                          const char *emsg)
    362    {
    363      GNUNET_assert (op == dht_op);
    364      dht_handle = ca_result;
    365      // Do work here...
    366      GNUNET_SCHEDULER_shutdown ();
    367    }
    368 
    369 
    370    static void *
    371    dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
    372    {
    373      struct MyContext *ctxt = cls;
    374 
    375      dht_handle = GNUNET_DHT_connect (cfg, ctxt->ht_len);
    376      return dht_handle;
    377    }
    378 
    379 
    380    static void
    381    dht_da (void *cls, void *op_result)
    382    {
    383      struct MyContext *ctxt = cls;
    384 
    385      GNUNET_DHT_disconnect ((struct GNUNET_DHT_Handle *) op_result);
    386      dht_handle = NULL;
    387    }
    388 
    389 
    390    static void
    391    test_master (void *cls,
    392                 struct GNUNET_TESTBED_RunHandle *h,
    393                 unsigned int num_peers,
    394                 struct GNUNET_TESTBED_Peer **peers,
    395                 unsigned int links_succeeded,
    396                 unsigned int links_failed)
    397    {
    398      ctxt.ht_len = 10;
    399      dht_op = GNUNET_TESTBED_service_connect
    400          (NULL, peers[0], "dht",
    401           &service_connect_comp, NULL,
    402           &dht_ca, &dht_da, &ctxt);
    403      GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL);
    404    }
    405 
    406 
    407    int
    408    main (int argc, char **argv)
    409    {
    410      int ret;
    411 
    412      result = GNUNET_SYSERR;
    413      ret = GNUNET_TESTBED_test_run
    414          ("awesome-test", "template.conf",
    415           NUM_PEERS, 0LL,
    416           NULL, NULL, &test_master, NULL);
    417      if ( (GNUNET_OK != ret) || (GNUNET_OK != result) )
    418        return 1;
    419      return 0;
    420    }
    421 
    422 The source code for the above listing can be found at
    423 https://git.gnunet.org/gnunet.git/tree/doc/documentation/testbed_test.c
    424 or in the ``doc/`` folder of your repository check-out. After installing
    425 GNUnet, the above source code can be compiled as:
    426 
    427 .. code-block:: text
    428 
    429    $ export CPPFLAGS="-I/path/to/gnunet/headers"
    430    $ export LDFLAGS="-L/path/to/gnunet/libraries"
    431    $ gcc $CPPFLAGS $LDFLAGS -o testbed-test testbed_test.c \
    432     -lgnunettestbed -lgnunetdht -lgnunetutil
    433    # Generate (empty) configuration
    434    $ touch template.conf
    435    # run it (press CTRL-C to stop)
    436    $ ./testbed-test
    437 
    438 The ``CPPFLAGS`` and ``LDFLAGS`` are necessary if GNUnet is installed
    439 into a different directory other than ``/usr/local``.
    440 
    441 All of testbed API's peer management functions treat management actions
    442 as operations and return operation handles. It is expected that the
    443 operations begin immediately, but they may get delayed (to balance out
    444 load on the system). The program using the API then has to take care of
    445 marking the operation as "done" so that its associated resources can be
    446 freed immediately and other waiting operations can be executed.
    447 Operations will be canceled if they are marked as "done" before their
    448 completion.
    449 
    450 An operation is treated as completed when it succeeds or fails.
    451 Completion of an operation is either conveyed as events through
    452 controller event callback or through respective operation completion
    453 callbacks. In functions which support completion notification through
    454 both controller event callback and operation completion callback, first
    455 the controller event callback will be called. If the operation is not
    456 marked as done in that callback or if the callback is given as NULL when
    457 creating the operation, the operation completion callback will be
    458 called. The API documentation shows which event are to be expected in
    459 the controller event notifications. It also documents any exceptional
    460 behaviour.
    461 
    462 Once the peers are started, test cases often need to connect some of the
    463 peers' services. Normally, opening a connect to a peer's service
    464 requires the peer's configuration. While using testbed, the testbed
    465 automatically generates per-peer configuration. Accessing those
    466 configurations directly through file system is discouraged as their
    467 locations are dynamically created and will be different among various
    468 runs of testbed. To make access to these configurations easy, testbed
    469 API provides the function ``GNUNET\_TESTBED\_service\_connect()``. This
    470 function fetches the configuration of a given peer and calls the Connect
    471 Adapter. In the example code, it is the ``dht\_ca``. A connect adapter
    472 is expected to open the connection to the needed service by using the
    473 provided configuration and return the created service connection handle.
    474 Successful connection to the needed service is signaled through
    475 ``service\_connect\_comp\_cb``.
    476 
    477 A dual to connect adapter is the Disconnect Adapter. This callback is
    478 called after the connect adapter has been called when the operation from
    479 ``GNUNET\_TESTBED\_service\_connect()`` is marked as "done". It has to
    480 disconnect from the service with the provided service handle
    481 (``op\_result``).
    482 
    483 Exercise: Find out how many peers you can run on your system.
    484 
    485 Exercise: Find out how to create a 2D torus topology by changing the
    486 options in the configuration file. See section "The GNUnet Reference
    487 Documentation" in The GNUnet Reference Documentation, then use the DHT
    488 API to store and retrieve values in the network.
    489 
    490 .. _Developing-Applications:
    491 
    492 Developing Applications
    493 =======================
    494 
    495 .. _gnunet_002dext:
    496 
    497 gnunet-ext
    498 ----------
    499 
    500 To develop a new peer-to-peer application or to extend GNUnet we provide
    501 a template build system for writing GNUnet extensions in C. It can be
    502 obtained as follows:
    503 
    504 .. code-block:: text
    505 
    506    $ git clone https://git.gnunet.org/gnunet-ext.git
    507    $ cd gnunet-ext/
    508    $ ./bootstrap
    509    $ ./configure --prefix=$PREFIX --with-gnunet=$PREFIX
    510    $ make
    511    $ make install
    512    $ make check
    513 
    514 The GNUnet ext template includes examples and a working buildsystem for
    515 a new GNUnet service. A common GNUnet service consists of the following
    516 parts which will be discussed in detail in the remainder of this
    517 document. The functionality of a GNUnet service is implemented in:
    518 
    519 -  the GNUnet service (gnunet-ext/src/ext/gnunet-service-ext.c)
    520 
    521 -  the client API (gnunet-ext/src/ext/ext_api.c)
    522 
    523 -  the client application using the service API
    524    (gnunet-ext/src/ext/gnunet-ext.c)
    525 
    526 The interfaces for these entities are defined in:
    527 
    528 -  client API interface (gnunet-ext/src/ext/ext.h)
    529 
    530 -  the service interface
    531    (gnunet-ext/src/include/gnunet_service_SERVICE.h)
    532 
    533 -  the P2P protocol (gnunet-ext/src/include/gnunet_protocols_ext.h)
    534 
    535 In addition the ext systems provides:
    536 
    537 -  a test testing the API (gnunet-ext/src/ext/test_ext_api.c)
    538 
    539 -  a configuration template for the service
    540    (gnunet-ext/src/ext/ext.conf.in)
    541 
    542 .. _Adapting-the-Template:
    543 
    544 Adapting the Template
    545 ---------------------
    546 
    547 The first step for writing any extension with a new service is to ensure
    548 that the ``ext.conf.in`` file contains entries for the ``UNIXPATH``,
    549 ``PORT`` and ``BINARY`` for the service in a section named after the
    550 service.
    551 
    552 If you want to adapt the template rename the ``ext.conf.in`` to match
    553 your services name, you have to modify the ``AC\_OUTPUT`` section in
    554 ``configure.ac`` in the ``gnunet-ext`` root.
    555 
    556 .. _Writing-a-Client-Application:
    557 
    558 Writing a Client Application
    559 ----------------------------
    560 
    561 When writing any client application (for example, a command-line tool),
    562 the basic structure is to start with the ``GNUNET\_PROGRAM\_run``
    563 function. This function will parse command-line options, setup the
    564 scheduler and then invoke the ``run`` function (with the remaining
    565 non-option arguments) and a handle to the parsed configuration (and the
    566 configuration file name that was used, which is typically not needed):
    567 
    568 .. code-block:: text
    569 
    570    #include <gnunet/platform.h>
    571    #include <gnunet/gnunet_util_lib.h>
    572 
    573    static int ret;
    574 
    575    static void
    576    run (void *cls,
    577         char *const *args,
    578         const char *cfgfile,
    579         const struct GNUNET_CONFIGURATION_Handle *cfg)
    580    {
    581      // main code here
    582      ret = 0;
    583    }
    584 
    585    int
    586    main (int argc, char *const *argv)
    587    {
    588      struct GNUNET_GETOPT_CommandLineOption options[] = {
    589        GNUNET_GETOPT_OPTION_END
    590      };
    591      return (GNUNET_OK ==
    592              GNUNET_PROGRAM_run (argc,
    593                                  argv,
    594                                  "binary-name",
    595                                  gettext_noop ("binary description text"),
    596                                  options, &run, NULL)) ? ret : 1;
    597    }
    598 
    599 .. _Handling-command_002dline-options:
    600 
    601 Handling command-line options
    602 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    603 
    604 Options can then be added easily by adding global variables and
    605 expanding the ``options`` array. For example, the following would add a
    606 string-option and a binary flag (defaulting to ``NULL`` and
    607 ``GNUNET\_NO`` respectively):
    608 
    609 .. code-block:: text
    610 
    611    static char *string_option;
    612    static int a_flag;
    613 
    614    // ...
    615      struct GNUNET_GETOPT_CommandLineOption options[] = {
    616        GNUNET_GETOPT_option_string ('s', "name", "SOMESTRING",
    617         gettext_noop ("text describing the string_option NAME"),
    618         &string_option},
    619        GNUNET_GETOPT_option_flag ('f', "flag",
    620         gettext_noop ("text describing the flag option"), 
    621         &a_flag),
    622        GNUNET_GETOPT_OPTION_END
    623      };
    624      string_option = NULL;
    625      a_flag = GNUNET_SYSERR;
    626    // ...
    627 
    628 Issues such as displaying some helpful text describing options using the
    629 ``--help`` argument and error handling are taken care of when using this
    630 approach. Other ``GNUNET\_GETOPT\_``-functions can be used to obtain
    631 integer value options, increment counters, etc. You can even write
    632 custom option parsers for special circumstances not covered by the
    633 available handlers. To check if an argument was specified by the user
    634 you initialize the variable with a specific value (e.g. NULL for a
    635 string and GNUNET\_SYSERR for a integer) and check after parsing
    636 happened if the values were modified.
    637 
    638 Inside the ``run`` method, the program would perform the
    639 application-specific logic, which typically involves initializing and
    640 using some client library to interact with the service. The client
    641 library is supposed to implement the IPC whereas the service provides
    642 more persistent P2P functions.
    643 
    644 Exercise: Add a few command-line options and print them inside of
    645 ``run``. What happens if the user gives invalid arguments?
    646 
    647 .. _Writing-a-Client-Library:
    648 
    649 Writing a Client Library
    650 ~~~~~~~~~~~~~~~~~~~~~~~~
    651 
    652 The first and most important step in writing a client library is to
    653 decide on an API for the library. Typical API calls include connecting
    654 to the service, performing application-specific requests and cleaning
    655 up. Many examples for such service APIs can be found in the
    656 ``gnunet/src/include/gnunet\_*\_service.h`` files.
    657 
    658 Then, a client-service protocol needs to be designed. This typically
    659 involves defining various message formats in a header that will be
    660 included by both the service and the client library (but is otherwise
    661 not shared and hence located within the service's directory and not
    662 installed by ``make install``). Each message must start with a
    663 ``struct GNUNET\_MessageHeader`` and must be shorter than 64k. By
    664 convention, all fields in IPC (and P2P) messages must be in big-endian
    665 format (and thus should be read using ``ntohl`` and similar functions
    666 and written using ``htonl`` and similar functions). Unique message types
    667 must be defined for each message struct in the ``gnunet\_protocols.h``
    668 header (or an extension-specific include file).
    669 
    670 .. _Connecting-to-the-Service:
    671 
    672 Connecting to the Service
    673 ^^^^^^^^^^^^^^^^^^^^^^^^^
    674 
    675 Before a client library can implement the application-specific protocol
    676 with the service, a connection must be created:
    677 
    678 .. code-block:: text
    679 
    680    struct GNUNET_MQ_MessageHandlers handlers[] = {
    681        // ...
    682      GNUNET_MQ_handler_end ()
    683    };
    684    struct GNUNET_MQ_Handle *mq;
    685 
    686    mq = GNUNET_CLIENT_connect (cfg,
    687                                "service-name",
    688                                handlers,
    689                                &error_cb,
    690                                NULL);
    691 
    692 As a result a ``GNUNET\_MQ\_Handle`` is returned which can to used
    693 henceforth to transmit messages to the service. The complete MQ API can
    694 be found in ``gnunet\_mq\_lib.h``. The ``handlers`` array in the example
    695 above is incomplete. Here is where you will define which messages you
    696 expect to receive from the service, and which functions handle them. The
    697 ``error\_cb`` is a function that is to be called whenever there are
    698 errors communicating with the service.
    699 
    700 .. _Sending-messages:
    701 
    702 Sending messages
    703 ^^^^^^^^^^^^^^^^
    704 
    705 In GNUnet, messages are always sent beginning with a
    706 ``struct GNUNET\_MessageHeader`` in big endian format. This header
    707 defines the size and the type of the message, the payload follows after
    708 this header.
    709 
    710 .. code-block:: text
    711 
    712    struct GNUNET_MessageHeader
    713    {
    714      uint16_t size GNUNET_PACKED;
    715      uint16_t type GNUNET_PACKED;
    716    };
    717 
    718 Existing message types are defined in ``gnunet\_protocols.h``. A common
    719 way to create a message is with an envelope:
    720 
    721 .. code-block:: text
    722 
    723    struct GNUNET_MQ_Envelope *env;
    724    struct GNUNET_MessageHeader *msg;
    725 
    726    env = GNUNET_MQ_msg_extra (msg, payload_size, GNUNET_MY_MESSAGE_TYPE);
    727    GNUNET_memcpy (&msg[1],
    728                   &payload,
    729                   payload_size);
    730    // Send message via message queue 'mq'
    731    GNUNET_mq_send (mq, env);
    732 
    733 Exercise: Define a message struct that includes a 32-bit unsigned
    734 integer in addition to the standard GNUnet MessageHeader. Add a C struct
    735 and define a fresh protocol number for your message. Protocol numbers in
    736 gnunet-ext are defined in
    737 ``gnunet-ext/src/include/gnunet_protocols_ext.h``
    738 
    739 Exercise: Find out how you can determine the number of messages in a
    740 message queue.
    741 
    742 Exercise: Find out how you can determine when a message you have queued
    743 was actually transmitted.
    744 
    745 Exercise: Define a helper function to transmit a 32-bit unsigned integer
    746 (as payload) to a service using some given client handle.
    747 
    748 .. _Receiving-Replies-from-the-Service:
    749 
    750 Receiving Replies from the Service
    751 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    752 
    753 Clients can receive messages from the service using the handlers
    754 specified in the ``handlers`` array we specified when connecting to the
    755 service. Entries in the the array are usually created using one of two
    756 macros, depending on whether the message is fixed size or variable size.
    757 Variable size messages are managed using two callbacks, one to check
    758 that the message is well-formed, the other to actually process the
    759 message. Fixed size messages are fully checked by the MQ-logic, and thus
    760 only need to provide the handler to process the message. Note that the
    761 prefixes ``check\_`` and ``handle\_`` are mandatory.
    762 
    763 .. code-block:: text
    764 
    765    static void
    766    handle_fix (void *cls, const struct MyMessage *msg)
    767    {
    768      // process 'msg'
    769    }
    770 
    771    static int
    772    check_var (void *cls, const struct MyVarMessage *msg)
    773    {
    774      // check 'msg' is well-formed
    775      return GNUNET_OK;
    776    }
    777 
    778    static void
    779    handle_var (void *cls, const struct MyVarMessage *msg)
    780    {
    781      // process 'msg'
    782    }
    783 
    784    struct GNUNET_MQ_MessageHandler handlers[] = {
    785      GNUNET_MQ_hd_fixed_size (fix,
    786                              GNUNET_MESSAGE_TYPE_MY_FIX,
    787                              struct MyMessage,
    788                              NULL),
    789      GNUNET_MQ_hd_fixed_size (var,
    790                              GNUNET_MESSAGE_TYPE_MY_VAR,
    791                              struct MyVarMessage,
    792                              NULL),
    793 
    794      GNUNET_MQ_handler_end ()
    795    };
    796 
    797 Exercise: Expand your helper function to receive a response message (for
    798 example, containing just the ``struct GNUnet MessageHeader`` without any
    799 payload). Upon receiving the service's response, you should call a
    800 callback provided to your helper function's API.
    801 
    802 Exercise: Figure out where you can pass values to the closures
    803 (``cls``).
    804 
    805 .. _Writing-a-user-interface:
    806 
    807 Writing a user interface
    808 ~~~~~~~~~~~~~~~~~~~~~~~~
    809 
    810 Given a client library, all it takes to access a service now is to
    811 combine calls to the client library with parsing command-line options.
    812 
    813 Exercise: Call your client API from your ``run()`` method in your client
    814 application to send a request to the service. For example, send a 32-bit
    815 integer value based on a number given at the command-line to the
    816 service.
    817 
    818 .. _Writing-a-Service:
    819 
    820 Writing a Service
    821 -----------------
    822 
    823 Before you can test the client you've written so far, you'll need to
    824 also implement the corresponding service.
    825 
    826 .. _Code-Placement:
    827 
    828 Code Placement
    829 ~~~~~~~~~~~~~~
    830 
    831 New services are placed in their own subdirectory under ``gnunet/src``.
    832 This subdirectory should contain the API implementation file
    833 ``SERVICE\_api.c``, the description of the client-service protocol
    834 ``SERVICE.h`` and P2P protocol ``SERVICE\_protocol.h``, the
    835 implementation of the service itself ``gnunet-service-SERVICE.h`` and
    836 several files for tests, including test code and configuration files.
    837 
    838 .. _Starting-a-Service:
    839 
    840 Starting a Service
    841 ~~~~~~~~~~~~~~~~~~
    842 
    843 The key API definition for creating a service is the
    844 ``GNUNET\_SERVICE\_MAIN`` macro:
    845 
    846 .. code-block:: text
    847 
    848    GNUNET_SERVICE_MAIN
    849    ("service-name",
    850     GNUNET_SERVICE_OPTION_NONE,
    851     &run,
    852     &client_connect_cb,
    853     &client_disconnect_cb,
    854     NULL,
    855     GNUNET_MQ_hd_fixed_size (...),
    856     GNUNET_MQ_hd_var_size (...),
    857     GNUNET_MQ_handler_end ());
    858 
    859 In addition to the service name and flags, the macro takes three
    860 functions, typically called ``run``, ``client\_connect\_cb`` and
    861 ``client\_disconnect\_cb`` as well as an array of message handlers that
    862 will be called for incoming messages from clients.
    863 
    864 A minimal version of the three central service functions would look like
    865 this:
    866 
    867 .. code-block:: text
    868 
    869    static void
    870    run (void *cls,
    871         const struct GNUNET_CONFIGURATION_Handle *c,
    872         struct GNUNET_SERVICE_Handle *service)
    873    {
    874    }
    875 
    876    static void *
    877    client_connect_cb (void *cls,
    878                       struct GNUNET_SERVICE_Client *c,
    879                       struct GNUNET_MQ_Handle *mq)
    880    {
    881      return c;
    882    }
    883 
    884    static void
    885    client_disconnect_cb (void *cls,
    886                          struct GNUNET_SERVICE_Client *c,
    887                          void *internal_cls)
    888    {
    889      GNUNET_assert (c == internal_cls);
    890    }
    891 
    892 Exercise: Write a stub service that processes no messages at all in your
    893 code. Create a default configuration for it, integrate it with the build
    894 system and start the service from ``gnunet-service-arm`` using
    895 ``gnunet-arm -i NAME``.
    896 
    897 Exercise: Figure out how to set the closure (``cls``) for handlers of a
    898 service.
    899 
    900 Exercise: Figure out how to send messages from the service back to the
    901 client.
    902 
    903 Each handler function in the service **must** eventually (possibly in
    904 some asynchronous continuation) call
    905 ``GNUNET\_SERVICE\_client\_continue()``. Only after this call additional
    906 messages from the same client may be processed. This way, the service
    907 can throttle processing messages from the same client.
    908 
    909 Exercise: Change the service to "handle" the message from your client
    910 (for now, by printing a message). What happens if you forget to call
    911 ``GNUNET\_SERVICE\_client\_continue()``?
    912 
    913 .. _Interacting-directly-with-other-Peers-using-the-CORE-Service:
    914 
    915 Interacting directly with other Peers using the CORE Service
    916 ------------------------------------------------------------
    917 
    918 FIXME: This section still needs to be updated to the latest API!
    919 
    920 One of the most important services in GNUnet is the ``CORE`` service
    921 managing connections between peers and handling encryption between
    922 peers.
    923 
    924 One of the first things any service that extends the P2P protocol
    925 typically does is connect to the ``CORE`` service using:
    926 
    927 .. code-block:: text
    928 
    929    #include <gnunet/gnunet_core_service.h>
    930 
    931    struct GNUNET_CORE_Handle *
    932    GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
    933                         void *cls,
    934                         GNUNET_CORE_StartupCallback init,
    935                         GNUNET_CORE_ConnectEventHandler connects,
    936                         GNUNET_CORE_DisconnectEventHandler disconnects,
    937                         const struct GNUNET_MQ_MessageHandler *handlers);
    938 
    939 .. _New-P2P-connections:
    940 
    941 New P2P connections
    942 ~~~~~~~~~~~~~~~~~~~
    943 
    944 Before any traffic with a different peer can be exchanged, the peer must
    945 be known to the service. This is notified by the ``CORE`` ``connects``
    946 callback, which communicates the identity of the new peer to the
    947 service:
    948 
    949 .. code-block:: text
    950 
    951    void *
    952    connects (void *cls,
    953              const struct GNUNET_PeerIdentity *peer,
    954              struct GNUNET_MQ_Handle *mq)
    955    {
    956      return mq;
    957    }
    958 
    959 Note that whatever you return from ``connects`` is given as the ``cls``
    960 argument to the message handlers for messages from the respective peer.
    961 
    962 Exercise: Create a service that connects to the ``CORE``. Then start
    963 (and connect) two peers and print a message once your connect callback
    964 is invoked.
    965 
    966 .. _Receiving-P2P-Messages:
    967 
    968 Receiving P2P Messages
    969 ~~~~~~~~~~~~~~~~~~~~~~
    970 
    971 To receive messages from ``CORE``, you pass the desired ``handlers`` to
    972 the ``GNUNET\_CORE\_connect()`` function, just as we showed for
    973 services.
    974 
    975 It is your responsibility to process messages fast enough or to
    976 implement flow control. If an application does not process CORE messages
    977 fast enough, CORE will randomly drop messages to not keep a very long
    978 queue in memory.
    979 
    980 Exercise: Start one peer with a new service that has a message handler
    981 and start a second peer that only has your "old" service without message
    982 handlers. Which "connect" handlers are invoked when the two peers are
    983 connected? Why?
    984 
    985 .. _Sending-P2P-Messages:
    986 
    987 Sending P2P Messages
    988 ~~~~~~~~~~~~~~~~~~~~
    989 
    990 You can transmit messages to other peers using the ``mq`` you were given
    991 during the ``connect`` callback. Note that the ``mq`` automatically is
    992 released upon ``disconnect`` and that you must not use it afterwards.
    993 
    994 It is your responsibility to not over-fill the message queue, GNUnet
    995 will send the messages roughly in the order given as soon as possible.
    996 
    997 Exercise: Write a service that upon connect sends messages as fast as
    998 possible to the other peer (the other peer should run a service that
    999 "processes" those messages). How fast is the transmission? Count using
   1000 the STATISTICS service on both ends. Are messages lost? How can you
   1001 transmit messages faster? What happens if you stop the peer that is
   1002 receiving your messages?
   1003 
   1004 .. _End-of-P2P-connections:
   1005 
   1006 End of P2P connections
   1007 ~~~~~~~~~~~~~~~~~~~~~~
   1008 
   1009 If a message handler returns ``GNUNET\_SYSERR``, the remote peer shuts
   1010 down or there is an unrecoverable network disconnection, CORE notifies
   1011 the service that the peer disconnected. After this notification no more
   1012 messages will be received from the peer and the service is no longer
   1013 allowed to send messages to the peer. The disconnect callback looks like
   1014 the following:
   1015 
   1016 .. code-block:: text
   1017 
   1018    void
   1019    disconnects (void *cls,
   1020                 const struct GNUNET_PeerIdentity * peer)
   1021    {
   1022        /* Remove peer's identity from known peers */
   1023        /* Make sure no messages are sent to peer from now on */
   1024    }
   1025 
   1026 Exercise: Fix your service to handle peer disconnects.
   1027 
   1028 .. _Storing-peer_002dspecific-data-using-the-PEERSTORE-service:
   1029 
   1030 Storing peer-specific data using the PEERSTORE service
   1031 ------------------------------------------------------
   1032 
   1033 GNUnet's PEERSTORE service offers a persistorage for arbitrary
   1034 peer-specific data. Other GNUnet services can use the PEERSTORE to
   1035 store, retrieve and monitor data records. Each data record stored with
   1036 PEERSTORE contains the following fields:
   1037 
   1038 -  subsystem: Name of the subsystem responsible for the record.
   1039 
   1040 -  peerid: Identity of the peer this record is related to.
   1041 
   1042 -  key: a key string identifying the record.
   1043 
   1044 -  value: binary record value.
   1045 
   1046 -  expiry: record expiry date.
   1047 
   1048 The first step is to start a connection to the PEERSTORE service:
   1049 
   1050 .. code-block:: text
   1051 
   1052    #include "gnunet_peerstore_service.h"
   1053 
   1054    peerstore_handle = GNUNET_PEERSTORE_connect (cfg);
   1055 
   1056 The service handle ``peerstore_handle`` will be needed for all
   1057 subsequent PEERSTORE operations.
   1058 
   1059 .. _Storing-records:
   1060 
   1061 Storing records
   1062 ~~~~~~~~~~~~~~~
   1063 
   1064 To store a new record, use the following function:
   1065 
   1066 .. code-block:: text
   1067 
   1068    struct GNUNET_PEERSTORE_StoreContext *
   1069    GNUNET_PEERSTORE_store (struct GNUNET_PEERSTORE_Handle *h,
   1070                            const char *sub_system,
   1071                            const struct GNUNET_PeerIdentity *peer,
   1072                            const char *key,
   1073                            const void *value,
   1074                            size_t size,
   1075                            struct GNUNET_TIME_Absolute expiry,
   1076                            enum GNUNET_PEERSTORE_StoreOption options,
   1077                            GNUNET_PEERSTORE_Continuation cont,
   1078                            void *cont_cls);
   1079 
   1080 The ``options`` parameter can either be
   1081 ``GNUNET_PEERSTORE_STOREOPTION_MULTIPLE`` which means that multiple
   1082 values can be stored under the same key combination (subsystem, peerid,
   1083 key), or ``GNUNET_PEERSTORE_STOREOPTION_REPLACE`` which means that
   1084 PEERSTORE will replace any existing values under the given key
   1085 combination (subsystem, peerid, key) with the new given value.
   1086 
   1087 The continuation function ``cont`` will be called after the store
   1088 request is successfully sent to the PEERSTORE service. This does not
   1089 guarantee that the record is successfully stored, only that it was
   1090 received by the service.
   1091 
   1092 The ``GNUNET_PEERSTORE_store`` function returns a handle to the store
   1093 operation. This handle can be used to cancel the store operation only
   1094 before the continuation function is called:
   1095 
   1096 .. code-block:: text
   1097 
   1098    void
   1099    GNUNET_PEERSTORE_store_cancel (struct GNUNET_PEERSTORE_StoreContext
   1100                                   *sc);
   1101 
   1102 .. _Retrieving-records:
   1103 
   1104 Retrieving records
   1105 ~~~~~~~~~~~~~~~~~~
   1106 
   1107 To retrieve stored records, use the following function:
   1108 
   1109 .. code-block:: text
   1110 
   1111    struct GNUNET_PEERSTORE_IterateContext *
   1112    GNUNET_PEERSTORE_iterate (struct GNUNET_PEERSTORE_Handle *h,
   1113                              const char *sub_system,
   1114                              const struct GNUNET_PeerIdentity *peer,
   1115                              const char *key,
   1116                              GNUNET_PEERSTORE_Processor callback,
   1117                              void *callback_cls);
   1118 
   1119 The values of ``peer`` and ``key`` can be ``NULL``. This allows the
   1120 iteration over values stored under any of the following key
   1121 combinations:
   1122 
   1123 -  (subsystem)
   1124 
   1125 -  (subsystem, peerid)
   1126 
   1127 -  (subsystem, key)
   1128 
   1129 -  (subsystem, peerid, key)
   1130 
   1131 The ``callback`` function will be called once with each retrieved record
   1132 and once more with a ``NULL`` record to signal the end of results.
   1133 
   1134 The ``GNUNET_PEERSTORE_iterate`` function returns a handle to the
   1135 iterate operation. This handle can be used to cancel the iterate
   1136 operation only before the callback function is called with a ``NULL``
   1137 record.
   1138 
   1139 .. _Monitoring-records:
   1140 
   1141 Monitoring records
   1142 ~~~~~~~~~~~~~~~~~~
   1143 
   1144 PEERSTORE offers the functionality of monitoring for new records stored
   1145 under a specific key combination (subsystem, peerid, key). To start the
   1146 monitoring, use the following function:
   1147 
   1148 .. code-block:: text
   1149 
   1150    struct GNUNET_PEERSTORE_WatchContext *
   1151    GNUNET_PEERSTORE_watch (struct GNUNET_PEERSTORE_Handle *h,
   1152                            const char *sub_system,
   1153                            const struct GNUNET_PeerIdentity *peer,
   1154                            const char *key,
   1155                            GNUNET_PEERSTORE_Processor callback,
   1156                            void *callback_cls);
   1157 
   1158 Whenever a new record is stored under the given key combination, the
   1159 ``callback`` function will be called with this new record. This will
   1160 continue until the connection to the PEERSTORE service is broken or the
   1161 watch operation is canceled:
   1162 
   1163 .. code-block:: text
   1164 
   1165    void
   1166    GNUNET_PEERSTORE_watch_cancel (struct GNUNET_PEERSTORE_WatchContext
   1167                                   *wc);
   1168 
   1169 .. _Disconnecting-from-PEERSTORE:
   1170 
   1171 Disconnecting from PEERSTORE
   1172 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   1173 
   1174 When the connection to the PEERSTORE service is no longer needed,
   1175 disconnect using the following function:
   1176 
   1177 .. code-block:: text
   1178 
   1179    void
   1180    GNUNET_PEERSTORE_disconnect (struct GNUNET_PEERSTORE_Handle *h,
   1181                                 int sync_first);
   1182 
   1183 If the ``sync_first`` flag is set to ``GNUNET_YES``, the API will delay
   1184 the disconnection until all store requests are received by the PEERSTORE
   1185 service. Otherwise, it will disconnect immediately.
   1186 
   1187 .. _Using-the-DHT:
   1188 
   1189 Using the DHT
   1190 -------------
   1191 
   1192 The DHT allows to store data so other peers in the P2P network can
   1193 access it and retrieve data stored by any peers in the network. This
   1194 section will explain how to use the DHT. Of course, the first thing to
   1195 do is to connect to the DHT service:
   1196 
   1197 .. code-block:: text
   1198 
   1199    dht_handle = GNUNET_DHT_connect (cfg, parallel_requests);
   1200 
   1201 The second parameter indicates how many requests in parallel to expect.
   1202 It is not a hard limit, but a good approximation will make the DHT more
   1203 efficient.
   1204 
   1205 .. _Storing-data-in-the-DHT:
   1206 
   1207 Storing data in the DHT
   1208 ~~~~~~~~~~~~~~~~~~~~~~~
   1209 
   1210 Since the DHT is a dynamic environment (peers join and leave frequently)
   1211 the data that we put in the DHT does not stay there indefinitely. It is
   1212 important to "refresh" the data periodically by simply storing it again,
   1213 in order to make sure other peers can access it.
   1214 
   1215 The put API call offers a callback to signal that the PUT request has
   1216 been sent. This does not guarantee that the data is accessible to others
   1217 peers, or even that is has been stored, only that the service has
   1218 requested to a neighboring peer the retransmission of the PUT request
   1219 towards its final destination. Currently there is no feedback about
   1220 whether or not the data has been successfully stored or where it has
   1221 been stored. In order to improve the availablilty of the data and to
   1222 compensate for possible errors, peers leaving and other unfavorable
   1223 events, just make several PUT requests!
   1224 
   1225 .. code-block:: text
   1226 
   1227    message_sent_cont (void *cls,
   1228                       const struct GNUNET_SCHEDULER_TaskContext *tc)
   1229    {
   1230      // Request has left local node
   1231    }
   1232 
   1233    struct GNUNET_DHT_PutHandle *
   1234    GNUNET_DHT_put (struct GNUNET_DHT_Handle *handle,
   1235                    const struct GNUNET_HashCode *key,
   1236                    uint32_t desired_replication_level,
   1237                    enum GNUNET_DHT_RouteOption options,
   1238                    enum GNUNET_BLOCK_Type type,
   1239                    size_t size,
   1240                    const void *data,
   1241                    struct GNUNET_TIME_Absolute exp,
   1242                    struct GNUNET_TIME_Relative timeout,
   1243                    GNUNET_DHT_PutContinuation cont, void *cont_cls)
   1244 
   1245 Exercise: Store a value in the DHT periodically to make sure it is
   1246 available over time. You might consider using the function
   1247 ``GNUNET\_SCHEDULER\_add\_delayed`` and call ``GNUNET\_DHT\_put`` from
   1248 inside a helper function.
   1249 
   1250 .. _Obtaining-data-from-the-DHT:
   1251 
   1252 Obtaining data from the DHT
   1253 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
   1254 
   1255 As we saw in the previous example, the DHT works in an asynchronous
   1256 mode. Each request to the DHT is executed "in the background" and the
   1257 API calls return immediately. In order to receive results from the DHT,
   1258 the API provides a callback. Once started, the request runs in the
   1259 service, the service will try to get as many results as possible
   1260 (filtering out duplicates) until the timeout expires or we explicitly
   1261 stop the request. It is possible to give a "forever" timeout with
   1262 ``GNUNET\_TIME\_UNIT\_FOREVER\_REL``.
   1263 
   1264 If we give a route option ``GNUNET\_DHT\_RO\_RECORD\_ROUTE`` the
   1265 callback will get a list of all the peers the data has travelled, both
   1266 on the PUT path and on the GET path.
   1267 
   1268 .. code-block:: text
   1269 
   1270    static void
   1271    get_result_iterator (void *cls, struct GNUNET_TIME_Absolute expiration,
   1272                         const struct GNUNET_HashCode *key,
   1273                         const struct GNUNET_PeerIdentity *get_path,
   1274                         unsigned int get_path_length,
   1275                         const struct GNUNET_PeerIdentity *put_path,
   1276                         unsigned int put_path_length,
   1277                         enum GNUNET_BLOCK_Type type, size_t size,
   1278                         const void *data)
   1279    {
   1280      // Optionally:
   1281      GNUNET_DHT_get_stop (get_handle);
   1282    }
   1283 
   1284    get_handle =
   1285          GNUNET_DHT_get_start (dht_handle,
   1286                                block_type,
   1287                                &key,
   1288                                replication,
   1289                                GNUNET_DHT_RO_NONE,
   1290                                NULL,
   1291                                0,
   1292                                &get_result_iterator,
   1293                                cls)
   1294 
   1295 Exercise: Store a value in the DHT and after a while retrieve it. Show
   1296 the IDs of all the peers the requests have gone through. In order to
   1297 convert a peer ID to a string, use the function ``GNUNET\_i2s``. Pay
   1298 attention to the route option parameters in both calls!
   1299 
   1300 .. _Implementing-a-block-plugin:
   1301 
   1302 Implementing a block plugin
   1303 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
   1304 
   1305 In order to store data in the DHT, it is necessary to provide a block
   1306 plugin. The DHT uses the block plugin to ensure that only well-formed
   1307 requests and replies are transmitted over the network.
   1308 
   1309 The block plugin should be put in a file ``plugin\_block\_SERVICE.c`` in
   1310 the service's respective directory. The mandatory functions that need to
   1311 be implemented for a block plugin are described in the following
   1312 sections.
   1313 
   1314 .. _Validating-requests-and-replies:
   1315 
   1316 Validating requests and replies
   1317 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   1318 
   1319 The evaluate function should validate a reply or a request. It returns a
   1320 ``GNUNET\_BLOCK\_EvaluationResult``, which is an enumeration. All
   1321 possible answers are in ``gnunet\_block\_lib.h``. The function will be
   1322 called with a ``reply\_block`` argument of ``NULL`` for requests. Note
   1323 that depending on how ``evaluate`` is called, only some of the possible
   1324 return values are valid. The specific meaning of the ``xquery`` argument
   1325 is application-specific. Applications that do not use an extended query
   1326 should check that the ``xquery\_size`` is zero. The block group is
   1327 typically used to filter duplicate replies.
   1328 
   1329 .. code-block:: text
   1330 
   1331    static enum GNUNET_BLOCK_EvaluationResult
   1332    block_plugin_SERVICE_evaluate (void *cls,
   1333                                  enum GNUNET_BLOCK_Type type,
   1334                                  struct GNUNET_BlockGroup *bg,
   1335                                  const GNUNET_HashCode *query,
   1336                                  const void *xquery,
   1337                                  size_t xquery_size,
   1338                                  const void *reply_block,
   1339                                  size_t reply_block_size)
   1340    {
   1341      // Verify type, block and bg
   1342    }
   1343 
   1344 Note that it is mandatory to detect duplicate replies in this function
   1345 and return the respective status code. Duplicate detection is typically
   1346 done using the Bloom filter block group provided by
   1347 ``libgnunetblockgroup.so``. Failure to do so may cause replies to circle
   1348 in the network.
   1349 
   1350 .. _Deriving-a-key-from-a-reply:
   1351 
   1352 Deriving a key from a reply
   1353 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
   1354 
   1355 The DHT can operate more efficiently if it is possible to derive a key
   1356 from the value of the corresponding block. The ``get\_key`` function is
   1357 used to obtain the key of a block --- for example, by means of hashing.
   1358 If deriving the key is not possible, the function should simply return
   1359 ``GNUNET\_SYSERR`` (the DHT will still work just fine with such blocks).
   1360 
   1361 .. code-block:: text
   1362 
   1363    static int
   1364    block_plugin_SERVICE_get_key (void *cls, enum GNUNET_BLOCK_Type type,
   1365                                 const void *block, size_t block_size,
   1366                                 struct GNUNET_HashCode *key)
   1367    {
   1368      // Store the key in the key argument, return GNUNET_OK on success.
   1369    }
   1370 
   1371 .. _Initialization-of-the-plugin:
   1372 
   1373 Initialization of the plugin
   1374 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   1375 
   1376 The plugin is realized as a shared C library. The library must export an
   1377 initialization function which should initialize the plugin. The
   1378 initialization function specifies what block types the plugin cares
   1379 about and returns a struct with the functions that are to be used for
   1380 validation and obtaining keys (the ones just defined above).
   1381 
   1382 .. code-block:: text
   1383 
   1384    void *
   1385    libgnunet_plugin_block_SERVICE_init (void *cls)
   1386    {
   1387      static enum GNUNET_BLOCK_Type types[] =
   1388      {
   1389        GNUNET_BLOCK_TYPE_SERVICE_BLOCKYPE,
   1390        GNUNET_BLOCK_TYPE_ANY
   1391      };
   1392      struct GNUNET_BLOCK_PluginFunctions *api;
   1393 
   1394      api = GNUNET_new (struct GNUNET_BLOCK_PluginFunctions);
   1395      api->evaluate = &block_plugin_SERICE_evaluate;
   1396      api->get_key = &block_plugin_SERVICE_get_key;
   1397      api->types = types;
   1398      return api;
   1399    }
   1400 
   1401 .. _Shutdown-of-the-plugin:
   1402 
   1403 Shutdown of the plugin
   1404 ^^^^^^^^^^^^^^^^^^^^^^
   1405 
   1406 Following GNUnet's general plugin API concept, the plugin must export a
   1407 second function for cleaning up. It usually does very little.
   1408 
   1409 .. code-block:: text
   1410 
   1411    void *
   1412    libgnunet_plugin_block_SERVICE_done (void *cls)
   1413    {
   1414      struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
   1415 
   1416      GNUNET_free (api);
   1417      return NULL;
   1418    }
   1419 
   1420 .. _Integration-of-the-plugin-with-the-build-system:
   1421 
   1422 Integration of the plugin with the build system
   1423 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   1424 
   1425 In order to compile the plugin, the ``Makefile.am`` file for the service
   1426 SERVICE should contain a rule similar to this:
   1427 
   1428 .. code-block:: text
   1429 
   1430      plugindir = $(libdir)/gnunet
   1431 
   1432      plugin_LTLIBRARIES = \
   1433              libgnunet_plugin_block_ext.la
   1434      libgnunet_plugin_block_ext_la_SOURCES = \
   1435              plugin_block_ext.c
   1436      libgnunet_plugin_block_ext_la_LIBADD = \
   1437              $(prefix)/lib/libgnunethello.la \
   1438              $(prefix)/lib/libgnunetblock.la \
   1439              $(prefix)/lib/libgnunetutil.la
   1440      libgnunet_plugin_block_ext_la_LDFLAGS = \
   1441              $(GN_PLUGIN_LDFLAGS)
   1442      libgnunet_plugin_block_ext_la_DEPENDENCIES = \
   1443              $(prefix)/lib/libgnunetblock.la
   1444 
   1445 Exercise: Write a block plugin that accepts all queries and all replies
   1446 but prints information about queries and replies when the respective
   1447 validation hooks are called.
   1448 
   1449 .. _Monitoring-the-DHT:
   1450 
   1451 Monitoring the DHT
   1452 ~~~~~~~~~~~~~~~~~~
   1453 
   1454 It is possible to monitor the functioning of the local DHT service. When
   1455 monitoring the DHT, the service will alert the monitoring program of any
   1456 events, both started locally or received for routing from another peer.
   1457 The are three different types of events possible: a GET request, a PUT
   1458 request or a response (a reply to a GET).
   1459 
   1460 Since the different events have different associated data, the API gets
   1461 3 different callbacks (one for each message type) and optional type and
   1462 key parameters, to allow for filtering of messages. When an event
   1463 happens, the appropriate callback is called with all the information
   1464 about the event.
   1465 
   1466 .. code-block:: text
   1467 
   1468    static void
   1469    get_callback (void *cls,
   1470                  enum GNUNET_DHT_RouteOption options,
   1471                  enum GNUNET_BLOCK_Type type,
   1472                  uint32_t hop_count,
   1473                  uint32_t desired_replication_level,
   1474                  unsigned int path_length,
   1475                  const struct GNUNET_PeerIdentity *path,
   1476                  const struct GNUNET_HashCode * key)
   1477    {
   1478    }
   1479 
   1480 
   1481    static void
   1482    get_resp_callback (void *cls,
   1483                       enum GNUNET_BLOCK_Type type,
   1484                       const struct GNUNET_PeerIdentity *get_path,
   1485                       unsigned int get_path_length,
   1486                       const struct GNUNET_PeerIdentity *put_path,
   1487                       unsigned int put_path_length,
   1488                       struct GNUNET_TIME_Absolute exp,
   1489                       const struct GNUNET_HashCode * key,
   1490                       const void *data,
   1491                       size_t size)
   1492    {
   1493    }
   1494 
   1495 
   1496    static void
   1497    put_callback (void *cls,
   1498                  enum GNUNET_DHT_RouteOption options,
   1499                  enum GNUNET_BLOCK_Type type,
   1500                  uint32_t hop_count,
   1501                  uint32_t desired_replication_level,
   1502                  unsigned int path_length,
   1503                  const struct GNUNET_PeerIdentity *path,
   1504                  struct GNUNET_TIME_Absolute exp,
   1505                  const struct GNUNET_HashCode * key,
   1506                  const void *data,
   1507                  size_t size)
   1508    {
   1509    }
   1510 
   1511 
   1512    monitor_handle = GNUNET_DHT_monitor_start (dht_handle,
   1513                                              block_type,
   1514                                              key,
   1515                                              &get_callback,
   1516                                              &get_resp_callback,
   1517                                              &put_callback,
   1518                                              cls);
   1519 
   1520 .. _Debugging-with-gnunet_002darm:
   1521 
   1522 Debugging with gnunet-arm
   1523 -------------------------
   1524 
   1525 Even if services are managed by ``gnunet-arm``, you can start them with
   1526 ``gdb`` or ``valgrind``. For example, you could add the following lines
   1527 to your configuration file to start the DHT service in a ``gdb`` session
   1528 in a fresh ``xterm``:
   1529 
   1530 .. code-block:: text
   1531 
   1532    [dht]
   1533    PREFIX=xterm -e gdb --args
   1534 
   1535 Alternatively, you can stop a service that was started via ARM and run
   1536 it manually:
   1537 
   1538 .. code-block:: text
   1539 
   1540    $ gnunet-arm -k dht
   1541    $ gdb --args gnunet-service-dht -L DEBUG
   1542    $ valgrind gnunet-service-dht -L DEBUG
   1543 
   1544 Assuming other services are well-written, they will automatically
   1545 re-integrate the restarted service with the peer.
   1546 
   1547 GNUnet provides a powerful logging mechanism providing log levels
   1548 ``ERROR``, ``WARNING``, ``INFO`` and ``DEBUG``. The current log level is
   1549 configured using the ``$GNUNET_FORCE_LOG`` environmental variable. The
   1550 ``DEBUG`` level is only available if ``--enable-logging=verbose`` was
   1551 used when running ``configure``. More details about logging can be found
   1552 under https://docs.gnunet.org/#Logging.
   1553 
   1554 You should also probably enable the creation of core files, by setting
   1555 ``ulimit``, and echo'ing ``1`` into
   1556 ``/proc/sys/kernel/core\_uses\_pid``. Then you can investigate the core
   1557 dumps with ``gdb``, which is often the fastest method to find simple
   1558 errors.
   1559 
   1560 Exercise: Add a memory leak to your service and obtain a trace pointing
   1561 to the leak using ``valgrind`` while running the service from
   1562 ``gnunet-service-arm``.
   1563 
   1564 .. _GNU-Free-Documentation-License:
   1565 
   1566 GNU Free Documentation License
   1567 ==============================
   1568 
   1569 license, GNU Free Documentation License
   1570 Version 1.3, 3 November 2008
   1571 
   1572 .. code-block:: text
   1573 
   1574    Copyright © 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc.
   1575    http://fsf.org/
   1576 
   1577    Everyone is permitted to copy and distribute verbatim copies
   1578    of this license document, but changing it is not allowed.
   1579 
   1580 1.  PREAMBLE
   1581 
   1582     The purpose of this License is to make a manual, textbook, or other
   1583     functional and useful document free in the sense of freedom: to
   1584     assure everyone the effective freedom to copy and redistribute it,
   1585     with or without modifying it, either commercially or
   1586     noncommercially. Secondarily, this License preserves for the author
   1587     and publisher a way to get credit for their work, while not being
   1588     considered responsible for modifications made by others.
   1589 
   1590     This License is a kind of "copyleft", which means that derivative
   1591     works of the document must themselves be free in the same sense. It
   1592     complements the GNU General Public License, which is a copyleft
   1593     license designed for free software.
   1594 
   1595     We have designed this License in order to use it for manuals for
   1596     free software, because free software needs free documentation: a
   1597     free program should come with manuals providing the same freedoms
   1598     that the software does. But this License is not limited to software
   1599     manuals; it can be used for any textual work, regardless of subject
   1600     matter or whether it is published as a printed book. We recommend
   1601     this License principally for works whose purpose is instruction or
   1602     reference.
   1603 
   1604 2.  APPLICABILITY AND DEFINITIONS
   1605 
   1606     This License applies to any manual or other work, in any medium,
   1607     that contains a notice placed by the copyright holder saying it can
   1608     be distributed under the terms of this License. Such a notice grants
   1609     a world-wide, royalty-free license, unlimited in duration, to use
   1610     that work under the conditions stated herein. The "Document", below,
   1611     refers to any such manual or work. Any member of the public is a
   1612     licensee, and is addressed as "you". You accept the license if you
   1613     copy, modify or distribute the work in a way requiring permission
   1614     under copyright law.
   1615 
   1616     A "Modified Version" of the Document means any work containing the
   1617     Document or a portion of it, either copied verbatim, or with
   1618     modifications and/or translated into another language.
   1619 
   1620     A "Secondary Section" is a named appendix or a front-matter section
   1621     of the Document that deals exclusively with the relationship of the
   1622     publishers or authors of the Document to the Document's overall
   1623     subject (or to related matters) and contains nothing that could fall
   1624     directly within that overall subject. (Thus, if the Document is in
   1625     part a textbook of mathematics, a Secondary Section may not explain
   1626     any mathematics.) The relationship could be a matter of historical
   1627     connection with the subject or with related matters, or of legal,
   1628     commercial, philosophical, ethical or political position regarding
   1629     them.
   1630 
   1631     The "Invariant Sections" are certain Secondary Sections whose titles
   1632     are designated, as being those of Invariant Sections, in the notice
   1633     that says that the Document is released under this License. If a
   1634     section does not fit the above definition of Secondary then it is
   1635     not allowed to be designated as Invariant. The Document may contain
   1636     zero Invariant Sections. If the Document does not identify any
   1637     Invariant Sections then there are none.
   1638 
   1639     The "Cover Texts" are certain short passages of text that are
   1640     listed, as Front-Cover Texts or Back-Cover Texts, in the notice that
   1641     says that the Document is released under this License. A Front-Cover
   1642     Text may be at most 5 words, and a Back-Cover Text may be at most 25
   1643     words.
   1644 
   1645     A "Transparent" copy of the Document means a machine-readable copy,
   1646     represented in a format whose specification is available to the
   1647     general public, that is suitable for revising the document
   1648     straightforwardly with generic text editors or (for images composed
   1649     of pixels) generic paint programs or (for drawings) some widely
   1650     available drawing editor, and that is suitable for input to text
   1651     formatters or for automatic translation to a variety of formats
   1652     suitable for input to text formatters. A copy made in an otherwise
   1653     Transparent file format whose markup, or absence of markup, has been
   1654     arranged to thwart or discourage subsequent modification by readers
   1655     is not Transparent. An image format is not Transparent if used for
   1656     any substantial amount of text. A copy that is not "Transparent" is
   1657     called "Opaque".
   1658 
   1659     Examples of suitable formats for Transparent copies include plain
   1660     ASCII without markup, Texinfo input format, LaTeX input format, SGML
   1661     or XML using a publicly available DTD, and standard-conforming
   1662     simple HTML, PostScript or PDF designed for human modification.
   1663     Examples of transparent image formats include PNG, XCF and JPG.
   1664     Opaque formats include proprietary formats that can be read and
   1665     edited only by proprietary word processors, SGML or XML for which
   1666     the DTD and/or processing tools are not generally available, and the
   1667     machine-generated HTML, PostScript or PDF produced by some word
   1668     processors for output purposes only.
   1669 
   1670     The "Title Page" means, for a printed book, the title page itself,
   1671     plus such following pages as are needed to hold, legibly, the
   1672     material this License requires to appear in the title page. For
   1673     works in formats which do not have any title page as such, "Title
   1674     Page" means the text near the most prominent appearance of the
   1675     work's title, preceding the beginning of the body of the text.
   1676 
   1677     The "publisher" means any person or entity that distributes copies
   1678     of the Document to the public.
   1679 
   1680     A section "Entitled XYZ" means a named subunit of the Document whose
   1681     title either is precisely XYZ or contains XYZ in parentheses
   1682     following text that translates XYZ in another language. (Here XYZ
   1683     stands for a specific section name mentioned below, such as
   1684     "Acknowledgements", "Dedications", "Endorsements", or "History".) To
   1685     "Preserve the Title" of such a section when you modify the Document
   1686     means that it remains a section "Entitled XYZ" according to this
   1687     definition.
   1688 
   1689     The Document may include Warranty Disclaimers next to the notice
   1690     which states that this License applies to the Document. These
   1691     Warranty Disclaimers are considered to be included by reference in
   1692     this License, but only as regards disclaiming warranties: any other
   1693     implication that these Warranty Disclaimers may have is void and has
   1694     no effect on the meaning of this License.
   1695 
   1696 3.  VERBATIM COPYING
   1697 
   1698     You may copy and distribute the Document in any medium, either
   1699     commercially or noncommercially, provided that this License, the
   1700     copyright notices, and the license notice saying this License
   1701     applies to the Document are reproduced in all copies, and that you
   1702     add no other conditions whatsoever to those of this License. You may
   1703     not use technical measures to obstruct or control the reading or
   1704     further copying of the copies you make or distribute. However, you
   1705     may accept compensation in exchange for copies. If you distribute a
   1706     large enough number of copies you must also follow the conditions in
   1707     section 3.
   1708 
   1709     You may also lend copies, under the same conditions stated above,
   1710     and you may publicly display copies.
   1711 
   1712 4.  COPYING IN QUANTITY
   1713 
   1714     If you publish printed copies (or copies in media that commonly have
   1715     printed covers) of the Document, numbering more than 100, and the
   1716     Document's license notice requires Cover Texts, you must enclose the
   1717     copies in covers that carry, clearly and legibly, all these Cover
   1718     Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
   1719     the back cover. Both covers must also clearly and legibly identify
   1720     you as the publisher of these copies. The front cover must present
   1721     the full title with all words of the title equally prominent and
   1722     visible. You may add other material on the covers in addition.
   1723     Copying with changes limited to the covers, as long as they preserve
   1724     the title of the Document and satisfy these conditions, can be
   1725     treated as verbatim copying in other respects.
   1726 
   1727     If the required texts for either cover are too voluminous to fit
   1728     legibly, you should put the first ones listed (as many as fit
   1729     reasonably) on the actual cover, and continue the rest onto adjacent
   1730     pages.
   1731 
   1732     If you publish or distribute Opaque copies of the Document numbering
   1733     more than 100, you must either include a machine-readable
   1734     Transparent copy along with each Opaque copy, or state in or with
   1735     each Opaque copy a computer-network location from which the general
   1736     network-using public has access to download using public-standard
   1737     network protocols a complete Transparent copy of the Document, free
   1738     of added material. If you use the latter option, you must take
   1739     reasonably prudent steps, when you begin distribution of Opaque
   1740     copies in quantity, to ensure that this Transparent copy will remain
   1741     thus accessible at the stated location until at least one year after
   1742     the last time you distribute an Opaque copy (directly or through
   1743     your agents or retailers) of that edition to the public.
   1744 
   1745     It is requested, but not required, that you contact the authors of
   1746     the Document well before redistributing any large number of copies,
   1747     to give them a chance to provide you with an updated version of the
   1748     Document.
   1749 
   1750 5.  MODIFICATIONS
   1751 
   1752     You may copy and distribute a Modified Version of the Document under
   1753     the conditions of sections 2 and 3 above, provided that you release
   1754     the Modified Version under precisely this License, with the Modified
   1755     Version filling the role of the Document, thus licensing
   1756     distribution and modification of the Modified Version to whoever
   1757     possesses a copy of it. In addition, you must do these things in the
   1758     Modified Version:
   1759 
   1760     A. Use in the Title Page (and on the covers, if any) a title
   1761        distinct from that of the Document, and from those of previous
   1762        versions (which should, if there were any, be listed in the
   1763        History section of the Document). You may use the same title as a
   1764        previous version if the original publisher of that version gives
   1765        permission.
   1766 
   1767     B. List on the Title Page, as authors, one or more persons or
   1768        entities responsible for authorship of the modifications in the
   1769        Modified Version, together with at least five of the principal
   1770        authors of the Document (all of its principal authors, if it has
   1771        fewer than five), unless they release you from this requirement.
   1772 
   1773     C. State on the Title page the name of the publisher of the Modified
   1774        Version, as the publisher.
   1775 
   1776     D. Preserve all the copyright notices of the Document.
   1777 
   1778     E. Add an appropriate copyright notice for your modifications
   1779        adjacent to the other copyright notices.
   1780 
   1781     F. Include, immediately after the copyright notices, a license
   1782        notice giving the public permission to use the Modified Version
   1783        under the terms of this License, in the form shown in the
   1784        Addendum below.
   1785 
   1786     G. Preserve in that license notice the full lists of Invariant
   1787        Sections and required Cover Texts given in the Document's license
   1788        notice.
   1789 
   1790     H. Include an unaltered copy of this License.
   1791 
   1792     I. Preserve the section Entitled "History", Preserve its Title, and
   1793        add to it an item stating at least the title, year, new authors,
   1794        and publisher of the Modified Version as given on the Title Page.
   1795        If there is no section Entitled "History" in the Document, create
   1796        one stating the title, year, authors, and publisher of the
   1797        Document as given on its Title Page, then add an item describing
   1798        the Modified Version as stated in the previous sentence.
   1799 
   1800     J. Preserve the network location, if any, given in the Document for
   1801        public access to a Transparent copy of the Document, and likewise
   1802        the network locations given in the Document for previous versions
   1803        it was based on. These may be placed in the "History" section.
   1804        You may omit a network location for a work that was published at
   1805        least four years before the Document itself, or if the original
   1806        publisher of the version it refers to gives permission.
   1807 
   1808     K. For any section Entitled "Acknowledgements" or "Dedications",
   1809        Preserve the Title of the section, and preserve in the section
   1810        all the substance and tone of each of the contributor
   1811        acknowledgements and/or dedications given therein.
   1812 
   1813     L. Preserve all the Invariant Sections of the Document, unaltered in
   1814        their text and in their titles. Section numbers or the equivalent
   1815        are not considered part of the section titles.
   1816 
   1817     M. Delete any section Entitled "Endorsements". Such a section may
   1818        not be included in the Modified Version.
   1819 
   1820     N. Do not retitle any existing section to be Entitled "Endorsements"
   1821        or to conflict in title with any Invariant Section.
   1822 
   1823     O. Preserve any Warranty Disclaimers.
   1824 
   1825     If the Modified Version includes new front-matter sections or
   1826     appendices that qualify as Secondary Sections and contain no
   1827     material copied from the Document, you may at your option designate
   1828     some or all of these sections as invariant. To do this, add their
   1829     titles to the list of Invariant Sections in the Modified Version's
   1830     license notice. These titles must be distinct from any other section
   1831     titles.
   1832 
   1833     You may add a section Entitled "Endorsements", provided it contains
   1834     nothing but endorsements of your Modified Version by various
   1835     parties---for example, statements of peer review or that the text
   1836     has been approved by an organization as the authoritative definition
   1837     of a standard.
   1838 
   1839     You may add a passage of up to five words as a Front-Cover Text, and
   1840     a passage of up to 25 words as a Back-Cover Text, to the end of the
   1841     list of Cover Texts in the Modified Version. Only one passage of
   1842     Front-Cover Text and one of Back-Cover Text may be added by (or
   1843     through arrangements made by) any one entity. If the Document
   1844     already includes a cover text for the same cover, previously added
   1845     by you or by arrangement made by the same entity you are acting on
   1846     behalf of, you may not add another; but you may replace the old one,
   1847     on explicit permission from the previous publisher that added the
   1848     old one.
   1849 
   1850     The author(s) and publisher(s) of the Document do not by this
   1851     License give permission to use their names for publicity for or to
   1852     assert or imply endorsement of any Modified Version.
   1853 
   1854 6.  COMBINING DOCUMENTS
   1855 
   1856     You may combine the Document with other documents released under
   1857     this License, under the terms defined in section 4 above for
   1858     modified versions, provided that you include in the combination all
   1859     of the Invariant Sections of all of the original documents,
   1860     unmodified, and list them all as Invariant Sections of your combined
   1861     work in its license notice, and that you preserve all their Warranty
   1862     Disclaimers.
   1863 
   1864     The combined work need only contain one copy of this License, and
   1865     multiple identical Invariant Sections may be replaced with a single
   1866     copy. If there are multiple Invariant Sections with the same name
   1867     but different contents, make the title of each such section unique
   1868     by adding at the end of it, in parentheses, the name of the original
   1869     author or publisher of that section if known, or else a unique
   1870     number. Make the same adjustment to the section titles in the list
   1871     of Invariant Sections in the license notice of the combined work.
   1872 
   1873     In the combination, you must combine any sections Entitled "History"
   1874     in the various original documents, forming one section Entitled
   1875     "History"; likewise combine any sections Entitled
   1876     "Acknowledgements", and any sections Entitled "Dedications". You
   1877     must delete all sections Entitled "Endorsements."
   1878 
   1879 7.  COLLECTIONS OF DOCUMENTS
   1880 
   1881     You may make a collection consisting of the Document and other
   1882     documents released under this License, and replace the individual
   1883     copies of this License in the various documents with a single copy
   1884     that is included in the collection, provided that you follow the
   1885     rules of this License for verbatim copying of each of the documents
   1886     in all other respects.
   1887 
   1888     You may extract a single document from such a collection, and
   1889     distribute it individually under this License, provided you insert a
   1890     copy of this License into the extracted document, and follow this
   1891     License in all other respects regarding verbatim copying of that
   1892     document.
   1893 
   1894 8.  AGGREGATION WITH INDEPENDENT WORKS
   1895 
   1896     A compilation of the Document or its derivatives with other separate
   1897     and independent documents or works, in or on a volume of a storage
   1898     or distribution medium, is called an "aggregate" if the copyright
   1899     resulting from the compilation is not used to limit the legal rights
   1900     of the compilation's users beyond what the individual works permit.
   1901     When the Document is included in an aggregate, this License does not
   1902     apply to the other works in the aggregate which are not themselves
   1903     derivative works of the Document.
   1904 
   1905     If the Cover Text requirement of section 3 is applicable to these
   1906     copies of the Document, then if the Document is less than one half
   1907     of the entire aggregate, the Document's Cover Texts may be placed on
   1908     covers that bracket the Document within the aggregate, or the
   1909     electronic equivalent of covers if the Document is in electronic
   1910     form. Otherwise they must appear on printed covers that bracket the
   1911     whole aggregate.
   1912 
   1913 9.  TRANSLATION
   1914 
   1915     Translation is considered a kind of modification, so you may
   1916     distribute translations of the Document under the terms of section
   1917     4. Replacing Invariant Sections with translations requires special
   1918     permission from their copyright holders, but you may include
   1919     translations of some or all Invariant Sections in addition to the
   1920     original versions of these Invariant Sections. You may include a
   1921     translation of this License, and all the license notices in the
   1922     Document, and any Warranty Disclaimers, provided that you also
   1923     include the original English version of this License and the
   1924     original versions of those notices and disclaimers. In case of a
   1925     disagreement between the translation and the original version of
   1926     this License or a notice or disclaimer, the original version will
   1927     prevail.
   1928 
   1929     If a section in the Document is Entitled "Acknowledgements",
   1930     "Dedications", or "History", the requirement (section 4) to Preserve
   1931     its Title (section 1) will typically require changing the actual
   1932     title.
   1933 
   1934 10. TERMINATION
   1935 
   1936     You may not copy, modify, sublicense, or distribute the Document
   1937     except as expressly provided under this License. Any attempt
   1938     otherwise to copy, modify, sublicense, or distribute it is void, and
   1939     will automatically terminate your rights under this License.
   1940 
   1941     However, if you cease all violation of this License, then your
   1942     license from a particular copyright holder is reinstated (a)
   1943     provisionally, unless and until the copyright holder explicitly and
   1944     finally terminates your license, and (b) permanently, if the
   1945     copyright holder fails to notify you of the violation by some
   1946     reasonable means prior to 60 days after the cessation.
   1947 
   1948     Moreover, your license from a particular copyright holder is
   1949     reinstated permanently if the copyright holder notifies you of the
   1950     violation by some reasonable means, this is the first time you have
   1951     received notice of violation of this License (for any work) from
   1952     that copyright holder, and you cure the violation prior to 30 days
   1953     after your receipt of the notice.
   1954 
   1955     Termination of your rights under this section does not terminate the
   1956     licenses of parties who have received copies or rights from you
   1957     under this License. If your rights have been terminated and not
   1958     permanently reinstated, receipt of a copy of some or all of the same
   1959     material does not give you any rights to use it.
   1960 
   1961 11. FUTURE REVISIONS OF THIS LICENSE
   1962 
   1963     The Free Software Foundation may publish new, revised versions of
   1964     the GNU Free Documentation License from time to time. Such new
   1965     versions will be similar in spirit to the present version, but may
   1966     differ in detail to address new problems or concerns. See
   1967     http://www.gnu.org/copyleft/.
   1968 
   1969     Each version of the License is given a distinguishing version
   1970     number. If the Document specifies that a particular numbered version
   1971     of this License "or any later version" applies to it, you have the
   1972     option of following the terms and conditions either of that
   1973     specified version or of any later version that has been published
   1974     (not as a draft) by the Free Software Foundation. If the Document
   1975     does not specify a version number of this License, you may choose
   1976     any version ever published (not as a draft) by the Free Software
   1977     Foundation. If the Document specifies that a proxy can decide which
   1978     future versions of this License can be used, that proxy's public
   1979     statement of acceptance of a version permanently authorizes you to
   1980     choose that version for the Document.
   1981 
   1982 12. RELICENSING
   1983 
   1984     "Massive Multiauthor Collaboration Site" (or "MMC Site") means any
   1985     World Wide Web server that publishes copyrightable works and also
   1986     provides prominent facilities for anybody to edit those works. A
   1987     public wiki that anybody can edit is an example of such a server. A
   1988     "Massive Multiauthor Collaboration" (or "MMC") contained in the site
   1989     means any set of copyrightable works thus published on the MMC site.
   1990 
   1991     "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
   1992     license published by Creative Commons Corporation, a not-for-profit
   1993     corporation with a principal place of business in San Francisco,
   1994     California, as well as future copyleft versions of that license
   1995     published by that same organization.
   1996 
   1997     "Incorporate" means to publish or republish a Document, in whole or
   1998     in part, as part of another Document.
   1999 
   2000     An MMC is "eligible for relicensing" if it is licensed under this
   2001     License, and if all works that were first published under this
   2002     License somewhere other than this MMC, and subsequently incorporated
   2003     in whole or in part into the MMC, (1) had no cover texts or
   2004     invariant sections, and (2) were thus incorporated prior to November
   2005     1, 2008.
   2006 
   2007     The operator of an MMC Site may republish an MMC contained in the
   2008     site under CC-BY-SA on the same site at any time before August 1,
   2009     2009, provided the MMC is eligible for relicensing.
   2010 
   2011 **ADDENDUM: How to use this License for your documents**
   2012 
   2013 To use this License in a document you have written, include a copy of
   2014 the License in the document and put the following copyright and license
   2015 notices just after the title page:
   2016 
   2017 .. code-block:: text
   2018 
   2019      Copyright (C)  year  your name.
   2020      Permission is granted to copy, distribute and/or modify this document
   2021      under the terms of the GNU Free Documentation License, Version 1.3
   2022      or any later version published by the Free Software Foundation;
   2023      with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
   2024      Texts.  A copy of the license is included in the section entitled ``GNU
   2025      Free Documentation License''.
   2026 
   2027 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
   2028 replace the "with...Texts." line with this:
   2029 
   2030 .. code-block:: text
   2031 
   2032        with the Invariant Sections being list their titles, with
   2033        the Front-Cover Texts being list, and with the Back-Cover Texts
   2034        being list.
   2035 
   2036 If you have Invariant Sections without Cover Texts, or some other
   2037 combination of the three, merge those two alternatives to suit the
   2038 situation.
   2039 
   2040 If your document contains nontrivial examples of program code, we
   2041 recommend releasing these examples in parallel under your choice of free
   2042 software license, such as the GNU General Public License, to permit
   2043 their use in free software.