=head1 NAME

nbd_connect_uri - connect to NBD URI

=head1 SYNOPSIS

 #include <libnbd.h>

 int nbd_connect_uri (
       struct nbd_handle *h, const char *uri
     );

=head1 DESCRIPTION

Connect (synchronously) to an NBD server
and export by specifying
the NBD URI.  NBD URIs are a standard way to specify a network
block device endpoint, using a syntax like
C<"nbd://example.com"> which is convenient, well defined and
future proof.

This call works by parsing the URI parameter and calling
L<nbd_set_export_name(3)> and L<nbd_set_tls(3)> and other
calls as needed, followed by L<nbd_connect_tcp(3)>,
L<nbd_connect_unix(3)> or L<nbd_connect_vsock(3)>.


This call returns when the connection has been made.  By default,
this proceeds all the way to transmission phase, but
L<nbd_set_opt_mode(3)> can be used for manual control over
option negotiation performed before transmission phase.

=head2 Example URIs supported

=over 4

=item C<nbd://example.com>

Connect over TCP, unencrypted, to C<example.com> port 10809.

=item C<nbds://example.com>

Connect over TCP with TLS, to C<example.com> port 10809.  If
the server does not support TLS then this will fail.

=item C<nbd+unix:///foo?socket=/tmp/nbd.sock>

Connect over the Unix domain socket F</tmp/nbd.sock> to
an NBD server running locally.  The export name is set to C<foo>
(note without any leading C</> character).

=item C<nbds+unix://alice@/?socket=/tmp/nbd.sock&tls-certificates=certs>

Connect over a Unix domain socket, enabling TLS and setting the
path to a directory containing certificates and keys.

=item C<nbd+vsock:///>

In this scenario libnbd is running in a virtual machine.  Connect
over C<AF_VSOCK> to an NBD server running on the hypervisor.

=item C<nbd+ssh://server/>

Connect to remote C<server> using Secure Shell, and tunnel NBD
to an NBD server listening on port 10809.

=back

=head2 NBD URI standard

L<https://github.com/NetworkBlockDevice/nbd/blob/master/doc/uri.md>
documents the NBD URI standard.

In the documentation below, I<Non-standard> indicates features
supported in libnbd which are not a part of the NBD URI standard,
meaning that other NBD URI parsers might not support them or might
implement things differently.

=head2 URI scheme

The scheme is the part before the first C<:>.  The following schemes
are supported in the current version of libnbd:

=over 4

=item C<nbd:>

Connect over TCP without using TLS.

=item C<nbds:>

Connect over TCP.  TLS is required and the connection
will fail if the server does not support TLS.

=item C<nbd+unix:>

=item C<nbds+unix:>

Connect over a Unix domain socket, without or with TLS
respectively.  The C<socket> parameter is required.

=item C<nbd+vsock:>

=item C<nbds+vsock:>

I<Non-standard>

Connect over the C<AF_VSOCK> transport, without or with
TLS respectively. You can use L<nbd_supports_vsock(3)> to
see if this build of libnbd supports C<AF_VSOCK>.

=item C<nbd+ssh:>

=item C<nbds+ssh:>

I<Non-standard, libnbd E<ge> 1.22>

Tunnel NBD over a Secure Shell connection.  This requires
that L<ssh(1)> is installed locally, and that L<nc(1)> (from the
nmap project) is installed on the remote server.

=back

=head2 URI authority

The authority part of the URI C<[username@][servername][:port]>
is parsed depending on the transport.  For TCP it specifies the
server to connect to and optional port number.  For C<+unix>
it should not be present.  For C<+vsock> the server name is the
numeric CID (eg. C<2> to connect to the host), and the optional
port number may be present.  For C<+ssh> the Secure Shell server
and optional port.  If the C<username> is present it
is used for TLS authentication or the SSH username.

=head2 URI export name

For all transports, an export name may be present, parsed in
accordance with the NBD URI specification.  Note that the initial
C</> character is not part of the export name:

 URI                    export name
 nbd://localhost/       ""        (empty string)
 nbd://localhost/export "export"

It is possible to override the export name programmatically
by using L<nbd_set_opt_mode(3)> to enable option mode,
then using L<nbd_set_export_name(3)> and L<nbd_opt_go(3)>
as part of subsequent negotiation.

=head2 URI query

Finally the query part of the URI can contain:

=over 4

=item B<compress=true>

I<Non-standard, libnbd E<ge> 1.24>

For SSH transport only, enable compression.  The default is false.

=item B<nbd-port=>C<PORT>

I<Non-standard, libnbd E<ge> 1.24>

Override the port number from the authority part of the URI.

For SSH transport, this specifies the port used to connect to
the NBD server, but the port in the authority field is used for
the SSH connection.

=item B<socket=>F<SOCKET>

Specifies the Unix domain socket to connect on.
Must be present for the C<+unix> transport, optional
for C<+ssh>, and must not be present for the other transports.

=item B<tls-certificates=>F<DIR>

I<Non-standard, libnbd E<ge> 1.10>

Set the certificates directory.  See L<nbd_set_tls_certificates(3)>.
Note this is not allowed by default - see next section.

=item B<tls-hostname=>C<SERVER>

I<libnbd E<ge> 1.22>

Set the TLS hostname.  See L<nbd_set_tls_hostname(3)>.

=item B<tls-priority=>C<PRIORITY>

I<Non-standard, libnbd E<ge> 1.24>

Override the TLS priority string.  See L<nbd_set_tls_priority(3)>.
This is not allowed by default - see next section.

=item B<tls-psk-file=>F<PSKFILE>

I<Non-standard>

Set the PSK file.  See L<nbd_set_tls_psk_file(3)>.  Note
this is not allowed by default - see next section.

=item B<tls-username=>C<USER>

I<Non-standard, libnbd E<ge> 1.24>

Override the username from the authority part of the URI.

For SSH transport, this specifies the TLS username for connecting to
the NBD server, but the user in the authority field is used
for the SSH connection.

=item B<tls-verify-peer=false>

Do not verify the server certificate.  See L<nbd_set_tls_verify_peer(3)>.
The default is C<true>.

=back

=head2 Disabling URI features

For security reasons you might want to disable certain URI
features.  Pre-filtering URIs is error-prone and should not
be attempted.  Instead use the libnbd APIs below to control
what can appear in URIs.  Note you must call these functions
on the same handle before calling L<nbd_connect_uri(3)> or
L<nbd_aio_connect_uri(3)>.

=over 4

=item TCP, Unix domain socket, C<AF_VSOCK> or SSH transports

Default: all allowed

To select which transports are allowed call
L<nbd_set_uri_allow_transports(3)>.

=item TLS

Default: both non-TLS and TLS connections allowed

To force TLS off or on in URIs call
L<nbd_set_uri_allow_tls(3)>.

=item TLS priority

Default: denied

To allow the TLS priority to be set in URIs call
L<nbd_set_uri_allow_tls_priority(3)>.

=item Connect to Unix domain socket in the local filesystem

Default: allowed

To prevent this you must disable the C<+unix> transport
using L<nbd_set_uri_allow_transports(3)>.

=item Read from local files

Default: denied

To allow URIs to contain references to local files
(eg. for parameters like C<tls-psk-file>) call
L<nbd_set_uri_allow_local_file(3)>.

=back

=head2 Optional features

This call will fail if libnbd was not compiled with libxml2; you can
test whether this is the case with L<nbd_supports_uri(3)>.

Support for URIs that require TLS will fail if libnbd was not
compiled with gnutls; you can test whether this is the case
with L<nbd_supports_tls(3)>.

=head2 Constructing a URI from an existing connection

See L<nbd_get_uri(3)>.

=head2 See if a string is an NBD URI

See L<nbd_is_uri(3)>.

=head2 Differences from qemu and glib parsing of NBD URIs

L<qemu(1)> also supports NBD URIs and has a separate URI parser.  In
S<qemu E<le> 9.0> this was done using their own parser.
In S<qemu E<ge> 9.1> this is done using glib C<g_uri> functions.
The current (glib-based) parser does not parse the export name part
of the URI in exactly the same way as libnbd, which may cause URIs
to work in libnbd but not in qemu or I<vice versa>.  Only URIs using
exportnames should be affected.  For details see
L<https://gitlab.com/qemu-project/qemu/-/issues/2584>.

=head2 Limitations on vsock port numbers

The L<vsock(7)> protocol allows 32 bit unsigned ports, reserving
ports 0, 1 and 2 for special purposes.  In Linux, ports E<lt> 1024 are
reserved for privileged processes.

libxml2 (used to parse the URI) imposes additional restrictions.
libxml2 E<lt> 2.9 limited port numbers to 99,999,999.
libxml2 E<ge> 2.9 limits port numbers to E<le> 0x7fff_ffff (31 bits).

libnbd E<ge> 1.24 allows you to override the port field by adding
C<?nbd-port=PORT> to the URI, allowing you to use any vsock port number.

=head1 RETURN VALUE

If the call is successful the function returns C<0>.

=head1 ERRORS

On error C<-1> is returned.

Refer to L<libnbd(3)/ERROR HANDLING>
for how to get further details of the error.

The following parameters must not be NULL: C<h>, C<uri>.
For more information see L<libnbd(3)/Non-NULL parameters>.

=head1 HANDLE STATE

nbd_connect_uri
can be called when the handle is in the following state:

 ┌─────────────────────────────────────┬─────────────────────────┐
 │ Handle created, before connecting   │ ✅ allowed              │
 │ Connecting                          │ ❌ error                │
 │ Connecting & handshaking (opt_mode) │ ❌ error                │
 │ Connected to the server             │ ❌ error                │
 │ Connection shut down                │ ❌ error                │
 │ Handle dead                         │ ❌ error                │
 └─────────────────────────────────────┴─────────────────────────┘

=head1 VERSION

This function first appeared in libnbd 1.0.

If you need to test if this function is available at compile time
check if the following macro is defined:

 #define LIBNBD_HAVE_NBD_CONNECT_URI 1

=head1 EXAMPLE

This example is also available as F<examples/connect-uri.c>
in the libnbd source code.

 /* This example shows how to connect to an NBD
  * server using the server's NBD URI.
  *
  * To test this with a recent version of nbdkit
  * that supports the '$uri' syntax, do:
  *
  * nbdkit -U - random 1M \
  *   --run './connect-uri $uri'
  *
  * To test connecting to a remote NBD server
  * listening on port 10809, do:
  *
  * ./connect-uri nbd://remote/
  */

 #include <stdio.h>
 #include <stdlib.h>
 #include <stdbool.h>
 #include <string.h>
 #include <stdint.h>
 #include <inttypes.h>

 #include <libnbd.h>

 int
 main (int argc, char *argv[])
 {
   struct nbd_handle *nbd;
   char *s;
   int64_t size;

   if (argc != 2) {
     fprintf (stderr, "usage: %s URI\n",
              argv[0]);
     exit (EXIT_FAILURE);
   }

   /* Create the libnbd handle. */
   nbd = nbd_create ();
   if (nbd == NULL) {
     fprintf (stderr, "%s\n", nbd_get_error ());
     exit (EXIT_FAILURE);
   }

   /* Request full information
    * (for nbd_get_canonical_export_name below)
    */
 #if LIBNBD_HAVE_NBD_SET_FULL_INFO
   if (nbd_set_full_info (nbd, true) == -1) {
     fprintf (stderr, "%s\n", nbd_get_error ());
     exit (EXIT_FAILURE);
   }
 #endif

   /* Connect to the NBD URI. */
   printf ("connecting to %s ...\n", argv[1]);
   fflush (stdout);
   if (nbd_connect_uri (nbd, argv[1]) == -1) {
     fprintf (stderr, "%s\n", nbd_get_error ());
     exit (EXIT_FAILURE);
   }
   printf ("connected\n");

   /* Print the URI, export name, size and other info. */
   printf ("requested URI: %s\n", argv[1]);
   s = nbd_get_uri (nbd);
   printf ("generated URI: %s\n", s ? s : "NULL");
   free (s);
   size = nbd_get_size (nbd);
   if (size == -1) {
     fprintf (stderr, "%s\n", nbd_get_error ());
     exit (EXIT_FAILURE);
   }
   printf ("size: %" PRIi64 "\n", size);
   s = nbd_get_export_name (nbd);
   printf ("requested export name: %s\n", s ? s : "NULL");
   free (s);
 #if LIBNBD_HAVE_NBD_GET_CANONICAL_EXPORT_NAME
   s = nbd_get_canonical_export_name (nbd);
   printf ("canonical export name: %s\n", s ? s : "NULL");
   free (s);
 #endif
 #if LIBNBD_HAVE_NBD_GET_EXPORT_DESCRIPTION
   s = nbd_get_export_description (nbd);
   printf ("export description: %s\n", s ? s : "NULL");
   free (s);
 #endif

   /* Close the libnbd handle. */
   nbd_close (nbd);

   exit (EXIT_SUCCESS);
 }

=head1 SEE ALSO

L<nbd_aio_connect_uri(3)>,
L<nbd_connect_tcp(3)>,
L<nbd_connect_unix(3)>,
L<nbd_connect_uri(3)>,
L<nbd_connect_vsock(3)>,
L<nbd_create(3)>,
L<nbd_get_uri(3)>,
L<nbd_is_uri(3)>,
L<nbd_opt_go(3)>,
L<nbd_set_export_name(3)>,
L<nbd_set_opt_mode(3)>,
L<nbd_set_tls(3)>,
L<nbd_set_tls_certificates(3)>,
L<nbd_set_tls_hostname(3)>,
L<nbd_set_tls_priority(3)>,
L<nbd_set_tls_psk_file(3)>,
L<nbd_set_tls_verify_peer(3)>,
L<nbd_set_uri_allow_local_file(3)>,
L<nbd_set_uri_allow_tls(3)>,
L<nbd_set_uri_allow_tls_priority(3)>,
L<nbd_set_uri_allow_transports(3)>,
L<nbd_supports_tls(3)>,
L<nbd_supports_uri(3)>,
L<nbd_supports_vsock(3)>,
L<libnbd(3)>,
L<nbdkit-ssh-plugin(1)>,
L<nc(1)>,
L<qemu(1)>,
L<ssh(1)>,
L<vsock(7)>,
L<https://github.com/NetworkBlockDevice/nbd/blob/master/doc/uri.md>.

=head1 AUTHORS

Eric Blake

Richard W.M. Jones

=head1 COPYRIGHT

Copyright Red Hat
