13. Protocols

  Module Protocols.HTTP

    Method do_proxied_method

      `.Query do_proxied_method(string|Standards.URI proxy, string user, string password, string method, string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con, void|string data)`

    Description

      Makes an HTTP request through a proxy.

    Parameter `proxy`

      URL for the proxy.

    Parameter `user`
    Parameter `password`

      Proxy authentication credentials.

    Parameter `method`
    Parameter `url`
    Parameter `query_variables`
    Parameter `request_headers`
    Parameter `con`
    Parameter `data`

      The remaining arguments are identical to do_method() .

    See also

      do_method() , do_async_proxied_method()

    Method do_method

      `.Query do_method(string method, string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con, void|string data)`

    Description

      Low level HTTP call method.

    Parameter `method`

      The HTTP method to use, e.g. `"GET"`.

    Parameter `url`

      The URL to perform method on. Should be a complete URL, including protocol, e.g. `"https://pike.ida.liu.se/"`.

    Parameter `query_variables`

      Calls http_encode_query and appends the result to the URL.

    Parameter `request_headers`

      The HTTP headers to be added to the request. By default the headers User-agent, Host and, if needed by the url, Authorization will be added, with generated contents. Providing these headers will override the default. Setting the value to 0 will remove that header from the request.

    Parameter `con`

      Old connection object.

    Parameter `data`

      Data payload to be transmitted in the request.

    See also

      do_sync_method()

    Method do_async_method

      `void do_async_method(string method, string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, Protocols.HTTP.Query con, void|string data)`

    Description

      Low level asynchronous HTTP call method.

    Parameter `method`

      The HTTP method to use, e.g. `"GET"`.

    Parameter `url`

      The URL to perform method on. Should be a complete URL, including protocol, e.g. `"https://pike.ida.liu.se/"`.

    Parameter `query_variables`

      Calls http_encode_query and appends the result to the URL.

    Parameter `request_headers`

      The HTTP headers to be added to the request. By default the headers User-agent, Host and, if needed by the url, Authorization will be added, with generated contents. Providing these headers will override the default. Setting the value to 0 will remove that header from the request.

    Parameter `con`

      Previously initialized connection object. In particular the callbacks must have been set (Query.set_callbacks() ).

    Parameter `data`

      Data payload to be transmitted in the request.

    See also

      do_method() , Query.set_callbacks()

    Method do_async_proxied_method

      `void do_async_proxied_method(string|Standards.URI proxy, string user, string password, string method, string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, Protocols.HTTP.Query con, void|string data)`

    Description

      Low level asynchronous proxied HTTP call method.

      Makes an HTTP request through a proxy.

    Parameter `proxy`

      URL for the proxy.

    Parameter `user`
    Parameter `password`

      Proxy authentication credentials.

    Parameter `method`

      The HTTP method to use, e.g. `"GET"`.

    Parameter `url`

      The URL to perform method on. Should be a complete URL, including protocol, e.g. `"https://pike.lysator.liu.se/"`.

    Parameter `query_variables`

      Calls http_encode_query and appends the result to the URL.

    Parameter `request_headers`

      The HTTP headers to be added to the request. By default the headers User-agent, Host and, if needed by the url, Authorization will be added, with generated contents. Providing these headers will override the default. Setting the value to 0 will remove that header from the request.

    Parameter `con`

      Previously initialized connection object. In particular the callbacks must have been set (Query.set_callbacks() ).

    Parameter `data`

      Data payload to be transmitted in the request.

    See also

      do_async_method() , do_proxied_method() , Query.set_callbacks()

    Method get_url

      `.Query get_url(string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

    Description

      Sends a HTTP GET request to the server in the URL and returns the created and initialized Query object. `0` is returned upon failure. If a query object having `request_headers->Connection=="Keep-Alive"` from a previous request is provided and the already established server connection can be used for the next request, you may gain some performance.

    Method put_url

      `.Query put_url(string|Standards.URI url, void|string file, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

    Description

      Sends a HTTP PUT request to the server in the URL and returns the created and initialized Query object. `0` is returned upon failure. If a query object having `request_headers->Connection=="Keep-Alive"` from a previous request is provided and the already established server connection can be used for the next request, you may gain some performance.

    Method delete_url

      `.Query delete_url(string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

    Description

      Sends a HTTP DELETE request to the server in the URL and returns the created and initialized Query object. `0` is returned upon failure. If a query object having `request_headers->Connection=="Keep-Alive"` from a previous request is provided and the already established server connection can be used for the next request, you may gain some performance.

    Method get_url_nice

      `array(string) get_url_nice(string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

    Description

      Returns an array of `({content_type, data})` after calling the requested server for the information. `0` is returned upon failure. Redirects (HTTP 302) are automatically followed.

    Method get_url_data

      `string get_url_data(string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

    Description

      Returns the returned data after calling the requested server for information through HTTP GET. `0` is returned upon failure. Redirects (HTTP 302) are automatically followed.

    Method post_url

      `.Query post_url(string|Standards.URI url, mapping(string:int|string|array(string))|string query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

    Description

      Similar to get_url , except that query variables is sent as a POST request instead of a GET request. If query_variables is a simple string, it is assumed to contain the verbatim body of the POST request; Content-Type must be properly specified manually, in this case.

    Method post_url_nice

      `array(string) post_url_nice(string|Standards.URI url, mapping(string:int|string|array(string))|string query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

    Description

      Similar to get_url_nice , except that query variables is sent as a POST request instead of a GET request.

    Method post_url_data

      `string post_url_data(string|Standards.URI url, mapping(string:int|string|array(string))|string query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

    Description

      Similar to get_url_data , except that query variables is sent as a POST request instead of a GET request.

    Method http_encode_query

      `string http_encode_query(mapping(string:int|string|array(string)) variables)`

    Description

      Encodes a query mapping to a string; this protects odd - in http perspective - characters like '&' and '#' and control characters, and packs the result together in a HTTP query string.

      Example:

          	> Protocols.HTTP.http_encode_query( (["anna":"eva","lilith":"blue"]) );
               Result: "lilith=blue&anna=eva"
               > Protocols.HTTP.http_encode_query( (["&amp;":"&","'=\"":"\0\0\0"]) );
               Result: "%26amp%3b=%26&%27%3d%22=%00%00%00"

    Method percent_encode

      `string percent_encode(string s)`

    Description

      Encodes the given string using `%XX` encoding, except that URI unreserved chars are not encoded. The unreserved chars are `A-Z`, `a-z`, `0-9`, `-`, `.`, `_`, and `~` (see RFC 2396 section 2.3).

      8-bit chars are encoded straight, and wider chars are not allowed. That means this encoding is applicable if s is a binary octet string. If it is a character string then uri_encode should be used instead.

      It is also slightly faster than uri_encode if s is known to contain only US-ASCII.

    Method percent_decode

      `string percent_decode(string s)`

    Description

      Decodes URI-style `%XX` encoded chars in the given string.

    See also

      percent_encode , uri_decode

    Bugs

      This function currently does not accept wide string input, which is necessary to work as the reverse of iri_encode .

    Method uri_encode

      `string uri_encode(string s)`

    Description

      Encodes the given string using `%XX` encoding to be used as a component part in a URI. This means that all URI reserved and excluded characters are encoded, i.e. everything except `A-Z`, `a-z`, `0-9`, `-`, `.`, `_`, and `~` (see RFC 2396 section 2.3).

      8-bit chars and wider are encoded using UTF-8 followed by percent-encoding. This follows RFC 3986 section 2.5, the IRI-to-URI conversion method in the IRI standard (RFC 3987) and appendix B.2 in the HTML 4.01 standard. It should work regardless of the charset used in the XML document the URI might be inserted into.

    See also

      uri_decode , uri_encode_invalids , iri_encode

    Method uri_encode_invalids

      `string uri_encode_invalids(string s)`

    Description

      Encodes all "dangerous" chars in the given string using `%XX` encoding, so that it can be included as a URI in an HTTP message or header field. This includes control chars, space and various delimiter chars except those in the URI `reserved` set (RFC 2396 section 2.2).

      Since this function doesn't touch the URI `reserved` chars nor the escape char `%`, it can be used on a complete formatted URI or IRI.

      8-bit chars and wider are encoded using UTF-8 followed by percent-encoding. This follows RFC 3986 section 2.5, the IRI standard (RFC 3987) and appendix B.2 in the HTML 4.01 standard.

    Note

      The characters in the URI `reserved` set are: `:`, `/`, `?`, `#`, `[`, `]`, `@`, `!`, `$`, `&`, `'`, `(`, `)`, `*`, `+`, `,`, `;`, `=`. In addition, this function doesn't touch the escape char `%`.

    See also

      uri_decode , uri_encode

    Method uri_decode

      `string uri_decode(string s)`

    Description

      Decodes URI-style `%XX` encoded chars in the given string, and then UTF-8 decodes the result. This is the reverse of uri_encode and uri_encode_invalids .

    See also

      uri_encode , uri_encode_invalids

    Method iri_encode

      `string iri_encode(string s)`

    Description

      Encodes the given string using `%XX` encoding to be used as a component part in an IRI (Internationalized Resource Identifier, see RFC 3987). This means that all chars outside the IRI `iunreserved` set are encoded, i.e. this function encodes equivalently to uri_encode except that all 8-bit and wider characters are left as-is.

    Bugs

      This function currently does not encode chars in the Unicode private ranges, although that is strictly speaking required in some but not all IRI components. That could change if it turns out to be a problem.

    See also

      percent_decode , uri_encode

    Method uri_normalize

      `string uri_normalize(string s)`

    Description

      Normalizes the URI-style `%XX` encoded string s by decoding all URI `unreserved` chars, i.e. US-ASCII digits, letters, `-`, `.`, `_`, and `~`.

      Since only unreserved chars are decoded, the result is always semantically equivalent to the input. It's therefore safe to use this on a complete formatted URI.

    See also

      uri_decode , uri_encode , iri_normalize

    Method iri_normalize

      `string iri_normalize(string s)`

    Description

      Normalizes the IRI-style UTF-8 and `%XX` encoded string s by decoding all IRI `unreserved` chars, i.e. everything except the URI `reserved` chars and control chars.

      Since only unreserved chars are decoded, the result is always semantically equivalent to the input. It's therefore safe to use this on a complete formatted IRI.

    See also

      iri_decode , uri_normalize

    Method quoted_string_encode

      `string quoted_string_encode(string s)`

    Description

      Encodes the given string quoted to be used as content inside a `quoted-string` according to RFC 2616 section 2.2. The returned string does not include the surrounding `"` chars.

    Note

      The `quoted-string` quoting rules in RFC 2616 have several problems:

      - Quoting is inconsistent since `"` is quoted as `\"`, but `\` does not need to be quoted. This is resolved in the HTTP bis update to mandate quoting of `\` too, which this function performs.

      - Many characters are not quoted sufficiently to make the result safe to use in an HTTP header, so this quoting is not enough if s contains NUL, CR, LF, or any 8-bit or wider character.

    See also

      quoted_string_decode

    Method quoted_string_decode

      `string quoted_string_decode(string s)`

    Description

      Decodes the given string which has been encoded as a `quoted-string` according to RFC 2616 section 2.2. s is assumed to not include the surrounding `"` chars.

    See also

      quoted_string_encode

    Method http_encode_string

      `__deprecated__ string http_encode_string(string in)`

    Description

      This is a deprecated alias for uri_encode , for compatibility with Pike 7.6 and earlier.

      In 7.6 this function didn't handle 8-bit and wider chars correctly. It encoded 8-bit chars directly to `%XX` escapes, and it used nonstandard `%uXXXX` escapes for 16-bit chars.

      That is considered a bug, and hence the function is changed. If you need the old buggy encoding then use the 7.6 compatibility version (`#pike 7.6`).

    Deprecated

    Method http_encode_cookie

      `__deprecated__ string http_encode_cookie(string f)`

    Description

      This function used to claim that it encodes the specified string according to the HTTP cookie standard. If fact it does not - it applies URI-style (i.e. `%XX`) encoding on some of the characters that cannot occur literally in cookie values. There exist some web servers (read Roxen and forks) that usually perform a corresponding nonstandard decoding of %-style escapes in cookie values in received requests.

      This function is deprecated. The function quoted_string_encode performs encoding according to the standard, but it is not safe to use with arbitrary chars. Thus URI-style encoding using uri_encode or percent_encode is normally a good choice, if you can use uri_decode /percent_decode at the decoding end.

    Deprecated

    Method unentity

      `__deprecated__ string unentity(string s)`

    Description

      Helper function for replacing HTML entities with the corresponding unicode characters.

    Deprecated

    CLASS Protocols.HTTP.Query

      Description

        Open and execute an HTTP query.

      Example

            HTTP.Query o=HTTP.Query();
             void ok()
             {
                write("ok...\n");
                write("%O\n", o->headers);
                exit(0);
             }
             void fail()
             {
                write("fail\n");
                exit(0);
             }
             int main()
             {
                o->set_callbacks(ok, fail);
                o->async_request("pike.ida.liu.se", 80, "HEAD / HTTP/1.0");
                return -1;
             }

      Variable errno

        `int Protocols.HTTP.Query.errno`

      Description

        Errno copied from the connection.

      Variable ok

        `int Protocols.HTTP.Query.ok`

      Description

        Tells if the connection is successfull.

      Variable headers

        `mapping Protocols.HTTP.Query.headers`

      Description

        Headers as a mapping. All header names are in lower case, for convinience.

      Variable protocol

        `string Protocols.HTTP.Query.protocol`

      Description

        Protocol string, ie `"HTTP/1.0"`.

        `int Protocols.HTTP.Query.status`
        `string Protocols.HTTP.Query.status_desc`

      Description

        Status number and description (eg `200` and `"ok"`).

        `string Protocols.HTTP.Query.host`
        `int Protocols.HTTP.Query.port`

      Description

        Connected host and port.

        Used to detect whether keep-alive can be used.

      Variable hostname_cache

        `mapping Protocols.HTTP.Query.hostname_cache`

      Description

        Set this to a global mapping if you want to use a cache, prior of calling *request().

      Method set_callbacks
      Method async_request

        `Protocols.HTTP.Query set_callbacks(function request_ok, function request_fail, mixed ... extra)`
        `Protocols.HTTP.Query async_request(string server, int port, string query)`
        `Protocols.HTTP.Query async_request(string server, int port, string query, mapping headers, string|void data)`

      Description

        Setup and run an asynchronous request, otherwise similar to thread_request() .

        request_ok (Protocols.HTTP.Query httpquery,...extra args) will be called when connection is complete, and headers are parsed.

        request_fail (Protocols.HTTP.Query httpquery,...extra args) is called if the connection fails.

      Returns

        Returns the called object

      Method thread_request

        `Protocols.HTTP.Query thread_request(string server, int port, string query)`
        `Protocols.HTTP.Query thread_request(string server, int port, string query, mapping headers, void|string data)`

      Description

        Create a new query object and begin the query.

        The query is executed in a background thread; call `() in the object to wait for the request to complete.

        query is the first line sent to the HTTP server; for instance `"GET /index.html HTTP/1.1"`.

        headers will be encoded and sent after the first line, and data will be sent after the headers.

      Returns

        Returns the called object.

      Method `()

        `int `()()`

      Description

        Wait for connection to complete.

      Returns

        Returns `1` on successfull connection, `0` on failure.

      Method data

        `string data(int|void max_length)`

      Description

        Gives back the data as a string.

      Method unicode_data

        `string unicode_data()`

      Description

        Gives back data, but decoded according to the content-type character set.

      See also

        data

      Method downloaded_bytes

        `int downloaded_bytes()`

      Description

        Gives back the number of downloaded bytes.

      Method total_bytes

        `int total_bytes()`

      Description

        Gives back the size of a file if a content-length header is present and parsed at the time of evaluation. Otherwise returns -1.

      Method cast

        `array cast("array")`

      Returns

        Array
        `mapping 0` | Headers
        `string 1` | Data
        `string 2` | Protocol
        `int 3` | Status
        `string 4` | Status description

      Method cast

        `mapping cast("mapping")`

      Returns

        The header mapping ORed with the following mapping.

        `"protocol" : string` | The protocol.
        `"status" : int` | The status code.
        `"status_desc" : string` | The status description.
        `"data" : string` | The returned data.

      Method cast

        `string cast("string")`

      Description

        Gives back the answer as a string.

      Method file

        `Protocols.HTTP.Query.PseudoFile file()`
        `Protocols.HTTP.Query.PseudoFile file(mapping newheaders, void|mapping removeheaders)`

      Description

        Gives back a pseudo-file object, with the methods `read()` and `close()`. This could be used to copy the file to disc at a proper tempo.

        newheaders , removeheaders is applied as: `(oldheaders|newheaders))-removeheaders` Make sure all new and remove-header indices are lower case.

      See also

        datafile()

      Method datafile

        `Protocols.HTTP.Query.PseudoFile datafile()`

      Description

        Gives back a pseudo-file object, with the methods `read()` and `close()`. This could be used to copy the file to disc at a proper tempo.

        datafile() doesn't give the complete request, just the data.

      See also

        file()

      Method close

        `void close()`

      Description

        Close all associated file descriptors.

      Method async_fetch

        `void async_fetch(function callback, mixed ... extra)`

      Description

        Fetch all data in background.

      See also

        timed_async_fetch() , async_request() , set_callbacks()

      Method timed_async_fetch

        `void timed_async_fetch(function(object:void) ok_callback, function(object:void) fail_callback, mixed ... extra)`

      Description

        Like async_fetch() , except with a timeout and a corresponding fail callback function.

      See also

        async_fetch() , async_request() , set_callbacks()

    CLASS Protocols.HTTP.Session

      Variable follow_redirects

        `int Protocols.HTTP.Session.follow_redirects`

      Description

        The number of redirects to follow, if any. This is the default to the created Request objects.

        A redirect automatically turns into a GET request, and all header, query, post or put information is dropped.

        Default is 20 redirects. A negative number will mean infinity.

      Bugs

        Loops will currently not be detected, only the limit works to stop loops.

      See also

        Request.follow_redirects

      Variable default_headers

        `mapping Protocols.HTTP.Session.default_headers`

      Description

        Default HTTP headers.

      Method set_http_cookie

        `void set_http_cookie(string cookie, Standards.URI at)`

      Description

        Parse and set a cookie received in the HTTP protocol. The cookie will be checked against current security levels et al.

      Method set_cookie

        `void set_cookie(Cookie cookie, Standards.URI who)`

      Description

        Set a cookie. The cookie will be checked against current security levels et al, using the parameter who . If who is zero, no security checks will be performed.

      Method encode_cookies
      Method decode_cookies

        `string encode_cookies()`
        `void decode_cookies(string data, void no_clear)`

      Description

        Dump all cookies to a string and read them back. This is useful to store cookies in between sessions (on disk, for instance). decode_cookies will throw an error upon parse failures. Also note, decode_cookies will clear out any previously learned cookies from the Session object, unless no_clear is given and true.

      Method get_cookies

        `array(string) get_cookies(Standards.URI|SessionURL for_url, void|int(0..1) no_delete)`

      Description

        Get the cookies that we should send to this server, for this url. They are presented in the form suitable for HTTP headers (as an array). This will also take in count expiration of cookies, and delete expired cookies from the Session unless no_delete is true.

      Variable hostname_cache

        `mapping Protocols.HTTP.Session.hostname_cache`

      Description

        Cache of hostname to IP lookups. Given to and used by the Query objects.

      Variable time_to_keep_unused_connections

        `int|float Protocols.HTTP.Session.time_to_keep_unused_connections`

      Description

        The time to keep unused connections in seconds. Set to zero to never save any kept-alive connections. (Might be good in a for instance totaly synchroneous script that keeps the backend thread busy and never will get call_outs.) Defaults to 10 seconds.

      Variable maximum_connections_per_server

        `int Protocols.HTTP.Session.maximum_connections_per_server`

      Description

        Maximum number of connections to the same server. Used only by async requests. Defaults to 10 connections.

      Variable maximum_total_connections

        `int Protocols.HTTP.Session.maximum_total_connections`

      Description

        Maximum total number of connections. Limits only async requests, and the number of kept-alive connections (live connections + kept-alive connections <= this number) Defaults to 50 connections.

      Variable maximum_connection_reuse

        `int Protocols.HTTP.Session.maximum_connection_reuse`

      Description

        Maximum times a connection is reused. Defaults to 1000000. <2 means no reuse at all.

      Method give_me_connection

        `Query give_me_connection(Standards.URI url)`

      Description

        Request a Query object suitable to use for the given URL. This may be a reused object from a keep-alive connection.

      Method return_connection

        `void return_connection(Standards.URI url, Query query)`

      Description

        Return a previously used Query object to the keep-alive storage. This function will determine if the given object is suitable to keep or not by checking status and headers.

      Method get_url
      Method post_url
      Method put_url
      Method delete_url

        `Request get_url(URL url, void|mapping query_variables)`
        `Request post_url(URL url, mapping|string query_variables)`
        `Request put_url(URL url, string file, void|mapping query_variables)`
        `Request delete_url(URL url, void|mapping query_variables)`

      Description

        Sends a HTTP GET, POST, PUT or DELETE request to the server in the URL and returns the created and initialized Request object. 0 is returned upon failure.

      Method get_url_nice
      Method get_url_data
      Method post_url_nice
      Method post_url_data

        `array(string) get_url_nice(URL url, mapping query_variables)`
        `string get_url_data(URL url, mapping query_variables)`
        `array(string) post_url_nice(URL url, mapping|string query_variables)`
        `string post_url_data(URL url, mapping|string query_variables)`

      Description

        Returns an array of `({content_type,data})` and just the data string respective, after calling the requested server for the information. `0` is returned upon failure.

        post* is similar to the get_url() class of functions, except that the query variables is sent as a POST request instead of as a GET.

      Method async_get_url
      Method async_put_url
      Method async_delete_url
      Method async_post_url

        `Request async_get_url(URL url, void|mapping query_variables, function callback_headers_ok, function callback_data_ok, function callback_fail, mixed ... callback_arguments)`
        `Request async_put_url(URL url, void|string file, void|mapping query_variables, function callback_headers_ok, function callback_data_ok, function callback_fail, mixed ... callback_arguments)`
        `Request async_delete_url(URL url, void|mapping query_variables, function callback_headers_ok, function callback_data_ok, function callback_fail, mixed ... callback_arguments)`
        `Request async_post_url(URL url, mapping query_variables, function callback_headers_ok, function callback_data_ok, function callback_fail, mixed ... callback_arguments)`

      Description

        Sends a HTTP GET, POST, PUT or DELETE request to the server in the URL asynchroneously, and call the corresponding callbacks when result arrives (or not). The callbacks will receive the created Request object as first argument, then the given callback_arguments , if any.

        callback_headers_ok is called when the HTTP request has received headers.

        callback_data_ok is called when the HTTP request has been received completely, data and all.

        callback_fail is called when the HTTP request has failed, on a TCP/IP or DNS level, or has received a forced timeout.

        The created Request object is returned.

      CLASS Protocols.HTTP.Session.Request

        Description

          Request

        Variable con

          `Query Protocols.HTTP.Session.Request.con`

        Description

          Raw connection object

        Variable url_requested

          `Standards.URI Protocols.HTTP.Session.Request.url_requested`

        Description

          URL requested (set by prepare_method). This will update according to followed redirects.

        Variable follow_redirects

          `int Protocols.HTTP.Session.Request.follow_redirects`

        Description

          Number of redirects to follow; the request will perform another request if the HTTP answer is a 3xx redirect. Default from the parent Session.follow_redirects .

          A redirect automatically turns into a GET request, and all header, query, post or put information is dropped.

        Bugs

          Loops will currently not be detected, only the limit works to stop loops.

        Variable cookie_encountered

          `function(string:mixed) Protocols.HTTP.Session.Request.cookie_encountered`

        Description

          Cookie callback. When a request is performed, the result is checked for cookie changes and additions. If a cookie is encountered, this function is called. Default is to call set_http_cookie in the Session object.

        Method prepare_method

          `array(string|int|mapping) prepare_method(string method, URL url, void|mapping query_variables, void|mapping extra_headers, void|string data)`

        Description

          Prepares the HTTP Query object for the connection, and returns the parameters to use with do_sync , do_async or do_thread .

          This method will also use cookie information from the parent Session , and may reuse connections (keep-alive).

        Method do_sync

          `Request do_sync(array(string|int|mapping) args)`

        Description

          Perform a request synchronously. Get arguments from prepare_method .

        Returns

          0 upon failure, this object upon success

        See also

          prepare_method , do_async , do_thread

        Method do_thread

          `Request do_thread(array(string|int|mapping) args)`

        Description

          Start a request in the background, using a thread. Call wait to wait for the thread to finish. Get arguments from prepare_method .

        Returns

          The called object.

        See also

          prepare_method , do_sync , do_async , wait

        Note

          do_thread does not rerun redirections automatically

        Method wait

          `Request wait()`

        Description

          Wait for the request thread to finish.

        Returns

          0 upon failure, or the called object upon success.

        See also

          do_thread

        Method set_callbacks

          `void set_callbacks(function(mixed ... :mixed) headers, function(mixed ... :mixed) data, function(mixed ... :mixed) fail, mixed ... callback_arguments)`

        Description

          Setup callbacks for async mode, headers will be called when the request got connected, and got data headers; data will be called when the request got the amount of data it's supposed to get and fail is called whenever the request failed.

          Note here that an error message from the server isn't considered a failure, only a failed TCP connection.

        Method do_async

          `Request do_async(array(string|int|mapping) args)`

        Description

          Start a request asyncroneously. It will perform in the background using callbacks (make sure the backend thread is free). Call set_callbacks to setup the callbacks. Get arguments from prepare_method .

        Returns

          The called object.

        See also

          set_callbacks , prepare_method , do_sync , do_thread

        Method destroy

          `void destroy()`

        Description

          destroy is called when an object is destructed. But since this clears the HTTP connection from the Request object, it can also be used to reuse a Request object.

      CLASS Protocols.HTTP.Session.SessionURL

        Description

          Class to store URL+referer

        Inherit URI

          inherit Standards.URI : URI

        Variable referer

          `URL Protocols.HTTP.Session.SessionURL.referer`

        Description

          the referer to this URL

        Method create

          `void Protocols.HTTP.Session.SessionURL(URL uri, URL base_uri, URL _referer)`

        Description

          instantiate a SessionURL object; when fed to Protocols.HTTP.Session calls, will add referer to the HTTP handshaking variables

    Module Protocols.HTTP.Server

      Constant HeaderParser

        `constant Protocols.HTTP.Server.HeaderParser`

      Description

        Fast HTTP header parser.

      Constant http_decode_string

        `constant Protocols.HTTP.Server.http_decode_string`

      Method http_decode_urlencoded_query

        `mapping(string:string|array(string)) http_decode_urlencoded_query(string query, void|mapping dest)`

      Description

        Decodes an URL-encoded query into a mapping.

      Method extension_to_type

        `string extension_to_type(string extension)`

      Description

        Looks up the file extension in a table to return a suitable MIME type.

      Method filename_to_type

        `string filename_to_type(string filename)`

      Description

        Looks up the file extension in a table to return a suitable MIME type.

      Method http_date

        `string http_date(int time)`

      Description

        Makes a time notification suitable for the HTTP protocol.

      Parameter `time`

        The time in seconds since the 00:00:00 UTC, January 1, 1970

      Returns

        The date in the HTTP standard date format. Example : Thu, 03 Aug 2000 05:40:39 GMT

      Method http_decode_date

        `int http_decode_date(string data)`

      Description

        Decode a HTTP date to seconds since 1970 (UTC)

      Returns

        zero (UNDEFINED) if the given string isn't a HTTP date

      CLASS Protocols.HTTP.Server.SSLPort

        Description

          The simplest SSL server possible. Binds a port and calls a callback with Request objects.

        Method create

          `void Protocols.HTTP.Server.SSLPort(function(Request:void) _callback, void|int _portno, void|string _interface, void|string key, void|string|array certificate)`

        Description

          Create a HTTPS (HTTP over SSL) server.

        Parameter `_callback`

          The function run when a request is received. takes one argument of type Request .

        Parameter `_portno`

          The port number to bind to, defaults to 443.

        Parameter `_interface`

          The interface address to bind to.

        Parameter `key`

          An optional SSL secret key, provided in binary format, such as that created by Standards.PKCS.RSA.private_key() .

        Parameter `certificate`

          An optional SSL certificate or chain of certificates with the host certificate first, provided in binary format.

        Method close

          `void close()`

        Description

          Closes the HTTP port.

        Method new_connection

          `void new_connection()`

        Description

          The port accept callback

        CLASS Protocols.HTTP.Server.SSLPort.MySSLPort

          Inherit sslport

            inherit SSL.sslport : sslport

          Method set_default_keycert

            `void set_default_keycert()`

          Method set_key

            `void set_key(string skey)`

          Method set_certificate

            `void set_certificate(string|array(string) certificate)`

      CLASS Protocols.HTTP.Server.Port

        Description

          The simplest server possible. Binds a port and calls a callback with Server.Request objects.

        Method create

          `void Protocols.HTTP.Server.Port(function(.Request:void) callback)`
          `void Protocols.HTTP.Server.Port(function(.Request:void) callback, int portno, void|string interface)`

        Method close

          `void close()`

        Description

          Closes the HTTP port.

      CLASS Protocols.HTTP.Server.Request

        Variable raw

          `string Protocols.HTTP.Server.Request.raw`

        Description

          raw unparsed full request (headers and body)

        Variable body_raw

          `string Protocols.HTTP.Server.Request.body_raw`

        Description

          raw unparsed body of the request (raw minus request line and headers)

        Variable request_raw

          `string Protocols.HTTP.Server.Request.request_raw`

        Description

          full request line (request_type + full_query + protocol )

        Variable request_type

          `string Protocols.HTTP.Server.Request.request_type`

        Description

          HTTP request method, eg. POST, GET, etc.

        Variable full_query

          `string Protocols.HTTP.Server.Request.full_query`

        Description

          full resource requested, including attached GET query

        Variable not_query

          `string Protocols.HTTP.Server.Request.not_query`

        Description

          resource requested minus any attached query

        Variable query

          `string Protocols.HTTP.Server.Request.query`

        Description

          query portion of requested resource, starting after the first "?"

        Variable protocol

          `string Protocols.HTTP.Server.Request.protocol`

        Description

          request protocol and version, eg. HTTP/1.0

        Variable request_headers

          `mapping(string:string|array(string)) Protocols.HTTP.Server.Request.request_headers`

        Description

          all headers included as part of the HTTP request, ie content-type.

        Variable variables

          `mapping(string:string|array(string)) Protocols.HTTP.Server.Request.variables`

        Description

          all variables included as part of a GET or POST request.

        Variable cookies

          `mapping(string:string) Protocols.HTTP.Server.Request.cookies`

        Description

          cookies set by client

        Variable misc

          `mapping Protocols.HTTP.Server.Request.misc`

        Description

          external use only

        Variable send_timeout_delay

          `int Protocols.HTTP.Server.Request.send_timeout_delay`

        Description

          send timeout (no activity for this period with data in send buffer) in seconds, default is 180

        Variable connection_timeout_delay

          `int Protocols.HTTP.Server.Request.connection_timeout_delay`

        Description

          connection timeout, delay until connection is closed while waiting for the correct headers:

        Method response_and_finish

          `void response_and_finish(mapping m, function|void _log_cb)`

        Description

          return a properly formatted response to the HTTP client

        Parameter `m`

          Contains elements for generating a response to the client.

          `"data" : string` | Data to be returned to the client.
          `"file" : object` | File object, the contents of which will be returned to the client.
          `"error" : int` | HTTP error code
          `"length" : int` | length of content returned. If file is provided, size bytes will be returned to client.
          `"modified" : string` | contains optional modification date.
          `"type" : string` | contains optional content-type
          `"extra_heads" : mapping` | contains a mapping of additional headers to be returned to client.
          `"server" : string` | contains the server identification header.

        Method sent_data

          `int sent_data()`

        Description

          Returns the amount of data sent.

  Module SSL

    CLASS SSL.packet

      Description

        SSL Record Layer. Handle formatting and parsing of packets.

    CLASS SSL.connection

      Description

        SSL packet layer. SSL.connection inherits SSL.handshake, and in addition to the state in the handshake super class, it contains the current read and write states, packet queues. This object is responsible for receiving and sending packets, processing handshake packets, and providing a clear text packages for some application.

      Inherit handshake

        inherit .handshake : handshake

      Inherit alert

        inherit ADT.Queue : alert

      Inherit urgent

        inherit ADT.Queue : urgent

      Inherit application

        inherit ADT.Queue : application

      Method set_alert_callback

        `void set_alert_callback(function(object:void) callback)`

      Description

        Called with alert object, sequence number of bad packet, and raw data as arguments, if a bad packet is received.

        Can be used to support a fallback redirect https->http.

      Method recv_packet

        `object recv_packet(string data)`

      Description

        Low-level receive handler. Returns a packet, an alert, or zero if more data is needed to get a complete packet.

      Method send_packet

        `void send_packet(object packet, int|void priority)`

      Description

        Queues a packet for write. Handshake and and change cipher must use the same priority, so must application data and close_notifies.

      Method to_write

        `string|int to_write()`

      Description

        Extracts data from the packet queues. Returns a string of data to be written, "" if there are no pending packets, 1 of the connection is being closed politely, and -1 if the connection died unexpectedly.

        This function is intended to be called from an i/o write callback.

      Method send_close

        `void send_close()`

      Description

        Initiate close.

      Method send_streaming_data

        `int send_streaming_data(string data)`

      Description

        Send an application data packet. If the data block is too large then as much as possible of the beginning of it is sent. The size of the sent data is returned.

      Method got_data

        `string|int got_data(string|int s)`

      Description

        Main receive handler. Returns a string of received application data, or 1 if a close was received, or -1 if an error occurred.

        This function is intended to be called from an i/o read callback.

    CLASS SSL.context

      Description

        Keeps the state that is shared by all SSL-connections for one server (or one port). It includes policy configuration, a server certificate, the server's private key(s), etc. It also includes the session cache.

      Variable rsa

        `Crypto.RSA SSL.context.rsa`

      Description

        The server's private key

      Variable client_rsa

        `Crypto.RSA SSL.context.client_rsa`

      Description

        The client's private key (used with client certificate authentication)

      Variable client_certificates

        `array(array(string)) SSL.context.client_certificates`

      Description

        An array of certificate chains a client may present to a server when client certificate authentication is requested.

      Variable client_certificate_selector

        `function(.context:array(string)) SSL.context.client_certificate_selector`

      Description

        A function which will select an acceptable client certificate for presentation to a remote server. This function will receive the SSL context, an array of acceptable certificate types, and a list of DNs of acceptable certificate authorities. This function should return an array of strings containing a certificate chain, with the client certificate first, (and the root certificate last, if applicable.)

      Variable auth_level

        `int SSL.context.auth_level`

      Description

        Policy for client authentication. One of SSL.Constants.AUTHLEVEL_none , SSL.Constants.AUTHLEVEL_ask and SSL.Constants.AUTHLEVEL_require .

      Method set_authorities

        `void set_authorities(array(string) a)`

      Description

        Array of authorities that are accepted for client certificates. The server will only accept connections from clients whose certificate is signed by one of these authorities. The string is a DER-encoded certificate, which typically must be decoded using MIME.decode_base64 or Tools.PEM.Msg first.

        Note that it is presumed that the issuer will also be trusted by the server. See trusted_issuers for details on specifying trusted issuers.

        If empty, the server will accept any client certificate whose issuer is trusted by the server.

      Variable require_trust

        `int SSL.context.require_trust`

      Description

        When set, require the chain to be known, even if the root is self signed.

        Note that if set, and certificates are set to be verified, trusted issuers must be provided, or no connections will be accepted.

      Method get_authorities

        `array(string) get_authorities()`

      Description

        Get the list of allowed authorities. See set_authorities .

      Method set_trusted_issuers

        `void set_trusted_issuers(array(array(string)) i)`

      Description

        Sets the list of trusted certificate issuers.

      Parameter `a`

        An array of certificate chains whose root is self signed (ie a root issuer), and whose final certificate is an issuer that we trust. The root of the certificate should be first certificate in the chain. The string is a DER-encoded certificate, which typically must be decoded using MIME.decode_base64 or Tools.PEM.Msg first.

        If this array is left empty, and the context is set to verify certificates, a certificate chain must have a root that is self signed.

      Method get_trusted_issuers

        `array(array(string)) get_trusted_issuers()`

      Description

        Get the list of trusted issuers. See set_trusted_issuers .

      Variable verify_certificates

        `int SSL.context.verify_certificates`

      Description

        Determines whether certificates presented by the peer are verified, or just accepted as being valid.

        `Crypto.RSA SSL.context.long_rsa`
        `Crypto.RSA SSL.context.short_rsa`

      Description

        Temporary, non-certified, private keys, used with a server_key_exchange message. The rules are as follows:

        If the negotiated cipher_suite has the "exportable" property, and short_rsa is not zero, send a server_key_exchange message with the (public part of) the short_rsa key.

        If the negotiated cipher_suite does not have the exportable property, and long_rsa is not zero, send a server_key_exchange message with the (public part of) the long_rsa key.

        Otherwise, dont send any server_key_exchange message.

      Variable dsa

        `Crypto.DSA SSL.context.dsa`

      Description

        Servers dsa key.

      Variable dh_params

        `.Cipher.DHParameters SSL.context.dh_params`

      Description

        Parameters for dh keyexchange.

      Variable random

        `function(int:string) SSL.context.random`

      Description

        Used to generate random cookies for the hello-message. If we use the RSA keyexchange method, and this is a server, this random number generator is not used for generating the master_secret.

      Variable certificates

        `array(string) SSL.context.certificates`

      Description

        The server's certificate, or a chain of X509.v3 certificates, with the server's certificate first and root certificate last.

      Variable preferred_auth_methods

        `array(int) SSL.context.preferred_auth_methods`

      Description

        For client authentication. Used only if auth_level is AUTH_ask or AUTH_require.

      Variable preferred_suites

        `array(int) SSL.context.preferred_suites`

      Description

        Cipher suites we want the server to support, best first.

      Method rsa_mode

        `void rsa_mode()`

      Description

        Set preferred_suites to RSA based methods.

      Method dhe_dss_mode

        `void dhe_dss_mode()`

      Description

        Set preferred_suites to DSS based methods.

      Variable preferred_compressors

        `array(int) SSL.context.preferred_compressors`

      Description

        Always ({ COMPRESSION_null })

      Variable use_cache

        `int SSL.context.use_cache`

      Description

        Non-zero to enable cahing of sessions

      Variable session_lifetime

        `int SSL.context.session_lifetime`

      Description

        Sessions are removed from the cache when they are older than this limit (in seconds). Sessions are also removed from the cache if a connection using the session dies unexpectedly.

      Variable max_sessions

        `int SSL.context.max_sessions`

      Description

        Maximum number of sessions to keep in the cache.

      Method lookup_session

        `.session lookup_session(string id)`

      Description

        Lookup a session identifier in the cache. Returns the corresponding session, or zero if it is not found or caching is disabled.

      Method new_session

        `.session new_session()`

      Description

        Create a new session.

      Method record_session

        `void record_session(.session s)`

      Description

        Add a session to the cache (if caching is enabled).

      Method purge_session

        `void purge_session(.session s)`

      Description

        Remove a session from the cache.

    CLASS SSL.handshake

      Description

        SSL.handshake keeps the state relevant for SSL handshaking. This includes a pointer to a context object (which doesn't change), various buffers, a pointer to a session object (reuse or created as appropriate), and pending read and write states being negotiated.

        Each connection will have two sets or read and write state: The current read and write states used for encryption, and pending read and write states to be taken into use when the current keyexchange handshake is finished.

        `array(int) SSL.handshake.client_cert_types`
        `array(string) SSL.handshake.client_cert_distinguished_names`

      Description

        A few storage variables for client certificate handling on the client side.

        `string SSL.handshake.client_random`
        `string SSL.handshake.server_random`

      Description

        Random cookies, sent and received with the hello-messages.

      Method handle_handshake

        `int(-1..1) handle_handshake(int type, string data, string raw)`

      Description

        Do handshake processing. Type is one of HANDSHAKE_*, data is the contents of the packet, and raw is the raw packet received (needed for supporting SSLv2 hello messages).

        This function returns 0 if hadshake is in progress, 1 if handshake is finished, and -1 if a fatal error occurred. It uses the send_packet() function to transmit packets.

    CLASS SSL.https

      Description

        Dummy HTTPS server

      Inherit sslport

        inherit SSL.sslport : sslport

    CLASS SSL.state

      Description

        A connection switches from one set of state objects to another, one or more times during its lifetime. Each state object handles a one-way stream of packets, and operates in either decryption or encryption mode.

      Variable session

        `object SSL.state.session`

      Description

        Information about the used algorithms.

      Variable mac

        `.Cipher.MACAlgorithm SSL.state.mac`

      Description

        Message Authentication Code

      Variable crypt

        `.Cipher.CipherAlgorithm SSL.state.crypt`

      Description

        Encryption or decryption object.

      Variable seq_num

        `Gmp.mpz SSL.state.seq_num`

      Description

        64-bit sequence number.

      Method decrypt_packet

        `Alert|.packet decrypt_packet(.packet packet, int version)`

      Description

        Destructively decrypts a packet (including inflating and MAC-verification, if needed). On success, returns the decrypted packet. On failure, returns an alert packet. These cases are distinguished by looking at the is_alert attribute of the returned packet.

      Method encrypt_packet

        `Alert|.packet encrypt_packet(.packet packet, int version)`

      Description

        Encrypts a packet (including deflating and MAC-generation).

    CLASS SSL.sslport

      Description

        Interface similar to Stdio.Port.

      Inherit socket

        inherit Stdio.Port : socket

      Inherit context

        inherit .context : context

      Inherit accept_queue

        inherit ADT.Queue : accept_queue

    CLASS SSL.session

      Description

        The most important information in a session object is a choice of encryption algorithms and a "master secret" created by keyexchange with a client. Each connection can either do a full key exchange to established a new session, or reuse a previously established session. That is why we have the session abstraction and the session cache. Each session is used by one or more connections, in sequence or simultaneously.

        It is also possible to change to a new session in the middle of a connection.

      Variable identity

        `string SSL.session.identity`

      Description

        Identifies the session to the server

      Variable compression_algorithm

        `int SSL.session.compression_algorithm`

      Description

        Always COMPRESSION_null.

      Variable cipher_suite

        `int SSL.session.cipher_suite`

      Description

        Constant defining a choice of keyexchange, encryption and mac algorithm.

      Variable cipher_spec

        `.Cipher.CipherSpec SSL.session.cipher_spec`

      Description

        Information about the encryption method derived from the cipher_suite.

      Variable ke_method

        `int SSL.session.ke_method`

      Description

        Key exchange method, also derived from the cipher_suite.

      Variable master_secret

        `string SSL.session.master_secret`

      Description

        48 byte secret shared between the client and the server. Used for deriving the actual keys.

      Variable cert_data

        `mapping SSL.session.cert_data`

      Description

        information about the certificate in use by the peer, such as issuing authority, and verification status.

      Variable peer_certificate_chain

        `array(string) SSL.session.peer_certificate_chain`

      Description

        the peer certificate chain

      Variable certificate_chain

        `array(string) SSL.session.certificate_chain`

      Description

        our certificate chain

      Method set_cipher_suite

        `void set_cipher_suite(int suite, int version)`

      Description

        Sets the proper authentication method and cipher specification for the given cipher suite and verison .

      Method set_compression_method

        `void set_compression_method(int compr)`

      Description

        Sets the compression method. Currently only COMPRESSION_null is supported.

      Method generate_keys

        `array(string) generate_keys(string client_random, string server_random, array(int) version)`

      Description

        Generates keys appropriate for the SSL version given in version , based on the client_random and server_random .

      Returns

        Array
        `string 0` | Client write MAC secret
        `string 1` | Server write MAC secret
        `string 2` | Client write key
        `string 3` | Server write key
        `string 4` | Client write IV
        `string 5` | Server write IV

      Method new_server_states

        `array(.state) new_server_states(string client_random, string server_random, array(int) version)`

      Description

        Computes a new set of encryption states, derived from the client_random, server_random and master_secret strings.

      Returns

        Array
        `SSL.state read_state` | Read state
        `SSL.state write_state` | Write state

      Method new_client_states

        `array(.state) new_client_states(string client_random, string server_random, array(int) version)`

      Description

        Computes a new set of encryption states, derived from the client_random, server_random and master_secret strings.

      Returns

        Array
        `SSL.state read_state` | Read state
        `SSL.state write_state` | Write state

    CLASS SSL.sslfile

      Description

        Interface similar to Stdio.File .

        - Handles blocking and nonblocking mode.

        - Handles callback mode in an arbitrary backend (also in blocking mode).

        - Read and write operations might each do both reading and writing. In callback mode that means that installing either a read or a write callback might install both internally. It also means that reading in one thread while writing in another doesn't work.

        - Callback changing operations like set_blocking and set_nonblocking aren't atomic.

        - Apart from the above, thread safety/atomicity characteristics are retained.

        - Blocking characterstics are retained for all functions.

        - is_open , connection init (create ) and close (close ) can do both reading and writing.

        - destroy attempts to close the stream properly by sending the close packet, but since it can't do blocking I/O it's not certain that it will succeed. The stream should therefore always be closed with an explicit close call.

        - Abrupt remote close without the proper handshake gets the errno System.EPIPE .

        - Objects do not contain cyclic references, so they are closed and destructed timely when dropped.

      Method create

        `void SSL.sslfile(Stdio.File stream, SSL.context ctx, int|void is_client, int|void is_blocking)`

      Description

        Create a connection over stream , which should be an open socket or pipe. ctx is the SSL context. If is_client is set then a client-side connection is started, server-side otherwise. If is_blocking is set then the stream is initially set in blocking mode, nonblocking mode otherwise.

        The backend used by stream is taken over and restored after the connection is closed (see close ). The callbacks and id in stream are overwritten.

      Method get_peer_certificate_info

        `mapping get_peer_certificate_info()`

      Description

        returns peer certificate information, if any.

      Method get_peer_certificates

        `array get_peer_certificates()`

      Description

        returns the peer certificate chain, if any.

      Method close

        `int close(void|string how, void|int clean_close, void|int dont_throw)`

      Description

        Close the connection. Both the read and write ends are always closed - the argument how is only for Stdio.File compatibility and must be either `"rw"` or `0`.

        If clean_close is set then close messages are exchanged to shut down the SSL connection but not the underlying stream. It may then continue to be used for other communication afterwards. The default is to send a close message and then close the stream without waiting for a response.

        I/O errors are normally thrown, but that can be turned off with dont_throw . In that case errno is set instead and 0 is returned. 1 is always returned otherwise. It's not an error to close an already closed connection.

      Note

        In nonblocking mode the stream might not be closed right away and the backend might be used for a while afterwards. This means that if there's an I/O problem it might not be signalled immediately by close .

      Note

        I/O errors from both reading and writing might occur in blocking mode.

      Note

        If a clean close is requested and data following the close message is received at the same time, then this object will read it and has no way to undo that. That data can be retrieved with read afterwards.

      Method shutdown

        `Stdio.File shutdown()`

      Description

        Shut down the SSL connection without sending any more packets. The underlying stream is returned if the connection isn't shut down already and if a nonclean close hasn't been requested.

      Method destroy

        `void destroy()`

      Description

        Try to close down the connection properly since it's customary to close files just by dropping them. No guarantee can be made that the close packet gets sent successfully though, because we can't risk blocking I/O here. You should call close explicitly.

      Method read

        `string read(void|int length, void|int(0..1) not_all)`

      Description

        Read some (decrypted) data from the connection. Works like Stdio.File.read .

      Note

        I/O errors from both reading and writing might occur in blocking mode.

      Method write

        `int write(string|array(string) data, mixed ... args)`

      Description

        Write some (unencrypted) data to the connection. Works like Stdio.File.write except that this function often buffers some data internally, so there's no guarantee that all the consumed data has been successfully written to the stream in nonblocking mode. It keeps the internal buffering to a minimum, however.

      Note

        This function returns zero if attempts are made to write data during the handshake phase and the mode is nonblocking.

      Note

        I/O errors from both reading and writing might occur in blocking mode.

      Method renegotiate

        `int renegotiate()`

      Description

        Renegotiate the connection by starting a new handshake. Note that the accept callback will be called again when the handshake is finished.

        Returns zero if there are any I/O errors. errno() will give the details.

      Note

        The read buffer is not cleared - a `read()` afterwards will return data from both before and after the renegotiation.

      Bugs

        Data in the write queue in nonblocking mode is not properly written before resetting the connection. Do a blocking `write("")` first to avoid problems with that.

      Method set_callbacks

        `void set_callbacks(void|function(mixed:int) read, void|function(mixed:int) write, void|function(mixed:int) close, void|function(mixed:int) read_oob, void|function(mixed:int) write_oob, void|function(void|mixed:int) accept)`

      Description

        Installs all the specified callbacks at once. Use UNDEFINED to keep the current setting for a callback.

        Like set_nonblocking , the callbacks are installed atomically. As opposed to set_nonblocking , this function does not do anything with the stream, and it doesn't even have to be open.

      Bugs

        read_oob and write_oob are currently ignored.

      See also

        set_read_callback , set_write_callback , set_close_callback , aet_accept_callback , query_callbacks

      Method set_nonblocking

        `void set_nonblocking(void|function(void|mixed:int) read, void|function(void|mixed:int) write, void|function(void|mixed:int) close, void|function(void|mixed:int) read_oob, void|function(void|mixed:int) write_oob, void|function(void|mixed:int) accept)`

      Description

        Set the stream in nonblocking mode, installing the specified callbacks. The alert callback isn't touched.

      Note

        Prior to version 7.5.12, this function didn't set the accept callback.

      Bugs

        read_oob and write_oob are currently ignored.

      Method set_nonblocking_keep_callbacks

        `void set_nonblocking_keep_callbacks()`

      Description

        Set nonblocking mode like set_nonblocking , but don't alter any callbacks.

      Method set_blocking

        `void set_blocking()`

      Description

        Set the stream in blocking mode. All but the alert callback are zapped.

      Note

        There might be some data still waiting to be written to the stream. That will be written in the next blocking call, regardless what it is.

      Note

        This function doesn't solve the case when the connection is used nonblocking in some backend thread and another thread switches it to blocking and starts using it. To solve that, put a call out in the backend from the other thread that switches it to blocking, and then wait until that call out has run.

      Note

        Prior to version 7.5.12, this function didn't clear the accept callback.

      Method set_blocking_keep_callbacks

        `void set_blocking_keep_callbacks()`

      Description

        Set blocking mode like set_blocking , but don't alter any callbacks.

      Method errno

        `int errno()`

      Method set_alert_callback

        `void set_alert_callback(function(object:void) alert)`

      Description

        Install a function that will be called when an alert packet is received. It doesn't affect the callback mode - it's called both from backends and from within normal function calls like read and write .

      Note

        This object is part of a cyclic reference whenever this is set, just like setting any other callback.

      Method query_alert_callback

        `function(object:void) query_alert_callback()`

      Method set_accept_callback

        `void set_accept_callback(function(void|object:int) accept)`

      Description

        Install a function that will be called when the handshake is finished and the connection is ready for use.

        The callback function will be called with the sslfile object and the additional id arguments (set with set_id ).

      Note

        Like the read, write and close callbacks, installing this callback implies callback mode, even after the handshake is done.

      Method query_accept_callback

        `function(void|object:int) query_accept_callback()`

      Method set_read_callback

        `void set_read_callback(function(void|mixed:int) read)`

      Description

        Install a function to be called when data is available.

      Method query_read_callback

        `function(void|mixed:int) query_read_callback()`

      Method set_write_callback

        `void set_write_callback(function(void|mixed:int) write)`

      Description

        Install a function to be called when data can be written.

      Method query_write_callback

        `function(void|mixed:int) query_write_callback()`

      Method set_close_callback

        `void set_close_callback(function(void|mixed:int) close)`

      Description

        Install a function to be called when the connection is closed, either normally or due to an error (use errno to retrieve it).

      Method query_close_callback

        `function(void|mixed:int) query_close_callback()`

      Method set_id

        `void set_id(mixed id)`

      Method query_id

        `mixed query_id()`

      Method set_backend

        `void set_backend(Pike.Backend backend)`

      Description

        Set the backend used for the file callbacks.

      Method query_backend

        `Pike.Backend query_backend()`

      Description

        Return the backend used for the file callbacks.

      Method query_address

        `string query_address(int|void arg)`

      Method is_open

        `int is_open()`

      Description

        Return nonzero if the stream currently is open, zero otherwise. This function does nonblocking I/O to check for a close packet in the input buffer.

      Method query_stream

        `Stdio.File query_stream()`

      Description

        Return the underlying stream.

      Note

        Avoid any temptation to do `destruct(sslfile_obj->query_stream())`. That almost certainly creates more problems than it solves.

      Method query_connection

        `SSL.connection query_connection()`

      Description

        Return the SSL connection object.

      Method query_context

        `SSL.context query_context()`

      Description

        Return the SSL context object.

    CLASS SSL.alert

      Description

        Alert package.

      Inherit packet

        inherit .packet : packet

      Method create

        `void SSL.alert(int level, int description, int version, string|void message, mixed|void trace)`

    Module SSL.Constants

      Description

        Protocol constants

      ENUM SSL.Constants.KeyExchangeType

        Description

          Key exchange methods.

        Constant KE_rsa

          `constant SSL.Constants.KE_rsa`

        Description

          Rivest-Shamir-Adelman

        Constant KE_dh

          `constant SSL.Constants.KE_dh`

        Description

          Diffie-Hellman

      ENUM SSL.Constants.CompressionType

        Description

          Compression methods.

        Constant COMPRESSION_null

          `constant SSL.Constants.COMPRESSION_null`

        Description

          No compression.

    Module SSL.Cipher

      Description

        Encryption and MAC algorithms used in SSL.

      Method prf

        `string prf(string secret, string label, string seed, int len)`

      Method rsa_sign

        `ADT.struct rsa_sign(object context, string cookie, ADT.struct struct)`

      Method rsa_verify

        `int(0..1) rsa_verify(object context, string cookie, ADT.struct struct, Gmp.mpz signature)`

      Method dsa_sign

        `ADT.struct dsa_sign(object context, string cookie, ADT.struct struct)`

      Method anon_sign

        `ADT.struct anon_sign(object context, string cookie, ADT.struct struct)`

      CLASS SSL.Cipher.CipherAlgorithm

        Description

          Cipher algorithm interface.

        Method set_encrypt_key
        Method set_decrypt_key

          `this_program set_encrypt_key(string)`
          `this_program set_decrypt_key(string)`

        Description

          Set the key used for encryption/decryption, and enter encryption mode.

        Method block_size

          `int(0..) block_size()`

        Description

          Return the block size for this crypto.

      CLASS SSL.Cipher.MACAlgorithm

        Description

          Message Authentication Code interface.

      CLASS SSL.Cipher.CipherSpec

        Description

          Cipher specification.

      CLASS SSL.Cipher.MACsha

        Description

          MAC using SHA.

        Method hash_raw

          `string hash_raw(string data)`

        Method hash

          `string hash(object packet, Gmp.mpz seq_num)`

        Method hash_master

          `string hash_master(string data, string|void s)`

        Method create

          `void SSL.Cipher.MACsha(string|void s)`

      CLASS SSL.Cipher.MACmd5

        Description

          MAC using MD5.

        Inherit MACsha

          inherit MACsha : MACsha

      CLASS SSL.Cipher.MAChmac_sha

        Method hash

          `string hash(object packet, Gmp.mpz seq_num)`

        Method create

          `void SSL.Cipher.MAChmac_sha(string|void s)`

      CLASS SSL.Cipher.MAChmac_md5

        Inherit MAChmac_sha

          inherit MAChmac_sha : MAChmac_sha

        Method create

          `void SSL.Cipher.MAChmac_md5(string|void s)`

      CLASS SSL.Cipher.DES

        Inherit CBC

          inherit Crypto.CBC : CBC

      CLASS SSL.Cipher.DES3

        Inherit CBC

          inherit Crypto.CBC : CBC

      CLASS SSL.Cipher.DHParameters

        Description

          Diffie-Hellman parameters.

          `Gmp.mpz SSL.Cipher.DHParameters.p`
          `Gmp.mpz SSL.Cipher.DHParameters.g`
          `Gmp.mpz SSL.Cipher.DHParameters.order`

  Module Protocols.LysKOM

    CLASS Protocols.LysKOM.Connection

      Description

        This class contains nice abstraction for calls into the server. They are named "`call`", "`async_call`" or "`async_cb_call`", depending on how you want the call to be done.

      Method XXX
      Method async_XXX
      Method async_cb_XXX

        `mixed XXX(mixed ... args)`
        `object async_XXX(mixed ... args)`
        `object async_cb_XXX(function callback, mixed ... args)`

      Description

        Do a call to the server. This really clones a Protocols.LysKOM.Request object, and initialises it. `XXX` is to be read as one of the calls in the lyskom protocol. ('-' is replaced with '_'.) (ie, logout, async_login or async_cb_get_conf_stat.)

        The first method is a synchronous call. This will send the command, wait for the server to execute it, and then return the result.

        The last two are asynchronous calls, returning an initialised Protocols.LysKOM.Request object.

        `int Protocols.LysKOM.Connection.protocol_level`
        `string Protocols.LysKOM.Connection.session_software`
        `string Protocols.LysKOM.Connection.software_version`

      Description

        Description of the connected server.

      Method create

        `void Protocols.LysKOM.Connection(string server)`
        `void Protocols.LysKOM.Connection(string server, mapping options)`

      Description

        The options argument is a mapping with the following members:

        `"login" : int|string` | login as this person number (get number from name).
        `"password" : string` | send this login password.
        `"invisible" : int(0..1)` | if set, login invisible.
        `"port" : int(0..65535)` | server port (default is 4894).
        `"whoami" : string` | present as this user (default is from uid/getpwent and hostname).

    CLASS Protocols.LysKOM.Session

      Variable user

        `object Protocols.LysKOM.Session.user`

      Description

        This variable contains the Protocols.LysKOM.Session.Person that is logged in.

      Method create

        `void Protocols.LysKOM.Session(string server)`
        `void Protocols.LysKOM.Session(string server, mapping options)`

      Description

        Initializes the session object, and opens a connection to that server.

        options is a mapping of options:

        `"login" : int|string` | login as this person number (get number from name).
        `"create" : string` | create a new person and login with it.
        `"password" : string` | send this login password.
        `"invisible" : int(0..1)` | if set, login invisible.
        `"port" : int(0..65535)` | server port (default is 4894).
        `"whoami" : string` | present as this user (default is from uid/getpwent and hostname).

      See also

        Connection

      Method text

        `Text text(int no)`

      Description

        Returns the text no .

      Method person

        `Person person(int no)`

      Description

        Returns the Person no .

      Method conference

        `Conference conference(int no)`

      Description

        Returns conference number no .

      Method try_complete_person

        `array(ProtocolTypes.ConfZInfo) try_complete_person(string orig)`

      Description

        Runs a LysKOM completion on the given string, returning an array of confzinfos of the match.

      Method login

        `object login(int user_no, string password)`
        `object login(int user_no, string password, int invisible)`

      Description

        Performs a login. Throws a lyskom error if unsuccessful.

      Returns

        The session object logged in.

      Method create_person

        `object create_person(string name, string password)`

      Description

        Create a person, which will be logged in. returns the new person object

      Method logout

        `this_program logout()`

      Description

        Logouts from the server. returns the called object

      Method create_text

        `object create_text(string subject, string body, mapping options)`
        `object create_text(string subject, string body, mapping options, function callback, mixed ... extra)`

      Description

        Creates a new text.

        if callback is given, the function will be called when the text has been created, with the text as first argument. Otherwise, the new text is returned.

        options is a mapping that may contain:

        `"recpt" : Conference|array(Conference)` | recipient conferences.
        `"cc" : Conference|array(Conference)` | cc-recipient conferences.
        `"bcc" : Conference|array(Conference)` | bcc-recipient conferences*.
        `"comm_to" : Text|array(Text)` | The text(s) to be commented.
        `"foot_to" : Text|array(Text)` | The text(s) to be footnoted.
        `"anonymous" : int(0..1)` | send text anonymously.
        `"aux_items" : array(AuxItemInput)` | AuxItems you want to set for the text*.

      Note

        The items above marked with '*' are only available on protocol 10 servers. A LysKOM error will be thrown if the call fails.

      See also

        Conference.create_text() , Text.comment() , Text.footnote()

      Method send_message

        `object|void send_message(string textstring, mapping options)`

      Description

        Sends a message.

        options is a mapping that may contain:

        `"recpt" : Conference` | recipient conference.

      Method register_async_message_callback

        `void register_async_message_callback(function(int:void) cb)`

      CLASS Protocols.LysKOM.Session.AuxItemInput

        FIXME

          Undocumented

        Inherit AuxItemInput

          inherit ProtocolTypes.AuxItemInput : AuxItemInput

      CLASS Protocols.LysKOM.Session.AuxItems

        FIXME

          Undocumented

      CLASS Protocols.LysKOM.Session.Text

        Description

          All variables in this class is read only.

        FIXME

          Undocumented

        Variable no

          `int Protocols.LysKOM.Session.Text.no`

        Description

          The text number, as spicified to create .

        Variable err

          `object Protocols.LysKOM.Session.Text.err`

        Description

          Undocumented

        Method create

          `void Protocols.LysKOM.Session.Text(string textnumber)`

        Description

          Initializes a Text object.

        Method mark_as_read

          `void mark_as_read()`

        FIXME

          Undocumented.

          `mixed Protocols.LysKOM.Session.Text.prefetch_text`
          `mixed Protocols.LysKOM.Session.Text.prefetch_stat`
          `mixed Protocols.LysKOM.Session.Text.lines`
          `mixed Protocols.LysKOM.Session.Text.characters`
          `mixed Protocols.LysKOM.Session.Text.clear_stat`
          `mixed Protocols.LysKOM.Session.Text.aux_items`

        FIXME

          Undocumented

        Variable text

          `string Protocols.LysKOM.Session.Text.text`

        Description

          The actual text (or body if you wish).

        Variable subject

          `string Protocols.LysKOM.Session.Text.subject`

        Description

          The message subject.

        Variable author

          `string Protocols.LysKOM.Session.Text.author`

        Description

          The author of the text.

        Variable misc

          `mixed Protocols.LysKOM.Session.Text.misc`

        Description

          Misc info, including what conferences the message is posted to.

        FIXME

          Needs a more complete description.

        Variable marks

          `int Protocols.LysKOM.Session.Text.marks`

        Description

          The number of marks on this text.

        Variable creation_time

          `mixed Protocols.LysKOM.Session.Text.creation_time`

        Description

          The time the text was created on the server.

      CLASS Protocols.LysKOM.Session.Membership

        Description

          All variables in this class is read only.

        Variable last_time_read

          `object Protocols.LysKOM.Session.Membership.last_time_read`

        Variable priority

          `int(0..255) Protocols.LysKOM.Session.Membership.priority`

        Variable last_text_read

          `int Protocols.LysKOM.Session.Membership.last_text_read`

        Variable read_texts

          `array(int) Protocols.LysKOM.Session.Membership.read_texts`

        Variable added_at

          `object Protocols.LysKOM.Session.Membership.added_at`

        Variable type

          `multiset(string) Protocols.LysKOM.Session.Membership.type`

        Variable position

          `int Protocols.LysKOM.Session.Membership.position`

        Variable conf

          `object Protocols.LysKOM.Session.Membership.conf`

        Method number_unread

          `int number_unread()`

        Method query_read_texts

          `void query_read_texts()`

        Method unread_texts

          `array(object) unread_texts()`

      CLASS Protocols.LysKOM.Session.Person

        Variable no

          `int Protocols.LysKOM.Session.Person.no`

        Method create

          `void Protocols.LysKOM.Session.Person(int no)`

          `mixed Protocols.LysKOM.Session.Person.prefetch_stat`
          `mixed Protocols.LysKOM.Session.Person.prefetch_conf`
          `mixed Protocols.LysKOM.Session.Person.prefetch_membership`

        FIXME

          Undocumented

          `object Protocols.LysKOM.Session.Person.error`
          `Text Protocols.LysKOM.Session.Person.user_area`
          `mixed Protocols.LysKOM.Session.Person.username`
          `mixed Protocols.LysKOM.Session.Person.privileges`
          `mixed Protocols.LysKOM.Session.Person.flags`
          `mixed Protocols.LysKOM.Session.Person.last_login`
          `mixed Protocols.LysKOM.Session.Person.total_time_present`
          `mixed Protocols.LysKOM.Session.Person.sessions`
          `mixed Protocols.LysKOM.Session.Person.created_lines`
          `mixed Protocols.LysKOM.Session.Person.created_bytes`
          `mixed Protocols.LysKOM.Session.Person.read_texts`
          `mixed Protocols.LysKOM.Session.Person.no_of_text_fetches`
          `mixed Protocols.LysKOM.Session.Person.created_persons`
          `mixed Protocols.LysKOM.Session.Person.created_confs`
          `mixed Protocols.LysKOM.Session.Person.first_created_local_no`
          `mixed Protocols.LysKOM.Session.Person.no_of_created_texts`
          `mixed Protocols.LysKOM.Session.Person.no_of_marks`
          `mixed Protocols.LysKOM.Session.Person.no_of_confs`
          `mixed Protocols.LysKOM.Session.Person.unread`
          `int(0..0) Protocols.LysKOM.Session.Person.clear_membership`
          `mixed Protocols.LysKOM.Session.Person.membership`

        FIXME

          Undocumented

      CLASS Protocols.LysKOM.Session.Conference

        Method create

          `void Protocols.LysKOM.Session.Conference(int no)`

          `mixed Protocols.LysKOM.Session.Conference.prefetch_stat`
          `int Protocols.LysKOM.Session.Conference.no`
          `object Protocols.LysKOM.Session.Conference.error`
          `Text Protocols.LysKOM.Session.Conference.msg_of_day`
          `Conference Protocols.LysKOM.Session.Conference.supervisor`
          `Conference Protocols.LysKOM.Session.Conference.permitted_submitters`
          `Conference Protocols.LysKOM.Session.Conference.super_conf`
          `Person Protocols.LysKOM.Session.Conference.creator`
          `mixed Protocols.LysKOM.Session.Conference.aux_items`
          `mixed Protocols.LysKOM.Session.Conference.name`
          `mixed Protocols.LysKOM.Session.Conference.type`
          `mixed Protocols.LysKOM.Session.Conference.creation_time`
          `mixed Protocols.LysKOM.Session.Conference.last_written`
          `mixed Protocols.LysKOM.Session.Conference.nice`
          `mixed Protocols.LysKOM.Session.Conference.no_of_members`
          `mixed Protocols.LysKOM.Session.Conference.first_local_no`
          `mixed Protocols.LysKOM.Session.Conference.no_of_texts`
          `mixed Protocols.LysKOM.Session.Conference.presentation`

        FIXME

          Undocumented

    Module Protocols.LysKOM.Request

      Description

        This module contains nice abstraction for calls into the server. They are named "`call`", "`async_call`" or "`async_cb_call`", depending on how you want the call to be done.

      CLASS Protocols.LysKOM.Request._Request

        Description

          This is the main request class. All lyskom request classes inherit this class.

        Method async
        Method sync

          `void async(mixed ... args)`
          `mixed sync(mixed ... args)`

        Description

          Initialise an asynchronous or a synchronous call, the latter is also evaluating the result. This calls `indata()` in itself, to get the correct arguments to the lyskom protocol call.

        Method _async
        Method _sync

          `void _async(int call, mixed_data)`
          `mixed _sync(int call, mixed_data)`

        Description

          Initialise an asynchronous or a synchronous call, the latter is also evaluating the result. These are called by async and sync respectively.

        Method _reply
        Method reply

          `mixed _reply(object|array what)`
          `mixed reply(object|array what)`

        Description

          _reply() is called as callback to evaluate the result, and calls reply() in itself to do the real work.

        Method `()

          `mixed `()()`

        Description

          Wait for the call to finish.

        Variable ok

          `int(0..1) Protocols.LysKOM.Request._Request.ok`

        Description

          Tells if the call has executed ok

        Variable error

          `object Protocols.LysKOM.Request._Request.error`

        Description

          How the call failed. The call has completed if `(ok||error)`.

    Module Protocols.LysKOM.ProtocolTypes

      Description

        Data types as defined by the LysKOM protocol specification.

  Module Protocols.DNS

    Description

      Support for the Domain Name System protocol.

      RFC 1034, RFC 1035 and RFC 2308

    Method async_ip_to_host

      `void async_ip_to_host(string ip, function cb, mixed ... cba)`

    Method async_host_to_ip

      `void async_host_to_ip(string host, function cb, mixed ... cba)`

    Method async_get_mx_all

      `void async_get_mx_all(string host, function cb, mixed ... cba)`

    Method async_get_mx

      `void async_get_mx(string host, function cb, mixed ... cba)`

    Method gethostbyname

      `array gethostbyname(string host)`

    Method gethostbyaddr

      `array gethostbyaddr(string host)`

    Method get_mx

      `string get_mx(string host)`

    Method get_primary_mx

      `string get_primary_mx(string host)`

    ENUM Protocols.DNS.ResourceClass

      Description

        Resource classes

      Constant C_IN

        `constant Protocols.DNS.C_IN`

      Description

        Class Internet

      Constant C_CS

        `constant Protocols.DNS.C_CS`

      Description

        Class CSNET (Obsolete)

      Constant C_CH

        `constant Protocols.DNS.C_CH`

      Description

        Class CHAOS

      Constant C_HS

        `constant Protocols.DNS.C_HS`

      Description

        Class Hesiod

      Constant C_ANY

        `constant Protocols.DNS.C_ANY`

      Description

        Class ANY

    ENUM Protocols.DNS.EntryType

      Description

        Entry types

      Constant T_A

        `constant Protocols.DNS.T_A`

      Description

        Type - host address

      Constant T_NS

        `constant Protocols.DNS.T_NS`

      Description

        Type - authoritative name server

      Constant T_MD

        `constant Protocols.DNS.T_MD`

      Description

        Type - mail destination (Obsolete - use MX)

      Constant T_MF

        `constant Protocols.DNS.T_MF`

      Description

        Type - mail forwarder (Obsolete - use MX)

      Constant T_CNAME

        `constant Protocols.DNS.T_CNAME`

      Description

        Type - canonical name for an alias

      Constant T_SOA

        `constant Protocols.DNS.T_SOA`

      Description

        Type - start of a zone of authority

      Constant T_MB

        `constant Protocols.DNS.T_MB`

      Description

        Type - mailbox domain name (EXPERIMENTAL)

      Constant T_MG

        `constant Protocols.DNS.T_MG`

      Description

        Type - mail group member (EXPERIMENTAL)

      Constant T_MR

        `constant Protocols.DNS.T_MR`

      Description

        Type - mail rename domain name (EXPERIMENTAL)

      Constant T_NULL

        `constant Protocols.DNS.T_NULL`

      Description

        Type - null RR (EXPERIMENTAL)

      Constant T_WKS

        `constant Protocols.DNS.T_WKS`

      Description

        Type - well known service description

      Constant T_PTR

        `constant Protocols.DNS.T_PTR`

      Description

        Type - domain name pointer

      Constant T_HINFO

        `constant Protocols.DNS.T_HINFO`

      Description

        Type - host information

      Constant T_MINFO

        `constant Protocols.DNS.T_MINFO`

      Description

        Type - mailbox or mail list information

      Constant T_MX

        `constant Protocols.DNS.T_MX`

      Description

        Type - mail exchange

      Constant T_TXT

        `constant Protocols.DNS.T_TXT`

      Description

        Type - text strings

      Constant T_AAAA

        `constant Protocols.DNS.T_AAAA`

      Description

        Type - IPv6 address record (RFC 1886, deprecated)

      Constant T_LOC

        `constant Protocols.DNS.T_LOC`

      Description

        Type - Location Record (RFC 1876)

      Constant T_SRV

        `constant Protocols.DNS.T_SRV`

      Description

        Type - Service location record (RFC 2782)

      Constant T_NAPTR

        `constant Protocols.DNS.T_NAPTR`

      Description

        Type - NAPTR (RFC 3403)

      Constant T_A6

        `constant Protocols.DNS.T_A6`

      Description

        Type - IPv6 address record (RFC 2874, incomplete support)

      Constant T_SPF

        `constant Protocols.DNS.T_SPF`

      Description

        Type - SPF - Sender Policy Framework (RFC 4408)

    CLASS Protocols.DNS.protocol

      Description

        Low level DNS protocol

      Method mkquery

        `string mkquery(string|mapping dnameorquery, int|void cl, int|void type)`

      Description

        create a DNS query PDU

      Parameter `dnameorquery`
      Parameter `cl`

        record class such as Protocols.DNS.C_IN

      Parameter `type`

        query type such Protocols.DNS.T_A

      Returns

        data suitable for use with Protocols.DNS.client.do_sync_query

      Example

            // generate a query PDU for a address lookup on the hostname pike.ida.liu.se
             string q=Protocols.DNS.protocol()->mkquery("pike.ida.liu.se", Protocols.DNS.C_IN, Protocols.DNS.T_A);

      Method decode_entries

        `array decode_entries(string s, int num, array(int) next)`

      Description

        Decode a set of entries from an answer.

      Parameter `s`

        Encoded entries.

      Parameter `num`

        Number of entires in s .

      Parameter `next`

        Array with a single element containing the start position in s on entry and the continuation position on return.

      Returns

        Returns an array of mappings describing the decoded entires:

        Array

        `mapping 0..`

        Mapping describing a single entry:

        `"name" : string` | Name the entry concerns.
        `"type" : EntryType` | Type of entry.
        `"cl" : ResourceClass` | Resource class. Typically C_IN .
        `"ttl" : int` | Time to live for the entry in seconds.
        `"len" : int` | Length in bytes of the encoded data section.

        Depending on the type of entry the mapping may contain different additional fields:

        `T_CNAME`

        `"cname" : string`

        `T_PTR`

        `"ptr" : string`

        `T_NS`

        `"ns" : string`

        `T_MX`

        `"preference" : int`
        `"mx" : string`

        `T_HINFO`

        `"cpu" : string`
        `"os" : string`

        `T_SRV`

        RFC 2052 and RFC 2782.

        `"priority" : int`
        `"weight" : int`
        `"port" : int`
        `"target" : string`
        `"service" : string`
        `"proto" : string`
        `"name" : string`

        `T_A`

        `"a" : string` | IPv4-address in dotted-decimal format.

        `T_AAAA`

        `"aaaa" : string` | IPv6-address in colon-separated hexadecimal format.

        `T_LOC`

        `"version" : int` | Version, currently only version `0` (zero) is supported.
        `"size" : int` |
        `"h_perc" : int` |
        `"v_perc" : int` |
        `"lat" : int` |
        `"long" : int` |
        `"alt" : int` |

        `T_SOA`

        `"mname" : string` |
        `"rname" : string` |
        `"serial" : int` |
        `"refresh" : int` |
        `"retry" : int` |
        `"expire" : int` |
        `"minimum" : int` | Note: For historical reasons this entry is named `"minimum"`, but it contains the TTL for negative answers (RFC 2308).

        `T_NAPTR`

        `"order" : int`
        `"preference" : int`
        `"flags" : string`
        `"service" : string`
        `"regexp" : string`
        `"replacement" : string`

        `T_TXT`

        `"txt" : string`

        `T_SPF`

        `"spf" : string`

    CLASS Protocols.DNS.server

      Description

        Base class for implementing a Domain Name Service (DNS) server.

        This class is typically used by inheriting it, and overloading reply_query() and handle_response() .

      Inherit protocol

        inherit protocol : protocol

      Method reply_query

        `mapping reply_query(mapping query, mapping udp_data, function(mapping:void) cb)`

      Description

        Reply to a query (stub).

      Parameter `query`

        Parsed query.

      Parameter `udp_data`

        Raw UDP data.

      Parameter `cb`

        Callback you can call with the result instead of returning it. In that case, return `0` (zero).

        Overload this function to implement the proper lookup.

      Returns

        Returns `0` (zero) on failure, or a result mapping on success:

        `"rcode" : int`

        Array

        `mapping(string:string|int) entry`

        `"name" : string|array(string)`
        `"type" : int`
        `"cl" : int`

        `"an" : array(mapping(string:string|int))|void`
        `"qd" : array|void` |
        `"ns" : array|void` |
        `"ar" : array|void` |

      Method create

        `void Protocols.DNS.server()`
        `void Protocols.DNS.server(int port)`
        `void Protocols.DNS.server(string ip)`
        `void Protocols.DNS.server(string ip, int port)`
        `void Protocols.DNS.server(string ip, int port, string|int ... more)`

      Description

        Open one or more new DNS server ports.

      Parameter `ip`

        The IP to bind to. Defaults to `"::"` or `0` (ie ANY) depending on whether IPv6 support is present or not.

      Parameter `port`

        The port number to bind to. Defaults to `53`.

      Parameter `more`

        Optional further DNS server ports to open. Must be a set of ip , port argument pairs.

    CLASS Protocols.DNS.client

      Description

        Synchronous DNS client.

      Inherit protocol

        inherit protocol : protocol

      Method create

        `void Protocols.DNS.client()`
        `void Protocols.DNS.client(void|string|array server, void|int|array domain)`

      Method do_sync_query

        `mapping do_sync_query(string s)`

      Description

        Perform a synchronous DNS query.

      Parameter `s`

        result of Protocols.DNS.protocol.mkquery

      Returns

        mapping containing query result or 0 on failure/timeout

      Example

            // perform a hostname lookup, results stored in r->an
             object d=Protocols.DNS.client();
             mapping r=d->do_sync_query(d->mkquery("pike.ida.liu.se", C_IN, T_A));

      Method gethostbyname

        `array gethostbyname(string hostname)`

      Description

        Queries the host name from the default or given DNS server. The result is an array with three elements,

      Returns

        An array with the requested information about the specified host.

        Array
        `string hostname` | Hostname.
        `array(string) ip` | IP number(s).
        `array(string) aliases` | DNS name(s).

      Note

        Prior to Pike 7.7 this function only returned IPv4 addresses.

      Method getsrvbyname

        `array getsrvbyname(string service, string protocol, string|void name)`

      Description

        Queries the service record (RFC 2782) from the default or given DNS server. The result is an array of arrays with the following six elements for each record. The array is sorted according to the priority of each record.

        Each element of the array returned represents a service record. Each service record contains the following:

      Returns

        An array with the requested information about the specified service.

        Array
        `int priority` | Priority
        `int weight` | Weight in event of multiple records with same priority.
        `int port` | port number
        `string target` | target dns name

      Method gethostbyaddr

        `array gethostbyaddr(string hostip)`

      Description

        Queries the host name or ip from the default or given DNS server. The result is an array with three elements,

      Returns

        The requested data about the specified host.

        Array
        `string hostip` | The host IP.
        `array(string) ip` | IP number(s).
        `array(string) aliases` | DNS name(s).

      Method get_primary_mx

        `string get_primary_mx(string hostname)`

      Description

        Queries the primary mx for the host.

      Returns

        Returns the hostname of the primary mail exchanger.

    CLASS Protocols.DNS.async_client

      Description

        Asynchronous DNS client.

      Inherit client

        inherit client : client

      Inherit udp

        inherit Stdio.UDP : udp

      Method host_to_ip

        `void host_to_ip(string host, function callback, mixed ... args)`

      Method ip_to_host

        `void ip_to_host(string ip, function callback, mixed ... args)`

      Method get_mx_all

        `void get_mx_all(string host, function callback, mixed ... args)`

      Method get_mx

        `void get_mx(string host, function callback, mixed ... args)`

      Method close

        `void close()`

      Description

        Close the client.

      Note

        All active requests are aborted.

  Module Protocols

    Module Protocols.IRC

      CLASS Protocols.IRC.Client

        Method create

          `void Protocols.IRC.Client(string server, void|mapping(string:mixed) options)`

        Parameter `server`

          The IRC server to connect to.

        Parameter `options`

          An optional mapping with additional IRC client options.

          `"port" : int` | Defaults to 6667.
          `"user" : string` | Defaults to `"unknown"` on systems without getpwuid and getuid and to `getpwuid(getuid())[0]` on systems with.
          `"nick" : string` | Defaults to `"Unknown"` on systems without getpwuid and getuid and to `String.capitalize(getpwuid(getuid())[0])` on systems with.
          `"pass" : string` | Server password, if any. Public servers seldom require this.
          `"realname" : string` | Defaults to `"Mr. Anonymous"` on systems without getpwuid and getuid and to `getpwuid(getuid())[4]` on systems with.
          `"host" : string` | Defaults to `"localhost"` on systems without uname and to `uname()->nodename` on systems with.
          `"ping_interval" : int` | Defaults to 120.
          `"ping_timeout" : int` | Defaults to 120.
          `"connection_lost" : function(void:void)` | This function is called when the connection to the IRC server is lost or when a ping isn't answered with a pong within the time set by the `ping_timeout` option. The default behaviour is to complain on stderr and self destruct.
          `"error_notify" : function(mixed ... :void)` | This function is called when a KILL or ERROR command is recieved from the IRC server.
          `"system_notify" : function(string:void)` |
          `"motd_notify" : function(string:void)` |
          `"error_nickinuse" : function(string:)` |
          `"generic_notify" : function(string:)` | The arguments are from, type, to, message and extra.
          `"quit_notify" : function(string:)` | The arguments are who and why.
          `"privmsg_notify" : function(Person:)` | The arguments are originator, message and to.
          `"notice_notify" : function(Person:)` | The arguments are originator, message and to.
          `"nick_notify" : function(Person:)` | The arguments are originator and to.

        Method close

          `void close()`

        Description

          Closes the connection to the server.

      CLASS Protocols.IRC.Person

        Description

          Abstract class for a person.

        Variable nick

          `string Protocols.IRC.Person.nick`

        Description

          User nickname, e.g. `"Mirar"`.

        Variable user

          `string Protocols.IRC.Person.user`

        Description

          User name, e.g. `"mirar"`.

        Variable ip

          `string Protocols.IRC.Person.ip`

        Description

          User domain, e.g. `"mistel.idonex.se"`.

        Variable last_action

          `int Protocols.IRC.Person.last_action`

        Description

          Time of last action, represented as posix time.

      CLASS Protocols.IRC.Channel

        Description

          Abstract class for a IRC channel.

        Variable name

          `string Protocols.IRC.Channel.name`

        Description

          The name of the channel.

    Module Protocols.Bittorrent

      CLASS Protocols.Bittorrent.Generator

        Description

          Generate a .torrent binary string from files in the filesystem

        Example

              // usage: thisprogram [<file/dir>] [<file/dir>...] <target .torrent>
                 int main(int ac,array am)
                 {
                    Generator g=Generator();
                    foreach (am[1..<1];;string f)
                       g->add(f);
                    string dest=am[-1];
                    if (-1==search(dest,"torrent")) dest+=".torrent";
                    Stdio.write_file(dest,g->digest());
                    return 0;
                 }

        Inherit Torrent

          inherit .Torrent : Torrent

        Method create

          `void Protocols.Bittorrent.Generator(void|string base, void|int piece_size)`

        Description

          Create a generator.

        Parameter `base`

          The base filename/path in the torrent.

        Parameter `piece_size`

          The size of the pieces that the SHA hashes are calculated on. Default 262144 and this value should probably be 2^n.

        Method add_announce

          `this_program add_announce(string|array(string) announce_url)`

        Description

          Add one or multiple announcers (trackers). This is needed to get a valid .torrent file. If this is called more then once, more announcers (trackers) will be added with lower priority.

        Method add_file

          `this_program add_file(string path, void|string filename)`

        Description

          Add a file to the torrent. The second argument is what the file will be called in the torrent.

        Method add_directory_tree

          `this_program add_directory_tree(string path, void|string dirbase)`

        Description

          Add a directory tree to the torrent. The second argument is what the directory will be called in the torrent. This will call add_file on all non-directories in the tree.

        Method add

          `this_program add(string path, void|string base)`

        Description

          Add a file, or a directory tree to the torrent. This will call add_directory_tree or add_file.

        Method build_sha1s

          `void build_sha1s(void|function(int:void) progress_callback)`

        Description

          Build the SHA hashes from the files.

        Method digest

          `string digest(void|function(int:void) progress_callback)`

        Description

          Finally make a torrent string out of this information. Will call build_sha1's if the sha1's aren't generated already.

          progress_callback is called with (pos,of) arguments, similar to Torrent.verify_targets .

      CLASS Protocols.Bittorrent.Tracker

        Variable interval

          `int(0..) Protocols.Bittorrent.Tracker.interval`

        Description

          The query interval reported back to clients. Defaults to `1800`.

        Variable dynamic_add_torrents

          `int(0..1) Protocols.Bittorrent.Tracker.dynamic_add_torrents`

        Description

          Allow clients to dynamically add torrents to the tracker.

        Method add_torrent

          `void add_torrent(string id)`

        Description

          Add a torrent to the tracker.

        Parameter `id`

          The info hash of the torrent file.

        Method announce

          `string announce(mapping args, string ip)`

        Description

          Handles HTTP announce queries to the tracker.

        Method scrape

          `string scrape(mapping args)`

        Description

          Returns the result of a scrape query.

      CLASS Protocols.Bittorrent.Peer

        Method is_connectable

          `int is_connectable()`

        Description

          Returns true if we can connect to this peer, when new or disconnected but not fatally.

        Method is_online

          `int is_online()`

        Description

          Returns true if this peer is online and connected.

        Method is_completed

          `int is_completed()`

        Description

          Returns true if this peer is completed, as in has downloaded everything already - and we shouldn't need to upload to get stuff.

        Method is_available

          `int is_available()`

        Description

          Returns true if this peer is available, as in we can use it to download stuff.

        Method is_activated

          `int is_activated()`

        Description

          Returns true if this peer is activated, as in we're downloading from it.

        Method is_strangled

          `int is_strangled()`

        Description

          Returns true if this peer is strangled; as in we don't want to upload more, because we're not getting any back.

        Method is_choked

          `int is_choked()`

        Description

          Returns true if this peer is choking, as in doesn't send more data to us.

        Method downloading_pieces

          `multiset(int) downloading_pieces()`

        Description

          Returns as multiset what this peer is downloading.

        Method connect

          `void connect()`

        Description

          Connect to the peer; this is done async. status/mode will change from `"connecting"` to `"dead"` or to `"connected"` depending on result. Will throw error if already online.

          Upon connect, protocol will be initiated in choked mode. When the protocol is up, status will change to `"online"` (or `"failed"` if the handshake failed).

        Method disconnect

          `void disconnect()`

        Description

          Disconnect a peer. Does nothing if we aren't online. status/mode will change to `"disconnected"`,1 if we were online.

        Method send_have

          `void send_have(int n)`

        Description

          Send a have message to tell I now have piece n. Ignored if not online.

        Method request

          `void request(int piece, int offset, int bytes, function(int:void|mixed) callback)`

        Description

          Called to request a chunk from this peer.

        Method status

          `void status(string type, void|int|string data)`

        Description

          Called whenever there is a status change for this peer. Always called with `"created"` when the object is created.

          Does not need to call inherited function.

      CLASS Protocols.Bittorrent.Port

        Method create

          `void Protocols.Bittorrent.Port(.Torrent _parent)`

        Description

          Bind a port for this Torrent.

      CLASS Protocols.Bittorrent.Torrent

        Description

          Bittorrent peer - download and share. Read more about bittorrent at http://bitconjurer.org/BitTorrent/introduction.html

        Example

              The smallest usable torrent downloader. As first argument,
               it expects a filename to a .torrent file.

          int main(int ac,array am) { // initialize Torrent from file: Protocols.Bittorrent.Torrent t=Protocols.Bittorrent.Torrent(); t->load_metainfo(am[1]);

          // Callback when download status changes: // t->downloads_update_status=...;

          // Callback when pieces status change (when we get new stuff): // t->pieces_update_status=...;

          // Callback when peer status changes (connect, disconnect, choked...): // t->peer_update_status=...;

          // Callback when download is completed: t->download_completed_callback= lambda() { call_out(exit,3600,0); // share for an hour, then exit };

          // Callback to print warnings (same args as sprintf): // t->warning=werror;

          // type of progress function used below: void progress(int n,int of) { /* ... */ };

          // Initiate targets from Torrent, // if target was created, no need to verify: if (t->fix_targets(1,0,progress)==1) t->verify_targets(progress);

          // Open port to listen on, // we want to do this to be able to talk to firewalled peers: t->open_port(6881);

          // Ok, start calling tracker to get peers, // and tell about us: t->start_update_tracker();

          // Finally, start the download: t->start_download();

          return -1; }

      Variable do_we_strangle

        `function(.Peer:int(0..1)) Protocols.Bittorrent.Torrent.do_we_strangle`

      Description

        Function to determine if we should strangle this peer. Default is to allow 100000 bytes of data over the ratio, which is 2:1 per default; upload twice as much as we get.

        Arguments are the peer, bytes in (downloaded) and bytes out (uploaded). Return 1 to strangle and 0 to allow the peer to proceed downloading again.

      Variable pieces_update_status

        `function Protocols.Bittorrent.Torrent.pieces_update_status`

      Description

        If set, called when we got another piece downloaded (no args).

      Variable downloads_update_status

        `function Protocols.Bittorrent.Torrent.downloads_update_status`

      Description

        If set, called when we start to download another piece (no args).

      Variable peer_update_status

        `function Protocols.Bittorrent.Torrent.peer_update_status`

      Description

        If set, called when peer status changes.

      Variable download_completed_callback

        `function Protocols.Bittorrent.Torrent.download_completed_callback`

      Description

        If set, called when download is completed.

      Variable warning

        `function(string:void|mixed) Protocols.Bittorrent.Torrent.warning`

      Description

        Called if there is a protocol error.

      Method load_metainfo

        `void load_metainfo(string filename)`

      Description

        Loads the metainfo from a file.

      Method fix_targets

        `int fix_targets(void|int(-1..2) allocate, void|string base_filename, void|function(int:void) progress_callback)`

      Description

        Opens target datafile(s).

        If all files are created, the verify info will be filled as well, but if it isn't created, a call to verify_target() is necessary after this call.

      Parameter `allocate`

        Determines allocation procedure if the file doesn't exist:

        `0` | Don't allocate.
        `1` | Allocate virtual file size (seek, write end byte).
        `2` | Allocate for real (will call progress_callback(pos,length)).
        `-1` | Means never create a file, only open old files.

      Parameter `my_filename`

        A new base filename to substitute the metainfo base target filename with.

      Returns

        `1` | The (a) file was already there.
        `2` | All target files were created.

      Method verify_targets

        `void verify_targets(void|function(int:void) progress_callback)`

      Description

        Verify the file and fill file_got (necessary after load_info, but needs open_file before this call). [ progress_callback(at chunk,total chunks) ]

      Method open_port

        `void open_port(void|int port)`

      Description

        Open the port we're listening on.

      Method bytes_done

        `int bytes_done()`

      Description

        Calculate the bytes successfully downloaded (full pieces).

      Method bytes_left

        `int bytes_left()`

      Description

        Calculate the bytes left to download.

      Method update_tracker

        `void update_tracker(void|string event, void|int contact)`

      Description

        Contact and update the tracker with current status will fill the peer list.

      Method start_update_tracker

        `void start_update_tracker(void|int interval)`

      Description

        Starts to contact the tracker at regular intervals, giving it the status and recieving more peers to talk to. Will also contact these peers. The default interval is 5 minutes. If given an event, will update tracker with it.

      Method stop_update_tracker

        `void stop_update_tracker(void|string event)`

      Description

        Stops updating the tracker; will send the event as a last event, if set. It will not contact new peers.

      Method contact_peers

        `void contact_peers(void|int n)`

      Description

        Contact all or n peers.

      Method file_got_bitfield

        `string file_got_bitfield()`

      Description

        Returns the file got field as a string bitfield (cached).

      Method start_download

        `void start_download()`

      Description

        Initiate the downloading scheme.

      CLASS Protocols.Bittorrent.Torrent.Target

        Description

          Each bittorrent has one or more target files. This represents one of those.

        syntax

          `string Protocols.Bittorrent.Torrent.Target.base`
          `int Protocols.Bittorrent.Torrent.Target.length`
          `int Protocols.Bittorrent.Torrent.Target.offset`
          `void|array Protocols.Bittorrent.Torrent.Target.path` `void Protocols.Bittorrent.Torrent.Target(string base, int length, int offset, void|array path)`

    Module Protocols.Bittorrent.Bencoding

      Method _decode

        `array(string|int|array|mapping) _decode(string what)`

      Description

        Decodes a Bittorrent bencoded data chunk.

      Returns

        Array
        `string|int|array|mapping data` | The decoded data. UNDEFINED if no data could be decoded.
        `string remainder` | The trailing data that wasn't decoded.

      Method decode

        `string|int|array|mapping decode(string what)`

      Description

        Decodes a Bittorrent bencoded data chunk and ignores the remaining string. Returns UNDEFINED if the data is incomplete.

      Method encode

        `string encode(string|int|array|mapping data)`

      Description

        Encodes a Bittorrent bencoded data chunk.

      Method bits2string

        `string bits2string(array(int(0..1)) v)`

      Description

        Convert an array of `int(0..1)` to a Bittorrent style bitstring. Input will be padded to even bytes.

      Method string2bits

        `array(int(0..1)) string2bits(string s)`

      Description

        Convert a Bittorrent style bitstring to an array of `int(0..1)`.

      Method string2arr

        `array(int) string2arr(string s)`

      Description

        Convert a Bittorrent style bitstring to an array of indices.

    Module Protocols.Bittorrent.PeerID

      Method identify_peer

        `string identify_peer(string peerid)`

      Description

        Decodes the given peerid , returning an identification string for the client software. Assumes the peerid string is exactly 20 characters long.

  Module Protocols.LDAP

      `constant Protocols.LDAP.LDAP_SUCCESS`
      `constant Protocols.LDAP.LDAP_OPERATIONS_ERROR`
      `constant Protocols.LDAP.LDAP_PROTOCOL_ERROR`
      `constant Protocols.LDAP.LDAP_TIMELIMIT_EXCEEDED`
      `constant Protocols.LDAP.LDAP_SIZELIMIT_EXCEEDED`
      `constant Protocols.LDAP.LDAP_COMPARE_FALSE`
      `constant Protocols.LDAP.LDAP_COMPARE_TRUE`
      `constant Protocols.LDAP.LDAP_AUTH_METHOD_NOT_SUPPORTED`
      `constant Protocols.LDAP.LDAP_STRONG_AUTH_NOT_SUPPORTED`
      `constant Protocols.LDAP.LDAP_STRONG_AUTH_REQUIRED`
      `constant Protocols.LDAP.LDAP_PARTIAL_RESULTS`
      `constant Protocols.LDAP.LDAP_REFERRAL`
      `constant Protocols.LDAP.LDAP_ADMINLIMIT_EXCEEDED`
      `constant Protocols.LDAP.LDAP_UNAVAILABLE_CRITICAL_EXTENSION`
      `constant Protocols.LDAP.LDAP_CONFIDENTIALITY_REQUIRED`
      `constant Protocols.LDAP.LDAP_SASL_BIND_IN_PROGRESS`
      `constant Protocols.LDAP.LDAP_NO_SUCH_ATTRIBUTE`
      `constant Protocols.LDAP.LDAP_UNDEFINED_TYPE`
      `constant Protocols.LDAP.LDAP_INAPPROPRIATE_MATCHING`
      `constant Protocols.LDAP.LDAP_CONSTRAINT_VIOLATION`
      `constant Protocols.LDAP.LDAP_TYPE_OR_VALUE_EXISTS`
      `constant Protocols.LDAP.LDAP_INVALID_SYNTAX`
      `constant Protocols.LDAP.LDAP_NO_SUCH_OBJECT`
      `constant Protocols.LDAP.LDAP_ALIAS_PROBLEM`
      `constant Protocols.LDAP.LDAP_INVALID_DN_SYNTAX`
      `constant Protocols.LDAP.LDAP_IS_LEAF`
      `constant Protocols.LDAP.LDAP_ALIAS_DEREF_PROBLEM`
      `constant Protocols.LDAP.LDAP_INAPPROPRIATE_AUTH`
      `constant Protocols.LDAP.LDAP_INVALID_CREDENTIALS`
      `constant Protocols.LDAP.LDAP_INSUFFICIENT_ACCESS`
      `constant Protocols.LDAP.LDAP_BUSY`
      `constant Protocols.LDAP.LDAP_UNAVAILABLE`
      `constant Protocols.LDAP.LDAP_UNWILLING_TO_PERFORM`
      `constant Protocols.LDAP.LDAP_LOOP_DETECT`
      `constant Protocols.LDAP.LDAP_SORT_CONTROL_MISSING`
      `constant Protocols.LDAP.LDAP_NAMING_VIOLATION`
      `constant Protocols.LDAP.LDAP_OBJECT_CLASS_VIOLATION`
      `constant Protocols.LDAP.LDAP_NOT_ALLOWED_ON_NONLEAF`
      `constant Protocols.LDAP.LDAP_NOT_ALLOWED_ON_RDN`
      `constant Protocols.LDAP.LDAP_ALREADY_EXISTS`
      `constant Protocols.LDAP.LDAP_NO_OBJECT_CLASS_MODS`
      `constant Protocols.LDAP.LDAP_RESULTS_TOO_LARGE`
      `constant Protocols.LDAP.LDAP_AFFECTS_MULTIPLE_DSAS`
      `constant Protocols.LDAP.LDAP_OTHER`
      `constant Protocols.LDAP.LDAP_SERVER_DOWN`
      `constant Protocols.LDAP.LDAP_LOCAL_ERROR`
      `constant Protocols.LDAP.LDAP_ENCODING_ERROR`
      `constant Protocols.LDAP.LDAP_DECODING_ERROR`
      `constant Protocols.LDAP.LDAP_TIMEOUT`
      `constant Protocols.LDAP.LDAP_AUTH_UNKNOWN`
      `constant Protocols.LDAP.LDAP_FILTER_ERROR`
      `constant Protocols.LDAP.LDAP_USER_CANCELLED`
      `constant Protocols.LDAP.LDAP_PARAM_ERROR`
      `constant Protocols.LDAP.LDAP_NO_MEMORY`
      `constant Protocols.LDAP.LDAP_CONNECT_ERROR`
      `constant Protocols.LDAP.LDAP_NOT_SUPPORTED`
      `constant Protocols.LDAP.LDAP_CONTROL_NOT_FOUND`
      `constant Protocols.LDAP.LDAP_NO_RESULTS_RETURNED`
      `constant Protocols.LDAP.LDAP_MORE_RESULTS_TO_RETURN`
      `constant Protocols.LDAP.LDAP_CLIENT_LOOP`
      `constant Protocols.LDAP.LDAP_REFERRAL_LIMIT_EXCEEDED`

    Description

      LDAP result codes.

    See also

      Protocols.LDAP.client.error_number , Protocols.LDAP.client.result.error_number

    Constant ldap_error_strings

      `constant Protocols.LDAP.ldap_error_strings`

    Description

      Mapping from `LDAP_*` result codes to descriptive strings.

      `constant Protocols.LDAP.SEARCH_LOWER_ATTRS`
      `constant Protocols.LDAP.SEARCH_MULTIVAL_ARRAYS_ONLY`
      `constant Protocols.LDAP.SEARCH_RETURN_DECODE_ERRORS`

    Description

      Bitfield flags given to Protocols.LDAP.client.search :

      SEARCH_LOWER_ATTRS

        Lowercase all attribute values. This makes it easier to match specific attributes in the mappings returned by Protocols.LDAP.client.result.fetch since LDAP attribute names are case insensitive.

      SEARCH_MULTIVAL_ARRAYS_ONLY

        Only use arrays for attribute values where the attribute syntax specify multiple values. I.e. the values for single valued attributes are returned as strings instead of arrays containing one string element.

        If no value is returned for a single valued attribute, e.g. when `attrsonly` is set in the search call, then a zero will be used as value.

        The special `"dn"` value is also returned as a string when this flag is set.

        Note that it's the attribute type descriptions that are used to decide this, not the number of values a particular attribute happens to have in the search result.

      SEARCH_RETURN_DECODE_ERRORS

        Don't throw attribute value decode errors, instead return them in the result from Protocols.LDAP.client.result.fetch in place of the value. I.e. anywhere an attribute value string occurs, you might instead have a Locale.Charset.DecodeError object.

      `constant Protocols.LDAP.SCOPE_BASE`
      `constant Protocols.LDAP.SCOPE_ONE`
      `constant Protocols.LDAP.SCOPE_SUB`

    Description

      Constants for the search scope used with e.g. Protocols.LDAP.client.set_scope .

      SCOPE_BASE

        Return the object specified by the DN.

      SCOPE_ONE

        Return the immediate subobjects of the object specified by the DN.

      SCOPE_SUB

        Return the object specified by the DN and all objects below it (on any level).

      `constant Protocols.LDAP.MODIFY_ADD`
      `constant Protocols.LDAP.MODIFY_DELETE`
      `constant Protocols.LDAP.MODIFY_REPLACE`

    Description

      Constants used in the `attropval` argument to Protocols.LDAP.client.modify .

    Method ldap_encode_string

      `string ldap_encode_string(string str)`

    Description

      Quote characters in the given string as necessary for use as a string literal in filters and various composite LDAP attributes.

      The quoting is compliant with RFCs 2252 (section 4.3) and 2254 (section 4). All characters that can be special in those RFCs are quoted using the `\xx` syntax, but the set might be extended.

    See also

      ldap_decode_string , Protocols.LDAP.client.search

    Method ldap_decode_string

      `string ldap_decode_string(string str)`

    Description

      Decodes all `\xx` escapes in str .

    See also

      ldap_encode_string

    Method encode_dn_value

      `string encode_dn_value(string str)`

    Description

      Encode the given string for use as an attribute value in a distinguished name (on string form).

      The encoding is according to RFC 2253 section 2.4 with the exception that characters above `0x7F` aren't UTF-8 encoded. UTF-8 encoding can always be done afterwards on the complete DN, which also is done internally by the Protocols.LDAP functions when LDAPv3 is used.

    Method canonicalize_dn

      `string canonicalize_dn(string dn, void|int strict)`

    Description

      Returns the given distinguished name on a canonical form, so it reliably can be used in comparisons for equality. This means removing surplus whitespace, lowercasing attributes, normalizing quoting in string attribute values, lowercasing the hex digits in binary attribute values, and sorting the RDN parts separated by "+".

      The returned string follows RFC 2253. The input string may use legacy LDAPv2 syntax and is treated according to section 4 in RFC 2253.

      If strict is set then errors will be thrown if the given DN is syntactically invalid. Otherwise the invalid parts remain untouched in the result.

    Note

      The result is not entirely canonical since no conversion is done from or to hexadecimal BER encodings of the attribute values. It's assumed that the input already has the suitable value encoding depending on the attribute type.

    Note

      No UTF-8 encoding or decoding is done. The function can be used on both encoded and decoded input strings, and the result will be likewise encoded or decoded.

    Constant LDAP_CONTROL_MANAGE_DSA_IT

      `constant Protocols.LDAP.LDAP_CONTROL_MANAGE_DSA_IT`

    Description

      LDAP control: Manage DSA IT LDAPv3 control (RFC 3296): Control to indicate that the operation is intended to manage objects within the DSA (server) Information Tree.

    Constant LDAP_CONTROL_VLVREQUEST

      `constant Protocols.LDAP.LDAP_CONTROL_VLVREQUEST`

    Description

      LDAP control: LDAP Extensions for Scrolling View Browsing of Search Results (internet draft): Control used to request virtual list view support from the server.

    Constant LDAP_CONTROL_VLVRESPONSE

      `constant Protocols.LDAP.LDAP_CONTROL_VLVRESPONSE`

    Description

      LDAP control: LDAP Extensions for Scrolling View Browsing of Search Results (internet draft): Control used to pass virtual list view (VLV) data from the server to the client.

    Constant LDAP_PAGED_RESULT_OID_STRING

      `constant Protocols.LDAP.LDAP_PAGED_RESULT_OID_STRING`

    Description

      LDAP control: Microsoft AD: Control to instruct the server to return the results of a search request in smaller, more manageable packets rather than in one large block.

    Constant LDAP_SERVER_ASQ_OID

      `constant Protocols.LDAP.LDAP_SERVER_ASQ_OID`

    Description

      LDAP control: Microsoft AD: Control to force the query to be based on a specific DN-valued attribute.

    Constant LDAP_SERVER_CROSSDOM_MOVE_TARGET_OID

      `constant Protocols.LDAP.LDAP_SERVER_CROSSDOM_MOVE_TARGET_OID`

    Description

      LDAP control: Microsoft AD: Control used with an extended LDAP rename function to move an LDAP object from one domain to another.

    Constant LDAP_SERVER_DIRSYNC_OID

      `constant Protocols.LDAP.LDAP_SERVER_DIRSYNC_OID`

    Description

      LDAP control: Microsoft AD: Control that enables an application to search the directory for objects changed from a previous state.

    Constant LDAP_SERVER_DOMAIN_SCOPE_OID

      `constant Protocols.LDAP.LDAP_SERVER_DOMAIN_SCOPE_OID`

    Description

      LDAP control: Microsoft AD: Control used to instruct the LDAP server not to generate any referrals when completing a request.

    Constant LDAP_SERVER_EXTENDED_DN_OID

      `constant Protocols.LDAP.LDAP_SERVER_EXTENDED_DN_OID`

    Description

      LDAP control: Microsoft AD: Control to request an extended form of an Active Directory object distinguished name.

    Constant LDAP_SERVER_LAZY_COMMIT_OID

      `constant Protocols.LDAP.LDAP_SERVER_LAZY_COMMIT_OID`

    Description

      LDAP control: Microsoft AD: Control used to instruct the server to return the results of a DS modification command, such as add, delete, or replace, after it has been completed in memory, but before it has been committed to disk.

    Constant LDAP_SERVER_NOTIFICATION_OID

      `constant Protocols.LDAP.LDAP_SERVER_NOTIFICATION_OID`

    Description

      LDAP control: Microsoft AD: Control used with an extended LDAP asynchronous search function to register the client to be notified when changes are made to an object in Active Directory.

    Constant LDAP_SERVER_PERMISSIVE_MODIFY_OID

      `constant Protocols.LDAP.LDAP_SERVER_PERMISSIVE_MODIFY_OID`

    Description

      LDAP control: Microsoft AD: An LDAP modify request will normally fail if it attempts to add an attribute that already exists, or if it attempts to delete an attribute that does not exist. With this control, as long as the attribute to be added has the same value as the existing attribute, then the modify will succeed. With this control, deletion of an attribute that does not exist will also succeed.

    Constant LDAP_SERVER_QUOTA_CONTROL_OID

      `constant Protocols.LDAP.LDAP_SERVER_QUOTA_CONTROL_OID`

    Description

      LDAP control: Microsoft AD: Control used to pass the SID of a security principal, whose quota is being queried, to the server in a LDAP search operation.

    Constant LDAP_SERVER_RESP_SORT_OID

      `constant Protocols.LDAP.LDAP_SERVER_RESP_SORT_OID`

    Description

      LDAP control: Microsoft AD: Control used by the server to indicate the results of a search function initiated using the LDAP_SERVER_SORT_OID control.

    Constant LDAP_SERVER_SD_FLAGS_OID

      `constant Protocols.LDAP.LDAP_SERVER_SD_FLAGS_OID`

    Description

      LDAP control: Microsoft AD: Control used to pass flags to the server to control various security descriptor results.

    Constant LDAP_SERVER_SEARCH_OPTIONS_OID

      `constant Protocols.LDAP.LDAP_SERVER_SEARCH_OPTIONS_OID`

    Description

      LDAP control: Microsoft AD: Control used to pass flags to the server to control various search behaviors.

    Constant LDAP_SERVER_SHOW_DELETED_OID

      `constant Protocols.LDAP.LDAP_SERVER_SHOW_DELETED_OID`

    Description

      LDAP control: Microsoft AD: Control used to specify that the search results include any deleted objects that match the search filter.

    Constant LDAP_SERVER_SORT_OID

      `constant Protocols.LDAP.LDAP_SERVER_SORT_OID`

    Description

      LDAP control: Microsoft AD: Control used to instruct the server to sort the search results before returning them to the client application.

    Constant LDAP_SERVER_TREE_DELETE_OID

      `constant Protocols.LDAP.LDAP_SERVER_TREE_DELETE_OID`

    Description

      LDAP control: Microsoft AD: Control used to delete an entire subtree in the directory.

    Constant LDAP_SERVER_VERIFY_NAME_OID

      `constant Protocols.LDAP.LDAP_SERVER_VERIFY_NAME_OID`

    Description

      LDAP control: Microsoft AD: Control used to instruct the DC accepting the update which DC it should verify with, the existence of any DN attribute values.

      `constant Protocols.LDAP.SYNTAX_ATTR_TYPE_DESCR`
      `constant Protocols.LDAP.SYNTAX_BINARY`
      `constant Protocols.LDAP.SYNTAX_BIT_STRING`
      `constant Protocols.LDAP.SYNTAX_BOOLEAN`
      `constant Protocols.LDAP.SYNTAX_CERT`
      `constant Protocols.LDAP.SYNTAX_CERT_LIST`
      `constant Protocols.LDAP.SYNTAX_CERT_PAIR`
      `constant Protocols.LDAP.SYNTAX_COUNTRY_STR`
      `constant Protocols.LDAP.SYNTAX_DN`
      `constant Protocols.LDAP.SYNTAX_DIRECTORY_STR`
      `constant Protocols.LDAP.SYNTAX_DIT_CONTENT_RULE_DESCR`
      `constant Protocols.LDAP.SYNTAX_FACSIMILE_PHONE_NUM`
      `constant Protocols.LDAP.SYNTAX_FAX`
      `constant Protocols.LDAP.SYNTAX_GENERALIZED_TIME`
      `constant Protocols.LDAP.SYNTAX_IA5_STR`
      `constant Protocols.LDAP.SYNTAX_INT`
      `constant Protocols.LDAP.SYNTAX_JPEG`
      `constant Protocols.LDAP.SYNTAX_MATCHING_RULE_DESCR`
      `constant Protocols.LDAP.SYNTAX_MATCHING_RULE_USE_DESCR`
      `constant Protocols.LDAP.SYNTAX_MHS_OR_ADDR`
      `constant Protocols.LDAP.SYNTAX_NAME_AND_OPTIONAL_UID`
      `constant Protocols.LDAP.SYNTAX_NAME_FORM_DESCR`
      `constant Protocols.LDAP.SYNTAX_NUMERIC_STRING`
      `constant Protocols.LDAP.SYNTAX_OBJECT_CLASS_DESCR`
      `constant Protocols.LDAP.SYNTAX_OID`
      `constant Protocols.LDAP.SYNTAX_OTHER_MAILBOX`
      `constant Protocols.LDAP.SYNTAX_POSTAL_ADDR`
      `constant Protocols.LDAP.SYNTAX_PRESENTATION_ADDR`
      `constant Protocols.LDAP.SYNTAX_PRINTABLE_STR`
      `constant Protocols.LDAP.SYNTAX_PHONE_NUM`
      `constant Protocols.LDAP.SYNTAX_UTC_TIME`
      `constant Protocols.LDAP.SYNTAX_LDAP_SYNTAX_DESCR`
      `constant Protocols.LDAP.SYNTAX_DIT_STRUCTURE_RULE_DESCR`

    Description

      LDAP syntax: Standard syntaxes from RFC 2252.

    Constant SYNTAX_CASE_EXACT_STR

      `constant Protocols.LDAP.SYNTAX_CASE_EXACT_STR`

    Description

      `"caseExactString"` is an alias used in e.g. RFC 2079.

      `constant Protocols.LDAP.SYNTAX_DELIVERY_METHOD`
      `constant Protocols.LDAP.SYNTAX_ENHANCED_GUIDE`
      `constant Protocols.LDAP.SYNTAX_GUIDE`
      `constant Protocols.LDAP.SYNTAX_OCTET_STR`
      `constant Protocols.LDAP.SYNTAX_TELETEX_TERMINAL_ID`
      `constant Protocols.LDAP.SYNTAX_TELETEX_NUM`
      `constant Protocols.LDAP.SYNTAX_SUPPORTED_ALGORITHM`

    Description

      LDAP syntax: Standard syntaxes from RFC 2256.

      `constant Protocols.LDAP.SYNTAX_AD_CASE_IGNORE_STR`
      `constant Protocols.LDAP.SYNTAX_AD_LARGE_INT`
      `constant Protocols.LDAP.SYNTAX_AD_OBJECT_SECURITY_DESCRIPTOR`

    Description

      LDAP syntax: Microsoft AD: Additional syntaxes used in AD. C.f. <http://community.roxen.com/(all)/developers/idocs/drafts/ draft-armijo-ldap-syntax-00.html>.

    Constant mapping

      `constant Protocols.LDAP.mapping`

    Description

      Mapping containing functions to decode charsets in syntaxes where that's necessary. If the syntax is complex in a way that makes the result ambiguous if decoded with a single charset transformation then it should typically not be decoded here.

      These decoders are used on all attribute values returned by Protocols.LDAP.client.result functions.

    Constant mapping

      `constant Protocols.LDAP.mapping`

    Description

      Mapping containing the reverse functions from syntax_decode_fns .

      `constant Protocols.LDAP.GUID_USERS_CONTAINER`
      `constant Protocols.LDAP.GUID_COMPUTERS_CONTAINER`
      `constant Protocols.LDAP.GUID_SYSTEMS_CONTAINER`
      `constant Protocols.LDAP.GUID_DOMAIN_CONTROLLERS_CONTAINER`
      `constant Protocols.LDAP.GUID_INFRASTRUCTURE_CONTAINER`
      `constant Protocols.LDAP.GUID_DELETED_OBJECTS_CONTAINER`
      `constant Protocols.LDAP.GUID_LOSTANDFOUND_CONTAINER`
      `constant Protocols.LDAP.GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER`
      `constant Protocols.LDAP.GUID_PROGRAM_DATA_CONTAINER`
      `constant Protocols.LDAP.GUID_MICROSOFT_PROGRAM_DATA_CONTAINER`
      `constant Protocols.LDAP.GUID_NTDS_QUOTAS_CONTAINER`

    Description

      Constants for Microsoft AD Well-Known Object GUIDs. These are e.g. used in LDAP URLs:

      "ldap://server/<WKGUID=" + Protocols.LDAP.GUID_USERS_CONTAINER + ",dc=my,dc=domain,dc=com>"

  Method get_constant_name

    `string get_constant_name(mixed val)`

  Description

    If val matches any non-integer constant in this module, its name is returned.

  Method parse_ldap_url

    `mapping(string:mixed) parse_ldap_url(string ldap_url)`

  Description

    Parses an LDAP URL and returns its fields in a mapping.

  Returns

    The returned mapping contains these fields:

    `scheme : string` | The URL scheme, either `"ldap"` or `"ldaps"`.
    `host : string` | Self-explanatory.
    `port : int`
    `basedn : string`
    `attributes : array(string)` | Array containing the attributes. Undefined if none was specified.
    `scope : int` | The scope as one of the `SEARCH_*` constants. Undefined if none was specified.
    `filter : string` | The search filter. Undefined if none was specified.
    `ext : mapping(string:string|int(1..1))` | The extensions. Undefined if none was specified. The mapping values are `1` for extensions without values. Critical extensions are checked and the leading `"!"` do not remain in the mapping indices.
    `url : string` | The original unparsed URL.

  See also

    get_parsed_url

  Method make_filter

    `object make_filter(string filter, void|int ldap_version)`

  Description

    Parses an LDAP filter string into an ASN1 object tree that can be given to Protocols.LDAP.search .

    Using this function instead of giving the filter string directly to the search function has two advantages: This function provides better error reports for syntax errors, and the same object tree can be used repeatedly to avoid reparsing the filter string.

  Parameter `filter`

    The filter to parse, according to the syntax specified in RFC 2254. The syntax is extended a bit to allow and ignore whitespace everywhere except inside and next to the filter values.

  Parameter `ldap_version`

    LDAP protocol version to make the filter for. This controls what syntaxes are allowed depending on the protocol version. Also, if the protocol is `3` or later then full Unicode string literals are supported. The default is the latest supported version.

  Returns

    An ASN1 object tree representing the filter.

  Throws

    FilterError is thrown if there's a syntax error in the filter.

  Method get_cached_filter

    `object get_cached_filter(string filter, void|int ldap_version)`

  Description

    Like make_filter but saves the generated objects for reuse. Useful for filters that reasonably will occur often. The cache is never garbage collected, however.

  Throws

    If there's a parse error in the filter then a FilterError is thrown as from make_filter .

  Method get_connection

    `object get_connection(string ldap_url, void|string binddn, void|string password, void|int version)`

  Description

    Returns a client connection to the specified LDAP URL. If a bind DN is specified (either through a `"bindname"` extension in ldap_url or, if there isn't one, through binddn ) then the connection will be bound using that DN and the optional password. If no bind DN is given then any connection is returned, regardless of the bind DN it is using.

    version may be used to specify the required protocol version in the bind operation. If zero or left out, a bind attempt with the default version (currently `3`) is done with a fallback to `2` if that fails. Also, a cached connection for any version might be returned if version isn't specified.

    As opposed to creating an Protocols.LDAP.client instance directly, this function can return an already established connection for the same URL, provided connections are given back using return_connection when they aren't used anymore.

    A client object with an error condition is returned if there's a bind error, e.g. invalid password.

  Method return_connection

    `void return_connection(object conn)`

  Description

    Use this to return a connection to the connection pool after you've finished using it. The connection is assumed to be working.

  Note

    Ensure that persistent connection settings such as the scope and the base DN are restored to the defaults

  Method num_connections

    `int num_connections(string ldap_url)`

  Description

    Returns the number of currently stored connections for the given LDAP URL.

  CLASS Protocols.LDAP.FilterError

    Description

      Error object thrown by make_filter for parse errors.

    Constant is_ldap_filter_error

      `constant Protocols.LDAP.FilterError.is_ldap_filter_error`

    Description

      Recognition constant.

  CLASS Protocols.LDAP.protocol

    Method error_number

      `int error_number()`

    Description

      Returns the error number from the last transaction. If the error is LDAP_SERVER_DOWN then there was a socket error, and the I/O error number can be retrieved using `<font face='courier'>ldapfd` ->errno().

    See also

      error_string , server_error_string

    Method error_string

      `string error_string()`

    Description

      Returns the description of the error from the last transaction. This is the error string from the server, or a standard error message corresponding to the error number if the server didn't provide any description.

      If error_number returns LDAP_SERVER_DOWN then this is the strerror message corresponding to the I/O error for the connection.

    See also

      server_error_string , error_number

    Method server_error_string

      `string server_error_string()`

    Description

      Returns the error string from the server, or zero if the server didn't provide any.

    See also

      error_string , error_number

    Method get_last_io_time

      `int get_last_io_time()`

    Description

      Returns when I/O was made last. Useful to find out whether it's safe to continue using a connection that has been idle for some time.

  CLASS Protocols.LDAP.client

    Description

      Contains the client implementation of the LDAP protocol. All of the version 2 protocol features are implemented but only the base parts of the version 3.

    Inherit protocol

      inherit .protocol : protocol

    Variable info

      `mapping Protocols.LDAP.client.info`

    Description

      Several information about code itself and about active connection too

    Method create

      `void Protocols.LDAP.client()`
      `void Protocols.LDAP.client(string url)`
      `void Protocols.LDAP.client(string url, object context)`

    Description

      Create object. The first optional argument can be used later for subsequence operations. The second one can specify TLS context of connection. The default context only allows 128-bit encryption methods, so you may need to provide your own context if your LDAP server supports only export encryption.

    Parameter `url`

      LDAP server URL on the form `"ldap://hostname/basedn?attrlist?scope?ext"`. See RFC 2255. It can also be a mapping as returned by Protocol.LDAP.parse_ldap_url .

    Parameter `context`

      TLS context of connection

    See also

      LDAP.client.bind , LDAP.client.search

    Method reset_options

      `void reset_options()`

    Description

      Resets all connection options, such as the scope and the base DN, to the defaults determined from the LDAP URL when the connection was created.

    Method start_tls

      `int start_tls(void|SSL.context context)`

    Description

      Requests that a SSL/TLS session be negotiated on the connection. If the connection is already secure, this call will fail.

    Parameter `context`

      an optional SSL.context object to provide to the SSL/TLS connection client.

      Returns `1` on success, `0` otherwise.

    Method bind

      `int bind()`
      `int bind(string dn, string password)`
      `int bind(string dn, string password, int version)`

    Description

      Authenticates connection to the direcory.

      First form uses default value previously entered in create.

      Second form uses value from parameters:

    Parameter `dn`

      The distinguished name (DN) of an entry aginst which will be made authentication.

    Parameter `password`

      Password used for authentication.

      Third form allows specify the version of LDAP protocol used by connection to the LDAP server.

    Parameter `version`

      The desired protocol version (current `2` or `3`). Defaults to `3` if zero or left out.

    Returns

      Returns `1` on success, `0` otherwise.

    Note

      Only simple authentication type is implemented. So be warned clear text passwords are sent to the directory server.

    Note

      The API change: the returning code was changed in Pike 7.3+ to follow his logic better.

    Method unbind

      `int unbind()`

    Description

      Unbinds from the directory and close the connection.

    Method delete

      `int delete(string dn)`

    Description

      Deletes entry from the LDAP server.

    Parameter `dn`

      The distinguished name of deleted entry.

    Returns

      Returns `1` on success, `0` otherwise.

    Note

      The API change: the returning code was changed in Pike 7.3+ to follow his logic better.

    Method compare

      `int compare(string dn, string attr, string value)`

    Description

      Compares an attribute value with one in the directory.

    Parameter `dn`

      The distinguished name of the entry.

    Parameter `attr`

      The type (aka name) of the attribute to compare.

    Parameter `value`

      The value to compare with. It's UTF-8 encoded automatically if the attribute syntax specifies that.

    Returns

      Returns `1` if at least one of the values for the attribute in the directory is equal to value , `0` if it didn't match or there was some error (use error_number to find out).

    Note

      This function has changed arguments since version 7.6. From 7.3 to 7.6 it was effectively useless since it always returned true.

    Note

      The equality matching rule for the attribute governs the comparison. There are attributes where the assertion syntax used here isn't the same as the attribute value syntax.

    Method add

      `int add(string dn, mapping(string:array(string)) attrs)`

    Description

      The Add Operation allows a client to request the addition of an entry into the directory

    Parameter `dn`

      The Distinguished Name of the entry to be added.

    Parameter `attrs`

      The mapping of attributes and their values that make up the content of the entry being added. Values that are sent UTF-8 encoded according the the attribute syntaxes are encoded automatically.

    Returns

      Returns `1` on success, `0` otherwise.

    Note

      The API change: the returning code was changed in Pike 7.3+ to follow his logic better.

    Method get_root_dse_attr

      `array(string) get_root_dse_attr(string attr)`

    Description

      Returns the value of an attribute in the root DSE (DSA-Specific Entry) of the bound server. The result is cached. A working connection is assumed.

    Returns

      The return value is an array of the attribute values, which have been UTF-8 decoded where appropriate.

      Don't be destructive on the returned array.

    Note

      This function intentionally does not try to simplify the return values for single-valued attributes (c.f. Protocols.LDAP.SEARCH_MULTIVAL_ARRAYS_ONLY ). That since (at least) Microsoft AD has a bunch of attributes in the root DSE that they don't bother to provide schema entries for. The return value format wouldn't be reliable if they suddenly change that.

    Method get_supported_controls

      `multiset(string) get_supported_controls()`

    Description

      Returns a multiset containing the controls supported by the server. They are returned as object identifiers on string form. A working connection is assumed.

    See also

      search

    Method make_filter

      `object make_filter(string filter)`

    Description

      Returns the ASN1 object parsed from the given filter. This is a wrapper for Protocols.LDAP.make_filter which parses the filter with the LDAP protocol version currently in use by this connection.

    Throws

      If there's a parse error in the filter then a Protocols.LDAP.FilterError is thrown as from Protocols.LDAP.make_filter .

    Method get_cached_filter

      `object get_cached_filter(string filter)`

    Description

      This is a wrapper for Protocols.LDAP.get_cached_filter which passes the LDAP protocol version currently in use by this connection.

    Throws

      If there's a parse error in the filter then a Protocols.LDAP.FilterError is thrown as from Protocols.LDAP.make_filter .

    Method get_default_filter

      `object get_default_filter()`

    Description

      Returns the ASN1 object parsed from the filter specified in the LDAP URL, or zero if the URL doesn't specify any filter.

    Throws

      If there's a parse error in the filter then a Protocols.LDAP.FilterError is thrown as from Protocols.LDAP.make_filter .

    Method search

      `result|int search(string|object|void filter, array(string)|void attrs, int|void attrsonly, void|mapping(string:array(int|string)) controls, void|int flags)`

    Description

      Search LDAP directory.

    Parameter `filter`

      Search filter to override the one from the LDAP URL. It's either a string with the format specified in RFC 2254, or an object returned by Protocols.LDAP.make_filter .

    Parameter `attrs`

      The array of attribute names which will be returned by server for every entry.

    Parameter `attrsonly`

      This flag causes server return only the attribute types (aka names) but not their values. The values will instead be empty arrays or - if Protocols.LDAP.SEARCH_MULTIVAL_ARRAYS_ONLY is given - zeroes for single-valued attributes.

    Parameter `controls`

      Extra controls to send in the search query, to modify how the server executes the search in various ways. The value is a mapping with an entry for each control.

      `object_identifier : string`

      The index is the object identifier in string form for the control type. There are constants in Protocols.LDAP for the object identifiers for some known controls.

      The mapping value is an array of two elements:

      Array
      `int 0` | The first element is an integer flag that specifies whether the control is critical or not. If it is nonzero, the server returns an error if it doesn't understand the control. If it is zero, the server ignores it instead.
      `string|int(0..0) 1` | The second element is the string value to pass with the control. It may also be zero to not pass any value at all.

    Parameter `flags`

      Bitfield with flags to control various behavior at the client side of the search operation. See the `Protocol.LDAP.SEARCH_*` constants for details.

    Returns

      Returns object LDAP.client.result on success, `0` otherwise.

    Note

      The API change: the returning code was changed in Pike 7.3+ to follow his logic better.

    See also

      result , result.fetch , read , get_supported_controls , Protocols.LDAP.ldap_encode_string , Protocols.LDAP.make_filter

    Method read

      `mapping(string:string|array(string)) read(string object_name, void|string filter, void|array(string) attrs, void|int attrsonly, void|mapping(string:array(int|string)) controls, void|int flags)`

    Description

      Reads a specified object in the LDAP server. object_name is the distinguished name for the object. The rest of the arguments are the same as to search .

      The default filter and attributes that might have been set in the LDAP URL doesn't affect this call. If filter isn't set then `"(objectClass=*)"` is used.

    Returns

      Returns a mapping of the requested attributes. It has the same form as the response from result.fetch .

    See also

      search

    Method read_attr

      `string|array(string) read_attr(string object_name, string attr, void|string filter, void|mapping(string:array(int|string)) controls)`

    Description

      Reads a specified attribute of a specified object in the LDAP server. object_name is the distinguished name of the object and attr is the attribute. The rest of the arguments are the same as to search .

      The default filter that might have been set in the LDAP URL doesn't affect this call. If filter isn't set then `"(objectClass=*)"` is used.

    Returns

      For single-valued attributes, the value is returned as a string. For multivalued attributes, the value is returned as an array of strings. Returns zero if there was an error.

    See also

      read , get_root_dse_attr

    Method get_protocol_version

      `int get_protocol_version()`

    Description

      Return the LDAP protocol version in use.

    Method set_basedn

      `string set_basedn(string base_dn)`

    Description

      Sets the base DN for searches using search and schema queries using get_attr_type_descr .

    Note

      For compatibility, the old base DN is returned. However, if LDAPv3 is used, the value is UTF-8 encoded. Use get_basedn separately instead.

    Method get_basedn

      `string get_basedn()`

    Description

      Returns the current base DN for searches using search and schema queries using get_attr_type_descr .

    Method get_bound_dn

      `string get_bound_dn()`

    Description

      Returns the bind DN currently in use for the connection. Zero is returned if the connection isn't bound. The empty string is returned if the connection is in use but no bind DN has been given explicitly to bind .

    Method get_bind_password_hash

      `string get_bind_password_hash()`

    Description

      Returns an MD5 hash of the password used for the bind operation, or zero if the connection isn't bound. If no password was given to bind then an empty string was sent as password, and the MD5 hash of that is therefore returned.

    Method set_scope

      `int set_scope(int|string scope)`

    Description

      Sets value of scope for search operation.

    Parameter `scope`

      The value can be one of the `SCOPE_*` constants or a string `"base"`, `"one"` or `"sub"`.

    Returns

      Returns the `SCOPE_*` constant for the old scope.

    Method get_scope

      `string get_scope()`

    Description

      Return the currently set scope as a string `"base"`, `"one"`, or `"sub"`.

    Method set_option

      `int set_option(int opttype, int value)`

    Parameter `option_type`

      LDAP_OPT_xxx

    Parameter `value`

      new value for option

    Method get_option

      `int get_option(int opttype)`

    Parameter `option_type`

      LDAP_OPT_xxx

    Method get_parsed_url

      `mapping(string:mixed) get_parsed_url()`

    Description

      Returns a mapping containing the data parsed from the LDAP URL passed to create . The mapping has the same format as the return value from Protocols.LDAP.parse_ldap_url . Don't be destructive on the returned value.

    Method modifydn

      `int modifydn(string dn, string newrdn, int deleteoldrdn, string|void newsuperior)`

    Description

      The Modify DN Operation allows a client to change the leftmost (least significant) component of the name of an entry in the directory, or to move a subtree of entries to a new location in the directory.

    Parameter `dn`

      DN of source object

    Parameter `newrdn`

      RDN of destination

    Parameter `deleteoldrdn`

      The parameter controls whether the old RDN attribute values are to be retained as attributes of the entry, or deleted from the entry.

    Parameter `newsuperior`

      If present, this is the Distinguished Name of the entry which becomes the immediate superior of the existing entry.

    Returns

      Returns `1` on success, `0` otherwise.

    Note

      The API change: the returning code was changed in Pike 7.3+ to follow his logic better.

    Method modify

      `int modify(string dn, mapping(string:array(int(0..2)|string)) attropval)`

    Description

      The Modify Operation allows a client to request that a modification of an entry be performed on its behalf by a server.

    Parameter `dn`

      The distinguished name of modified entry.

    Parameter `attropval`

      The mapping of attributes with requested operation and attribute's values.

      attropval=([ attribute: ({operation, value1, value2, ...}) ])

    Where operation is one of the following:

    Protocols.LDAP.MODIFY_ADD

      Add values listed to the given attribute, creating the attribute if necessary.

    Protocols.LDAP.MODIFY_DELETE

      Delete values listed from the given attribute, removing the entire attribute if no values are listed, or if all current values of the attribute are listed for deletion.

    Protocols.LDAP.MODIFY_REPLACE

      Replace all existing values of the given attribute with the new values listed, creating the attribute if it did not already exist. A replace with no value will delete the entire attribute if it exists, and is ignored if the attribute does not exist.

    Values that are sent UTF-8 encoded according the the attribute syntaxes are encoded automatically.

  Returns

    Returns `1` on success, `0` otherwise.

  Note

    The API change: the returning code was changed in Pike 7.3+ to follow his logic better.

  Method get_referrals

    `array|int get_referrals()`

  Description

    Gets referrals.

  Returns

    Returns array of referrals or `0`.

  Method parse_url

    `mapping(string:mixed) parse_url(string ldapuri)`

  Description

    Compatibility alias for Protocols.LDAP.parse_ldap_url .

  Method get_attr_type_descr

    `mapping(string:mixed) get_attr_type_descr(string attr, void|int standard_attrs)`

  Description

    Returns the attribute type description for the given attribute, which includes the name, object identifier, syntax, etc (see section 4.2 in RFC 2252 for details).

    This might do a query to the server, but results are cached.

  Parameter `attr`

    The name of the attribute. Might also be the object identifier on string form.

  Parameter `standard_attrs`

    Flag that controls how the known standard attributes stored in Protocols.LDAP are to be used:

    `0` | Check the known standard attributes first. If the attribute isn't found there, query the server. This is the default.
    `1` | Don't check the known standard attributes, i.e. always use the schema from the server.
    `2` | Only check the known standard attributes. The server is never contacted.

  Returns

    Returns a mapping where the indices are the terms that the server has returned and the values are their values on string form (dequoted and converted from UTF-8 as appropriate). Terms without values get `1` as value in the mapping.

    The mapping might contain the following members (all except `"oid"` are optional):

    `"oid" : string` | The object identifier on string form. According to the RFC, this should always be a dotted decimal string. However some LDAP servers, e.g. iPlanet, allows registering attributes without an assigned OID. In such cases this can be some other string. In the case of iPlanet, it uses the attribute name with "-oid" appended (c.f. http://docs.sun.com/source/816-5606-10/scmacfg.htm).
    `"NAME" : string` | Array with one or more names used for the attribute.
    `"DESC" : string` | Description.
    `"OBSOLETE" : string` | Flag.
    `"SUP" : string` | Derived from this other attribute. The value is the name or oid of it. Note that the attribute description from the referenced type always is merged with the current one to make the returned description complete.
    `"EQUALITY" : string` | The value is the name or oid of a matching rule.
    `"ORDERING" : string` | The value is the name or oid of a matching rule.
    `"SUBSTR" : string` | The value is the name or oid of a matching rule.
    `"syntax_oid" : string` | The value is the oid of the syntax (RFC 2252, section 4.3.2). (This is extracted from the `"SYNTAX"` term.)
    `"syntax_len" : string` | Optional suggested minimum upper bound of the number of characters in the attribute (or bytes if the attribute is binary). (This is extracted from the `"SYNTAX"` term.)
    `"SINGLE-VALUE" : string` | Flag. Default multi-valued.
    `"COLLECTIVE" : string` | Flag. Default not collective.
    `"NO-USER-MODIFICATION" : string` | Flag. Default user modifiable.

    `"USAGE" : string`

    The value is any of the following:

    `"userApplications"` | Self-explanatory.
    `"directoryOperation"`
    `"distributedOperation"` | DSA-shared.
    `"dSAOperation"` | DSA-specific, value depends on server.

    There might be more fields for server extensions.

    Zero is returned if the server didn't provide any attribute type description for attr .

  Note

    It's the schema applicable at the base DN that is queried.

  Note

    LDAPv3 is assumed.

  CLASS Protocols.LDAP.client.result

    Description

      Contains the result of a LDAP search.

    See also

      LDAP.client.search , LDAP.client.result.fetch

    Method create

      `object|int Protocols.LDAP.client.result(array(object) entries, int stuff, int flags)`

    Description

      You can't create instances of this object yourself. The only way to create it is via a search of a LDAP server.

    Method error_number

      `int error_number()`

    Description

      Returns the error number in the search result.

    See also

      error_string , server_error_string

    Method error_string

      `string error_string()`

    Description

      Returns the description of the error in the search result. This is the error string from the server, or a standard error message corresponding to the error number if the server didn't provide any description.

    See also

      server_error_string , error_number

    Method server_error_string

      `string server_error_string()`

    Description

      Returns the error string from the server, or zero if the server didn't provide any.

    See also

      error_string , error_number

    Method num_entries

      `int num_entries()`

    Description

      Returns the number of entries.

    See also

      LDAP.client.result.count_entries

    Method count_entries

      `int count_entries()`

    Description

      Returns the number of entries from the current cursor position to the end of the list.

    See also

      LDAP.client.result.first , LDAP.client.result.next

    Method fetch

      `ResultEntry fetch(int|void idx)`

    Description

      Returns the current entry pointed to by the cursor.

    Parameter `index`

      This optional argument can be used for direct access to an entry other than the one currently pointed to by the cursor.

    Returns

      The return value is a mapping describing the entry:

      `attribute : string`

      An attribute in the entry. The value is an array containing the returned attribute value(s) on string form, or a single string if Protocols.LDAP.SEARCH_MULTIVAL_ARRAYS_ONLY was given to search and the attribute is typed as single valued.

      If Protocols.LDAP.SEARCH_RETURN_DECODE_ERRORS was given to search then Locale.Charset.DecodeError objects are returned in place of a string whenever an attribute value fails to be decoded.

      `"dn" : string` | This special entry contains the object name of the entry as a distinguished name. This might also be a Locale.Charset.DecodeError if Protocols.LDAP.SEARCH_RETURN_DECODE_ERRORS was given to search .

      Zero is returned if the cursor is outside the valid range of entries.

    Throws

      Unless Protocols.LDAP.SEARCH_RETURN_DECODE_ERRORS was given to search , a Locale.Charset.DecodeError is thrown if there is an error decoding the DN or any attribute value.

    Note

      It's undefined whether or not destructive operations on the returned mapping will affect future fetch calls for the same entry.

    Note

      In Pike 7.6 and earlier, the special `"dn"` entry was incorrectly returned in UTF-8 encoded form for LDAPv3 connections.

    See also

      fetch_all

    Method get_dn

      `string|Locale.Charset.DecodeError get_dn()`

    Description

      Returns distinguished name (DN) of the current entry in the result list. Note that this is the same as getting the `"dn"` field from the return value from fetch .

    Note

      In Pike 7.6 and earlier, this field was incorrectly returned in UTF-8 encoded form for LDAPv3 connections.

    Method first

      `void first()`

    Description

      Initialized the result cursor to the first entry in the result list.

    See also

      LDAP.client.result.next

    Method next

      `int next()`

    Description

      Moves the result cursor to the next entry in the result list. Returns number of remained entries in the result list. Returns 0 at the end.

    See also

      LDAP.client.result.next

    Method fetch_all

      `array(ResultEntry) fetch_all()`

    Description

      Convenience function to fetch all entries at once. The cursor isn't affected.

    Returns

      Returns an array where each element is the entry from the result. Don't be destructive on the returned value.

    Throws

      Unless Protocols.LDAP.SEARCH_RETURN_DECODE_ERRORS was given to search , a Locale.Charset.DecodeError is thrown if there is an error decoding the DN or any attribute value.

    See also

      fetch

Module Protocols.LysKOM

  CLASS Protocols.LysKOM.Connection

    Description

      This class contains nice abstraction for calls into the server. They are named "`call`", "`async_call`" or "`async_cb_call`", depending on how you want the call to be done.

    Method XXX
    Method async_XXX
    Method async_cb_XXX

      `mixed XXX(mixed ... args)`
      `object async_XXX(mixed ... args)`
      `object async_cb_XXX(function callback, mixed ... args)`

    Description

      Do a call to the server. This really clones a Protocols.LysKOM.Request object, and initialises it. `XXX` is to be read as one of the calls in the lyskom protocol. ('-' is replaced with '_'.) (ie, logout, async_login or async_cb_get_conf_stat.)

      The first method is a synchronous call. This will send the command, wait for the server to execute it, and then return the result.

      The last two are asynchronous calls, returning an initialised Protocols.LysKOM.Request object.

      `int Protocols.LysKOM.Connection.protocol_level`
      `string Protocols.LysKOM.Connection.session_software`
      `string Protocols.LysKOM.Connection.software_version`

    Description

      Description of the connected server.

    Method create

      `void Protocols.LysKOM.Connection(string server)`
      `void Protocols.LysKOM.Connection(string server, mapping options)`

    Description

      The options argument is a mapping with the following members:

      `"login" : int|string` | login as this person number (get number from name).
      `"password" : string` | send this login password.
      `"invisible" : int(0..1)` | if set, login invisible.
      `"port" : int(0..65535)` | server port (default is 4894).
      `"whoami" : string` | present as this user (default is from uid/getpwent and hostname).

  CLASS Protocols.LysKOM.Session

    Variable user

      `object Protocols.LysKOM.Session.user`

    Description

      This variable contains the Protocols.LysKOM.Session.Person that is logged in.

    Method create

      `void Protocols.LysKOM.Session(string server)`
      `void Protocols.LysKOM.Session(string server, mapping options)`

    Description

      Initializes the session object, and opens a connection to that server.

      options is a mapping of options:

      `"login" : int|string` | login as this person number (get number from name).
      `"create" : string` | create a new person and login with it.
      `"password" : string` | send this login password.
      `"invisible" : int(0..1)` | if set, login invisible.
      `"port" : int(0..65535)` | server port (default is 4894).
      `"whoami" : string` | present as this user (default is from uid/getpwent and hostname).

    See also

      Connection

    Method text

      `Text text(int no)`

    Description

      Returns the text no .

    Method person

      `Person person(int no)`

    Description

      Returns the Person no .

    Method conference

      `Conference conference(int no)`

    Description

      Returns conference number no .

    Method try_complete_person

      `array(ProtocolTypes.ConfZInfo) try_complete_person(string orig)`

    Description

      Runs a LysKOM completion on the given string, returning an array of confzinfos of the match.

    Method login

      `object login(int user_no, string password)`
      `object login(int user_no, string password, int invisible)`

    Description

      Performs a login. Throws a lyskom error if unsuccessful.

    Returns

      The session object logged in.

    Method create_person

      `object create_person(string name, string password)`

    Description

      Create a person, which will be logged in. returns the new person object

    Method logout

      `this_program logout()`

    Description

      Logouts from the server. returns the called object

    Method create_text

      `object create_text(string subject, string body, mapping options)`
      `object create_text(string subject, string body, mapping options, function callback, mixed ... extra)`

    Description

      Creates a new text.

      if callback is given, the function will be called when the text has been created, with the text as first argument. Otherwise, the new text is returned.

      options is a mapping that may contain:

      `"recpt" : Conference|array(Conference)` | recipient conferences.
      `"cc" : Conference|array(Conference)` | cc-recipient conferences.
      `"bcc" : Conference|array(Conference)` | bcc-recipient conferences*.
      `"comm_to" : Text|array(Text)` | The text(s) to be commented.
      `"foot_to" : Text|array(Text)` | The text(s) to be footnoted.
      `"anonymous" : int(0..1)` | send text anonymously.
      `"aux_items" : array(AuxItemInput)` | AuxItems you want to set for the text*.

    Note

      The items above marked with '*' are only available on protocol 10 servers. A LysKOM error will be thrown if the call fails.

    See also

      Conference.create_text() , Text.comment() , Text.footnote()

    Method send_message

      `object|void send_message(string textstring, mapping options)`

    Description

      Sends a message.

      options is a mapping that may contain:

      `"recpt" : Conference` | recipient conference.

    Method register_async_message_callback

      `void register_async_message_callback(function(int:void) cb)`

    CLASS Protocols.LysKOM.Session.AuxItemInput

      FIXME

        Undocumented

      Inherit AuxItemInput

        inherit ProtocolTypes.AuxItemInput : AuxItemInput

    CLASS Protocols.LysKOM.Session.AuxItems

      FIXME

        Undocumented

    CLASS Protocols.LysKOM.Session.Text

      Description

        All variables in this class is read only.

      FIXME

        Undocumented

      Variable no

        `int Protocols.LysKOM.Session.Text.no`

      Description

        The text number, as spicified to create .

      Variable err

        `object Protocols.LysKOM.Session.Text.err`

      Description

        Undocumented

      Method create

        `void Protocols.LysKOM.Session.Text(string textnumber)`

      Description

        Initializes a Text object.

      Method mark_as_read

        `void mark_as_read()`

      FIXME

        Undocumented.

        `mixed Protocols.LysKOM.Session.Text.prefetch_text`
        `mixed Protocols.LysKOM.Session.Text.prefetch_stat`
        `mixed Protocols.LysKOM.Session.Text.lines`
        `mixed Protocols.LysKOM.Session.Text.characters`
        `mixed Protocols.LysKOM.Session.Text.clear_stat`
        `mixed Protocols.LysKOM.Session.Text.aux_items`

      FIXME

        Undocumented

      Variable text

        `string Protocols.LysKOM.Session.Text.text`

      Description

        The actual text (or body if you wish).

      Variable subject

        `string Protocols.LysKOM.Session.Text.subject`

      Description

        The message subject.

      Variable author

        `string Protocols.LysKOM.Session.Text.author`

      Description

        The author of the text.

      Variable misc

        `mixed Protocols.LysKOM.Session.Text.misc`

      Description

        Misc info, including what conferences the message is posted to.

      FIXME

        Needs a more complete description.

      Variable marks

        `int Protocols.LysKOM.Session.Text.marks`

      Description

        The number of marks on this text.

      Variable creation_time

        `mixed Protocols.LysKOM.Session.Text.creation_time`

      Description

        The time the text was created on the server.

    CLASS Protocols.LysKOM.Session.Membership

      Description

        All variables in this class is read only.

      Variable last_time_read

        `object Protocols.LysKOM.Session.Membership.last_time_read`

      Variable priority

        `int(0..255) Protocols.LysKOM.Session.Membership.priority`

      Variable last_text_read

        `int Protocols.LysKOM.Session.Membership.last_text_read`

      Variable read_texts

        `array(int) Protocols.LysKOM.Session.Membership.read_texts`

      Variable added_at

        `object Protocols.LysKOM.Session.Membership.added_at`

      Variable type

        `multiset(string) Protocols.LysKOM.Session.Membership.type`

      Variable position

        `int Protocols.LysKOM.Session.Membership.position`

      Variable conf

        `object Protocols.LysKOM.Session.Membership.conf`

      Method number_unread

        `int number_unread()`

      Method query_read_texts

        `void query_read_texts()`

      Method unread_texts

        `array(object) unread_texts()`

    CLASS Protocols.LysKOM.Session.Person

      Variable no

        `int Protocols.LysKOM.Session.Person.no`

      Method create

        `void Protocols.LysKOM.Session.Person(int no)`

        `mixed Protocols.LysKOM.Session.Person.prefetch_stat`
        `mixed Protocols.LysKOM.Session.Person.prefetch_conf`
        `mixed Protocols.LysKOM.Session.Person.prefetch_membership`

      FIXME

        Undocumented

        `object Protocols.LysKOM.Session.Person.error`
        `Text Protocols.LysKOM.Session.Person.user_area`
        `mixed Protocols.LysKOM.Session.Person.username`
        `mixed Protocols.LysKOM.Session.Person.privileges`
        `mixed Protocols.LysKOM.Session.Person.flags`
        `mixed Protocols.LysKOM.Session.Person.last_login`
        `mixed Protocols.LysKOM.Session.Person.total_time_present`
        `mixed Protocols.LysKOM.Session.Person.sessions`
        `mixed Protocols.LysKOM.Session.Person.created_lines`
        `mixed Protocols.LysKOM.Session.Person.created_bytes`
        `mixed Protocols.LysKOM.Session.Person.read_texts`
        `mixed Protocols.LysKOM.Session.Person.no_of_text_fetches`
        `mixed Protocols.LysKOM.Session.Person.created_persons`
        `mixed Protocols.LysKOM.Session.Person.created_confs`
        `mixed Protocols.LysKOM.Session.Person.first_created_local_no`
        `mixed Protocols.LysKOM.Session.Person.no_of_created_texts`
        `mixed Protocols.LysKOM.Session.Person.no_of_marks`
        `mixed Protocols.LysKOM.Session.Person.no_of_confs`
        `mixed Protocols.LysKOM.Session.Person.unread`
        `int(0..0) Protocols.LysKOM.Session.Person.clear_membership`
        `mixed Protocols.LysKOM.Session.Person.membership`

      FIXME

        Undocumented

    CLASS Protocols.LysKOM.Session.Conference

      Method create

        `void Protocols.LysKOM.Session.Conference(int no)`

        `mixed Protocols.LysKOM.Session.Conference.prefetch_stat`
        `int Protocols.LysKOM.Session.Conference.no`
        `object Protocols.LysKOM.Session.Conference.error`
        `Text Protocols.LysKOM.Session.Conference.msg_of_day`
        `Conference Protocols.LysKOM.Session.Conference.supervisor`
        `Conference Protocols.LysKOM.Session.Conference.permitted_submitters`
        `Conference Protocols.LysKOM.Session.Conference.super_conf`
        `Person Protocols.LysKOM.Session.Conference.creator`
        `mixed Protocols.LysKOM.Session.Conference.aux_items`
        `mixed Protocols.LysKOM.Session.Conference.name`
        `mixed Protocols.LysKOM.Session.Conference.type`
        `mixed Protocols.LysKOM.Session.Conference.creation_time`
        `mixed Protocols.LysKOM.Session.Conference.last_written`
        `mixed Protocols.LysKOM.Session.Conference.nice`
        `mixed Protocols.LysKOM.Session.Conference.no_of_members`
        `mixed Protocols.LysKOM.Session.Conference.first_local_no`
        `mixed Protocols.LysKOM.Session.Conference.no_of_texts`
        `mixed Protocols.LysKOM.Session.Conference.presentation`

      FIXME

        Undocumented

  Module Protocols.LysKOM.Request

    Description

      This module contains nice abstraction for calls into the server. They are named "`call`", "`async_call`" or "`async_cb_call`", depending on how you want the call to be done.

    CLASS Protocols.LysKOM.Request._Request

      Description

        This is the main request class. All lyskom request classes inherit this class.

      Method async
      Method sync

        `void async(mixed ... args)`
        `mixed sync(mixed ... args)`

      Description

        Initialise an asynchronous or a synchronous call, the latter is also evaluating the result. This calls `indata()` in itself, to get the correct arguments to the lyskom protocol call.

      Method _async
      Method _sync

        `void _async(int call, mixed_data)`
        `mixed _sync(int call, mixed_data)`

      Description

        Initialise an asynchronous or a synchronous call, the latter is also evaluating the result. These are called by async and sync respectively.

      Method _reply
      Method reply

        `mixed _reply(object|array what)`
        `mixed reply(object|array what)`

      Description

        _reply() is called as callback to evaluate the result, and calls reply() in itself to do the real work.

      Method `()

        `mixed `()()`

      Description

        Wait for the call to finish.

      Variable ok

        `int(0..1) Protocols.LysKOM.Request._Request.ok`

      Description

        Tells if the call has executed ok

      Variable error

        `object Protocols.LysKOM.Request._Request.error`

      Description

        How the call failed. The call has completed if `(ok||error)`.

  Module Protocols.LysKOM.ProtocolTypes

    Description

      Data types as defined by the LysKOM protocol specification.

Module Protocols.X

  Module Protocols.X.Extensions

    CLASS Protocols.X.Extensions.extension

      Description

        an abstract class used to provide features for implimenting X11 extensions. Provides no useful functionality on its own.

      Method init

        `int init(object d)`

      Description

        initialize the extension.

      Parameter `d`

        An object of type Protocols.X.Xlib.Display

    CLASS Protocols.X.Extensions.XTEST

      Description

        Provides support for the X11 XTEST extension.

      Inherit extension

        inherit extension : extension

      Method create

        `void Protocols.X.Extensions.XTEST()`

      Description

        Create object.

      Method init

        `int init(object display)`

      Description

        Initialize the XTEST extension. Returns 1 if successful.

      Parameter `display`

        Protocols.X.Display object

      Method XTestFakeInput

        `void XTestFakeInput(string event_type, int detail, int delay, object|void window, int|void xloc, int|void yloc)`

      Description

        Send a synthetic event to an X server.

      Parameter `event_type`

        Type of event to send. Possible values: KeyPress: 2, KeyRelease: 3, ButtonPress: 4, ButtonRelease: 5, MotionNotify: 6

      Parameter `detail`

        Button (for Button events) or Keycode (for Key events) to send

      Parameter `delay`

        Delay before the X server simulates event. 0 indicates zero delay.

      Parameter `window`

        Window object that a motion event occurrs in. If no window is provided, the root window will be used.

      Parameter `xloc`

        For motion events, this is the relative X distance or absolute X coordinates.

      Parameter `yloc`

        For motion events, this is the relative Y distance or absolute Y coordinates.

      Method XTestGrabControl

        `void XTestGrabControl(int impervious)`

      Description

        Cause the executing client to become impervious to server grabs. That is, it can continue to execute requests even if another client grabs the server.

      Parameter `impervious`

        A true (non zero) value causes the client to perform as described above. If false (zero), server returns to the normal state of being susceptible to server grabs.

Module Protocols.SNMP

  Description

    SNMPv1 and v2c

  Constant ERROR_TOOBIG

    `constant Protocols.SNMP.ERROR_TOOBIG`

  Description

    Error tooBig

  Constant ERROR_NOERROR

    `constant Protocols.SNMP.ERROR_NOERROR`

  Description

    Error noError

  Constant ERROR_NOSUCHNAME

    `constant Protocols.SNMP.ERROR_NOSUCHNAME`

  Description

    Error noSuchName

  Constant ERROR_BADVALUE

    `constant Protocols.SNMP.ERROR_BADVALUE`

  Description

    Error badValue

  Constant ERROR_READONLY

    `constant Protocols.SNMP.ERROR_READONLY`

  Description

    Error readOnly

  Constant ERROR_GENERROR

    `constant Protocols.SNMP.ERROR_GENERROR`

  Description

    Error genError

  Constant REQUEST_GET

    `constant Protocols.SNMP.REQUEST_GET`

  Description

    PDU type Get

  Constant REQUEST_GETNEXT

    `constant Protocols.SNMP.REQUEST_GETNEXT`

  Description

    PDU type GetNext

  Constant REQUEST_SET

    `constant Protocols.SNMP.REQUEST_SET`

  Description

    PDU type Set

  Constant REQUEST_GET_RESPONSE

    `constant Protocols.SNMP.REQUEST_GET_RESPONSE`

  Description

    PDU type GetResponse

  Constant REQUEST_TRAP

    `constant Protocols.SNMP.REQUEST_TRAP`

  Description

    PDU type Trap

  CLASS Protocols.SNMP.protocol

    Description

      SNMP protocol implementation for Pike

      RFCs:

      implemented (yet): 1155-7 : v1

      1901-4 : v2/community (Bulk ops aren't implemented!)

      planned: 2742 : agentX

      2570 : v3 description

    Inherit snmp

      inherit Stdio.UDP : snmp

    Variable snmp_version

      `int Protocols.SNMP.protocol.snmp_version`

    Description

      SNMP version

      currently version 1 and 2 are supported.

    Variable snmp_community

      `string Protocols.SNMP.protocol.snmp_community`

    Description

      SNMP community string

      should be set to the appropriate SNMP community before sending a request.

    Note

      Set to "public" by default.

    Method create

      `void Protocols.SNMP.protocol(int|void rem_port, string|void rem_addr, int|void loc_port, string|void loc_addr)`

    Description

      create a new SNMP protocol object

    Parameter `rem_port`
    Parameter `rem_addr`

      remote address and UDP port (optional)

    Parameter `loc_port`
    Parameter `loc_addr`

      local address and UDP port (optional)

    Method readmsg

      `mapping readmsg(int|float|void timeout)`

    Description

      return the whole SNMP message in raw format

    Method decode_asn1_msg

      `mapping decode_asn1_msg(mapping rawd)`

    Description

      decode ASN1 data, if garbaged ignore it

    Method to_pool

      `void to_pool(mapping rawd)`

    Description

      decode raw pdu message and place in message pool

    Method readmsg_from_pool

      `mapping readmsg_from_pool(int msgid)`

    Description

      read decoded message from pool

    Method get_request

      `int get_request(array(string) varlist, string|void rem_addr, int|void rem_port)`

    Description

      GetRequest-PDU call

    Parameter `varlist`

      an array of OIDs to GET

    Parameter `rem_addr`
    Parameter `rem_port`

      remote address an UDP port to send request to (optional)

    Returns

      request ID

    Method get_response

      `int get_response(mapping varlist, mapping origdata, int|void errcode, int|void erridx)`

    Description

      GetResponse-PDU call

    Parameter `varlist`

      a mapping containing data to return

      `oid1 : array`

      Array
      `string type` | data type such as tick, oid, gauge, etc
      `mixed data` | data to return for oid1

      `oid2 : array`

      Array
      `string type` | data type such as tick, oid, gauge, etc
      `mixed data` | data to return for oid2

      `oidn : array`

      Array
      `string type` | data type such as tick, oid, gauge, etc
      `mixed data` | data to return for oidn

    Parameter `origdata`

      original received decoded pdu that this response corresponds to

    Parameter `errcode`

      error code

    Parameter `erridx`

      error index

    Returns

      request ID

    Method get_nextrequest

      `int get_nextrequest(array(string) varlist, string|void rem_addr, int|void rem_port)`

    Description

      GetNextRequest-PDU call

    Parameter `varlist`

      an array of OIDs to GET

    Parameter `rem_addr`
    Parameter `rem_port`

      remote address an UDP port to send request to (optional)

    Returns

      request ID

    Method set_request

      `int set_request(mapping varlist, string|void rem_addr, int|void rem_port)`

    Description

      SetRequest-PDU call

    Parameter `varlist`

      a mapping of OIDs to SET

      `oid1 : array`

      Array
      `string type` | data type such as tick, oid, gauge, etc
      `mixed data` | data to return for oid1

      `oid2 : array`

      Array
      `string type` | data type such as tick, oid, gauge, etc
      `mixed data` | data to return for oid2

      `oidn : array`

      Array
      `string type` | data type such as tick, oid, gauge, etc
      `mixed data` | data to return for oidn

    Parameter `rem_addr`
    Parameter `rem_port`

      remote address an UDP port to send request to (optional)

    Returns

      request ID

    Example

          // set the value of 1.3.6.1.4.1.1882.2.1 to "blah".
             object s=Protocols.SNMP.protocol();
             s->snmp_community="mysetcommunity";
             mapping req=(["1.3.6.1.4.1.1882.2.1": ({"str", "blah"})]);
             int id=s->set_request(req, "172.21.124.32");

    Method trap

      `int trap(mapping varlist, string oid, int type, int spectype, int ticks, string|void locip, string|void remaddr, int|void remport)`

    Description

      send an SNMP-v1 trap

    Parameter `varlist`

      a mapping of OIDs to include in trap

      `oid1 : array`

      Array
      `string type` | data type such as tick, oid, gauge, etc
      `mixed data` | data to return for oid1

      `oid2 : array`

      Array
      `string type` | data type such as tick, oid, gauge, etc
      `mixed data` | data to return for oid2

      `oidn : array`

      Array
      `string type` | data type such as tick, oid, gauge, etc
      `mixed data` | data to return for oidn

    Parameter `oid`
    Parameter `type`

      generic trap-type

    Parameter `spectype`

      specific trap-type

    Parameter `ticks`

      uptime

    Parameter `locip`

      originating ip address of the trap

    Parameter `remaddr`
    Parameter `remport`

      address and UDP to send trap to

    Returns

      request id

  CLASS Protocols.SNMP.agent

    Description

      A simple SNMP agent with support for SNMP Get requests

    Inherit "protocol"

      inherit "protocol"

    Method create

      `void Protocols.SNMP.agent(int|void port, string|void addr)`

    Description

      create a new instance of the agent

    Parameter `port`

      the port number to listen for requests on

    Parameter `addr`

      the address to bind to for listening

    Note

      only one agent may be bound to a port at one time the agent does not currently support SMUX or AGENTX or other agent multiplexing protocols.

    Method set_threaded

      `void set_threaded()`

    Description

      Run the agent event loop in a thread, if available.

    Method set_managers_only

      `void set_managers_only(int yesno)`

    Description

      enable manager access limits

    Parameter `yesno`

      1 to allow only managers to submit requests 0 to allow any host to submit requests

      default setting allows all requests from all hosts

    Method set_get_communities

      `void set_get_communities(array communities)`

    Description

      set the valid community strings for Get requests

    Parameter `communities`

      an array of valid Get communities

    Note

      send an empty array to disable Get requests

    Method set_set_communities

      `void set_set_communities(array communities)`

    Description

      set the valid community strings for Set requests

    Parameter `communities`

      an array of valid Set communities

    Note

      send an empty array to disable Set requests

    Method set_managers

      `void set_managers(array managers)`

    Description

      set the valid manager list for requests

    Parameter `managers`

      an array of valid management hosts

    Note

      send an empty array to disable all requests

    Method set_set_oid_callback

      `void set_set_oid_callback(string oid, function cb)`

    Description

      set the Set request callback function for an Object Identifier

    Parameter `oid`

      the string object identifier, such as 1.3.6.1.4.1.132.2 or an asterisk (*) to serve as the handler for all requests for which a handler is specified.

    Parameter `cb`

      the function to call when oid is requested by a manager the function should take 3 arguments: a string containing the requested oid, the desired value, and the body of the request as a mapping. The function should return an array containing 3 elements: The first is a boolean indicating success or failure. If success, the next 2 elements should be the SNMP data type of the result followed by the result itself. If failure, the next 2 elements should be the error-status such as Protocols.SNMP.ERROR_TOOBIG and the second is the error-index, if any.

    Note

      there can be only one callback per object identifier. calling this function more than once with the same oid will result in the new callback replacing the existing one.

    Method clear_set_oid_callback

      `int clear_set_oid_callback(string oid)`

    Description

      clear the Set callback function for an Object Identifier

    Parameter `oid`

      the string object identifier, such as 1.3.6.1.4.1.132.2 or an asterisk (*) to indicate the default handler.

    Returns

      1 if the callback existed, 0 otherwise

    Method get_set_oid_callback

      `void|function get_set_oid_callback(string oid)`

    Description

      get the Set request callback function for an Object Identifier

    Parameter `oid`

      the string object identifier, such as 1.3.6.1.4.1.132.2 or an asterisk (*) to indicate the default handler

    Returns

      the function associated with oid, if any

    Method set_get_oid_callback

      `void set_get_oid_callback(string oid, function cb)`

    Description

      set the Get request callback function for an Object Identifier

    Parameter `oid`

      the string object identifier, such as 1.3.6.1.4.1.132.2 or an asterisk (*) to serve as the handler for all requests for which a handler is specified.

    Parameter `cb`

      the function to call when oid is requested by a manager the function should take 2 arguments: a string containing the requested oid and the body of the request as a mapping. The function should return an array containing 3 elements: The first is a boolean indicating success or failure. If success, the next 2 elements should be the SNMP data type of the result followed by the result itself. If failure, the next 2 elements should be the error-status such as Protocols.SNMP.ERROR_TOOBIG and the second is the error-index, if any.

    Note

      there can be only one callback per object identifier. calling this function more than once with the same oid will result in the new callback replacing the existing one.

    Method clear_get_oid_callback

      `int clear_get_oid_callback(string oid)`

    Description

      clear the Get callback function for an Object Identifier

    Parameter `oid`

      the string object identifier, such as 1.3.6.1.4.1.132.2 or an asterisk (*) to indicate the default handler.

    Returns

      1 if the callback existed, 0 otherwise

    Method get_get_oid_callback

      `void|function get_get_oid_callback(string oid)`

    Description

      get the Get request callback function for an Object Identifier

    Parameter `oid`

      the string object identifier, such as 1.3.6.1.4.1.132.2 or an asterisk (*) to indicate the default handler

    Returns

      the function associated with oid, if any

Module Protocols.XMLRPC

  Description

    This module implements most features of the XML-RPC standard (see http://xml-rpc.org/).

    Translation rules for conversions from Pike datatypes to XML-RPC datatypes:

    Pike `int` is translated to XML-RPC `<int>`. Pike `string` is translated to XML-RPC `<string>`. Pike `float` is translated to XML-RPC `<double>`. Pike `mapping` is translated to XML-RPC `<struct>`. Pike `array` is translated to XML-RPC `<array>`. Pike Calendar object is translated to XML-RPC `<dateTime.iso8601`. Pike `Val.false` and `Val.true` is translated to XML-RPC `<boolean>`.

    Translation rules for conversions from XML-RPC datatypes to Pike datatypes:

    XML-RPC `<i4>` and `<int>` are translated to Pike `int`. XML-RPC `<boolean>` is translated to Pike `Val.true` and `Val.false`. XML-RPC `<string>` and `<base64>` are translated to Pike `string`. XML_RPC `<double>` is translated to Pike `float`. XML-RPC `<struct>` is translated to Pike `mapping`. XML-RPC `<array>` is translated to Pike `array`. XML-RPC `<dateTime.iso8601>` is translated to Pike Calendar object.

  Note

    The XML-RPC `<dateTime.iso8601>` datatype does not assume any time zone, but local time is always used in the conversion to Calendar objects.

  Method decode_call

    `Call decode_call(string xml_input)`

  Description

    Decodes a XML-RPC representation of a function call and returns a Call object.

  See also

    Call

  Method decode_response

    `array|Fault decode_response(string xml_input, int|void boolean)`

  Description

    Decodes a XML-RPC representation of a response and returns an array containing response values, or a Fault object.

  See also

    Fault

  Method encode_call

    `string encode_call(string method_name, array params)`

  Description

    Encodes a function call with the name method_name and the arguments params and returns the XML-RPC string representation.

  Method encode_response

    `string encode_response(array params)`

  Description

    Encodes a response containing the multiple values in params and returns the XML-RPC string representation.

  Method encode_response_fault

    `string encode_response_fault(int fault_code, string fault_string)`

  Description

    Encodes a response fault containing a fault_code and a fault_string and returns the XML-RPC string representation.

  CLASS Protocols.XMLRPC.Call

    Description

      Represents a function call made to a XML-RPC server.

    See also

      decode_call()

    syntax

      `string Protocols.XMLRPC.Call.method_name`
      `array Protocols.XMLRPC.Call.params` `void Protocols.XMLRPC.Call(string method_name, array params)`

    Variable method_name

      `int Protocols.XMLRPC.Call.method_name`

    Description

      Represents `<methodName>` in the XML-RPC standard.

    Variable params

      `array Protocols.XMLRPC.Call.params`

    Description

      Represents `<params>` in the XML-RPC standard where all datatypes have been converted to equivalent or similar datatypes in Pike.

  CLASS Protocols.XMLRPC.Fault

    Description

      Represents a fault response which can be one of the return values from a XML-RPC function call.

    See also

      decode_response()

    syntax

      `int Protocols.XMLRPC.Fault.fault_code`
      `string Protocols.XMLRPC.Fault.fault_string` `void Protocols.XMLRPC.Fault(int fault_code, string fault_string)`

    Variable fault_code

      `int Protocols.XMLRPC.Fault.fault_code`

    Description

      Represents `faultCode` in the XML-RPC standard.

    Variable fault_string

      `int Protocols.XMLRPC.Fault.fault_string`

    Description

      Represents `faultString` in the XML-RPC standard.

  CLASS Protocols.XMLRPC.Client

    Description

      This class implements an XML-RPC client that uses HTTP transport.

      There is an optional boolean flag to get the new behavior of booleans being returned as Val instead of ints.

    Example

             > Protocols.XMLRPC.Client client = Protocols.XMLRPC.Client("http://www.oreillynet.com/meerkat/xml-rpc/server.php");
             Result: Protocols.XMLRPC.Client("http://www.oreillynet.com/meerkat/xml-rpc/server.php");
             > client["system.listMethods"]();
             Result: ({ /* 1 element */
            		    ({ /* 9 elements */
            			"meerkat.getChannels",
            			"meerkat.getCategories",
            			"meerkat.getCategoriesBySubstring",
            			"meerkat.getChannelsByCategory",
            			"meerkat.getChannelsBySubstring",
            			"meerkat.getItems",
            			"system.listMethods",
            			"system.methodHelp",
            			"system.methodSignature"
            		    })
            		})

    syntax

      `string|Standards.URI Protocols.XMLRPC.Client.url`
      `int|void Protocols.XMLRPC.Client.boolean` `void Protocols.XMLRPC.Client(string|Standards.URI url, int|void boolean)`

  CLASS Protocols.XMLRPC.AsyncClient

    Description

      This class implements an XML-RPC client that uses HTTP transport using non blocking sockets.

      There is an optional boolean flag to get the new behavior of booleans being returned Val instead of ints.

    Example

          void data_ok(mixed result)
          {
            write("result=%O\n", result);
          }

          void fail()
          {
            write("fail\n");
          }

          int main(int argc, array argv)
          {
            object async_client = Protocols.XMLRPC.AsyncClient("http://www.oreillynet.com/meerkat/xml-rpc/server.php");
            async_client["system.listMethods"](data_ok, fail);
            return -1;

Module Protocols.HTTP

  Method do_proxied_method

    `.Query do_proxied_method(string|Standards.URI proxy, string user, string password, string method, string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con, void|string data)`

  Description

    Makes an HTTP request through a proxy.

  Parameter `proxy`

    URL for the proxy.

  Parameter `user`
  Parameter `password`

    Proxy authentication credentials.

  Parameter `method`
  Parameter `url`
  Parameter `query_variables`
  Parameter `request_headers`
  Parameter `con`
  Parameter `data`

    The remaining arguments are identical to do_method() .

  See also

    do_method() , do_async_proxied_method()

  Method do_method

    `.Query do_method(string method, string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con, void|string data)`

  Description

    Low level HTTP call method.

  Parameter `method`

    The HTTP method to use, e.g. `"GET"`.

  Parameter `url`

    The URL to perform method on. Should be a complete URL, including protocol, e.g. `"https://pike.ida.liu.se/"`.

  Parameter `query_variables`

    Calls http_encode_query and appends the result to the URL.

  Parameter `request_headers`

    The HTTP headers to be added to the request. By default the headers User-agent, Host and, if needed by the url, Authorization will be added, with generated contents. Providing these headers will override the default. Setting the value to 0 will remove that header from the request.

  Parameter `con`

    Old connection object.

  Parameter `data`

    Data payload to be transmitted in the request.

  See also

    do_sync_method()

  Method do_async_method

    `void do_async_method(string method, string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, Protocols.HTTP.Query con, void|string data)`

  Description

    Low level asynchronous HTTP call method.

  Parameter `method`

    The HTTP method to use, e.g. `"GET"`.

  Parameter `url`

    The URL to perform method on. Should be a complete URL, including protocol, e.g. `"https://pike.ida.liu.se/"`.

  Parameter `query_variables`

    Calls http_encode_query and appends the result to the URL.

  Parameter `request_headers`

    The HTTP headers to be added to the request. By default the headers User-agent, Host and, if needed by the url, Authorization will be added, with generated contents. Providing these headers will override the default. Setting the value to 0 will remove that header from the request.

  Parameter `con`

    Previously initialized connection object. In particular the callbacks must have been set (Query.set_callbacks() ).

  Parameter `data`

    Data payload to be transmitted in the request.

  See also

    do_method() , Query.set_callbacks()

  Method do_async_proxied_method

    `void do_async_proxied_method(string|Standards.URI proxy, string user, string password, string method, string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, Protocols.HTTP.Query con, void|string data)`

  Description

    Low level asynchronous proxied HTTP call method.

    Makes an HTTP request through a proxy.

  Parameter `proxy`

    URL for the proxy.

  Parameter `user`
  Parameter `password`

    Proxy authentication credentials.

  Parameter `method`

    The HTTP method to use, e.g. `"GET"`.

  Parameter `url`

    The URL to perform method on. Should be a complete URL, including protocol, e.g. `"https://pike.lysator.liu.se/"`.

  Parameter `query_variables`

    Calls http_encode_query and appends the result to the URL.

  Parameter `request_headers`

    The HTTP headers to be added to the request. By default the headers User-agent, Host and, if needed by the url, Authorization will be added, with generated contents. Providing these headers will override the default. Setting the value to 0 will remove that header from the request.

  Parameter `con`

    Previously initialized connection object. In particular the callbacks must have been set (Query.set_callbacks() ).

  Parameter `data`

    Data payload to be transmitted in the request.

  See also

    do_async_method() , do_proxied_method() , Query.set_callbacks()

  Method get_url

    `.Query get_url(string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

  Description

    Sends a HTTP GET request to the server in the URL and returns the created and initialized Query object. `0` is returned upon failure. If a query object having `request_headers->Connection=="Keep-Alive"` from a previous request is provided and the already established server connection can be used for the next request, you may gain some performance.

  Method put_url

    `.Query put_url(string|Standards.URI url, void|string file, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

  Description

    Sends a HTTP PUT request to the server in the URL and returns the created and initialized Query object. `0` is returned upon failure. If a query object having `request_headers->Connection=="Keep-Alive"` from a previous request is provided and the already established server connection can be used for the next request, you may gain some performance.

  Method delete_url

    `.Query delete_url(string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

  Description

    Sends a HTTP DELETE request to the server in the URL and returns the created and initialized Query object. `0` is returned upon failure. If a query object having `request_headers->Connection=="Keep-Alive"` from a previous request is provided and the already established server connection can be used for the next request, you may gain some performance.

  Method get_url_nice

    `array(string) get_url_nice(string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

  Description

    Returns an array of `({content_type, data})` after calling the requested server for the information. `0` is returned upon failure. Redirects (HTTP 302) are automatically followed.

  Method get_url_data

    `string get_url_data(string|Standards.URI url, void|mapping(string:int|string|array(string)) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

  Description

    Returns the returned data after calling the requested server for information through HTTP GET. `0` is returned upon failure. Redirects (HTTP 302) are automatically followed.

  Method post_url

    `.Query post_url(string|Standards.URI url, mapping(string:int|string|array(string))|string query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

  Description

    Similar to get_url , except that query variables is sent as a POST request instead of a GET request. If query_variables is a simple string, it is assumed to contain the verbatim body of the POST request; Content-Type must be properly specified manually, in this case.

  Method post_url_nice

    `array(string) post_url_nice(string|Standards.URI url, mapping(string:int|string|array(string))|string query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

  Description

    Similar to get_url_nice , except that query variables is sent as a POST request instead of a GET request.

  Method post_url_data

    `string post_url_data(string|Standards.URI url, mapping(string:int|string|array(string))|string query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con)`

  Description

    Similar to get_url_data , except that query variables is sent as a POST request instead of a GET request.

  Method http_encode_query

    `string http_encode_query(mapping(string:int|string|array(string)) variables)`

  Description

    Encodes a query mapping to a string; this protects odd - in http perspective - characters like '&' and '#' and control characters, and packs the result together in a HTTP query string.

    Example:

        	> Protocols.HTTP.http_encode_query( (["anna":"eva","lilith":"blue"]) );
             Result: "lilith=blue&anna=eva"
             > Protocols.HTTP.http_encode_query( (["&amp;":"&","'=\"":"\0\0\0"]) );
             Result: "%26amp%3b=%26&%27%3d%22=%00%00%00"

  Method percent_encode

    `string percent_encode(string s)`

  Description

    Encodes the given string using `%XX` encoding, except that URI unreserved chars are not encoded. The unreserved chars are `A-Z`, `a-z`, `0-9`, `-`, `.`, `_`, and `~` (see RFC 2396 section 2.3).

    8-bit chars are encoded straight, and wider chars are not allowed. That means this encoding is applicable if s is a binary octet string. If it is a character string then uri_encode should be used instead.

    It is also slightly faster than uri_encode if s is known to contain only US-ASCII.

  Method percent_decode

    `string percent_decode(string s)`

  Description

    Decodes URI-style `%XX` encoded chars in the given string.

  See also

    percent_encode , uri_decode

  Bugs

    This function currently does not accept wide string input, which is necessary to work as the reverse of iri_encode .

  Method uri_encode

    `string uri_encode(string s)`

  Description

    Encodes the given string using `%XX` encoding to be used as a component part in a URI. This means that all URI reserved and excluded characters are encoded, i.e. everything except `A-Z`, `a-z`, `0-9`, `-`, `.`, `_`, and `~` (see RFC 2396 section 2.3).

    8-bit chars and wider are encoded using UTF-8 followed by percent-encoding. This follows RFC 3986 section 2.5, the IRI-to-URI conversion method in the IRI standard (RFC 3987) and appendix B.2 in the HTML 4.01 standard. It should work regardless of the charset used in the XML document the URI might be inserted into.

  See also

    uri_decode , uri_encode_invalids , iri_encode

  Method uri_encode_invalids

    `string uri_encode_invalids(string s)`

  Description

    Encodes all "dangerous" chars in the given string using `%XX` encoding, so that it can be included as a URI in an HTTP message or header field. This includes control chars, space and various delimiter chars except those in the URI `reserved` set (RFC 2396 section 2.2).

    Since this function doesn't touch the URI `reserved` chars nor the escape char `%`, it can be used on a complete formatted URI or IRI.

    8-bit chars and wider are encoded using UTF-8 followed by percent-encoding. This follows RFC 3986 section 2.5, the IRI standard (RFC 3987) and appendix B.2 in the HTML 4.01 standard.

  Note

    The characters in the URI `reserved` set are: `:`, `/`, `?`, `#`, `[`, `]`, `@`, `!`, `$`, `&`, `'`, `(`, `)`, `*`, `+`, `,`, `;`, `=`. In addition, this function doesn't touch the escape char `%`.

  See also

    uri_decode , uri_encode

  Method uri_decode

    `string uri_decode(string s)`

  Description

    Decodes URI-style `%XX` encoded chars in the given string, and then UTF-8 decodes the result. This is the reverse of uri_encode and uri_encode_invalids .

  See also

    uri_encode , uri_encode_invalids

  Method iri_encode

    `string iri_encode(string s)`

  Description

    Encodes the given string using `%XX` encoding to be used as a component part in an IRI (Internationalized Resource Identifier, see RFC 3987). This means that all chars outside the IRI `iunreserved` set are encoded, i.e. this function encodes equivalently to uri_encode except that all 8-bit and wider characters are left as-is.

  Bugs

    This function currently does not encode chars in the Unicode private ranges, although that is strictly speaking required in some but not all IRI components. That could change if it turns out to be a problem.

  See also

    percent_decode , uri_encode

  Method uri_normalize

    `string uri_normalize(string s)`

  Description

    Normalizes the URI-style `%XX` encoded string s by decoding all URI `unreserved` chars, i.e. US-ASCII digits, letters, `-`, `.`, `_`, and `~`.

    Since only unreserved chars are decoded, the result is always semantically equivalent to the input. It's therefore safe to use this on a complete formatted URI.

  See also

    uri_decode , uri_encode , iri_normalize

  Method iri_normalize

    `string iri_normalize(string s)`

  Description

    Normalizes the IRI-style UTF-8 and `%XX` encoded string s by decoding all IRI `unreserved` chars, i.e. everything except the URI `reserved` chars and control chars.

    Since only unreserved chars are decoded, the result is always semantically equivalent to the input. It's therefore safe to use this on a complete formatted IRI.

  See also

    iri_decode , uri_normalize

  Method quoted_string_encode

    `string quoted_string_encode(string s)`

  Description

    Encodes the given string quoted to be used as content inside a `quoted-string` according to RFC 2616 section 2.2. The returned string does not include the surrounding `"` chars.

  Note

    The `quoted-string` quoting rules in RFC 2616 have several problems:

    - Quoting is inconsistent since `"` is quoted as `\"`, but `\` does not need to be quoted. This is resolved in the HTTP bis update to mandate quoting of `\` too, which this function performs.

    - Many characters are not quoted sufficiently to make the result safe to use in an HTTP header, so this quoting is not enough if s contains NUL, CR, LF, or any 8-bit or wider character.

  See also

    quoted_string_decode

  Method quoted_string_decode

    `string quoted_string_decode(string s)`

  Description

    Decodes the given string which has been encoded as a `quoted-string` according to RFC 2616 section 2.2. s is assumed to not include the surrounding `"` chars.

  See also

    quoted_string_encode

  Method http_encode_string

    `__deprecated__ string http_encode_string(string in)`

  Description

    This is a deprecated alias for uri_encode , for compatibility with Pike 7.6 and earlier.

    In 7.6 this function didn't handle 8-bit and wider chars correctly. It encoded 8-bit chars directly to `%XX` escapes, and it used nonstandard `%uXXXX` escapes for 16-bit chars.

    That is considered a bug, and hence the function is changed. If you need the old buggy encoding then use the 7.6 compatibility version (`#pike 7.6`).

  Deprecated

  Method http_encode_cookie

    `__deprecated__ string http_encode_cookie(string f)`

  Description

    This function used to claim that it encodes the specified string according to the HTTP cookie standard. If fact it does not - it applies URI-style (i.e. `%XX`) encoding on some of the characters that cannot occur literally in cookie values. There exist some web servers (read Roxen and forks) that usually perform a corresponding nonstandard decoding of %-style escapes in cookie values in received requests.

    This function is deprecated. The function quoted_string_encode performs encoding according to the standard, but it is not safe to use with arbitrary chars. Thus URI-style encoding using uri_encode or percent_encode is normally a good choice, if you can use uri_decode /percent_decode at the decoding end.

  Deprecated

  Method unentity

    `__deprecated__ string unentity(string s)`

  Description

    Helper function for replacing HTML entities with the corresponding unicode characters.

  Deprecated

  CLASS Protocols.HTTP.Query

    Description

      Open and execute an HTTP query.

    Example

          HTTP.Query o=HTTP.Query();
           void ok()
           {
              write("ok...\n");
              write("%O\n", o->headers);
              exit(0);
           }
           void fail()
           {
              write("fail\n");
              exit(0);
           }
           int main()
           {
              o->set_callbacks(ok, fail);
              o->async_request("pike.ida.liu.se", 80, "HEAD / HTTP/1.0");
              return -1;
           }

    Variable errno

      `int Protocols.HTTP.Query.errno`

    Description

      Errno copied from the connection.

    Variable ok

      `int Protocols.HTTP.Query.ok`

    Description

      Tells if the connection is successfull.

    Variable headers

      `mapping Protocols.HTTP.Query.headers`

    Description

      Headers as a mapping. All header names are in lower case, for convinience.

    Variable protocol

      `string Protocols.HTTP.Query.protocol`

    Description

      Protocol string, ie `"HTTP/1.0"`.

      `int Protocols.HTTP.Query.status`
      `string Protocols.HTTP.Query.status_desc`

    Description

      Status number and description (eg `200` and `"ok"`).

      `string Protocols.HTTP.Query.host`
      `int Protocols.HTTP.Query.port`

    Description

      Connected host and port.

      Used to detect whether keep-alive can be used.

    Variable hostname_cache

      `mapping Protocols.HTTP.Query.hostname_cache`

    Description

      Set this to a global mapping if you want to use a cache, prior of calling *request().

    Method set_callbacks
    Method async_request

      `Protocols.HTTP.Query set_callbacks(function request_ok, function request_fail, mixed ... extra)`
      `Protocols.HTTP.Query async_request(string server, int port, string query)`
      `Protocols.HTTP.Query async_request(string server, int port, string query, mapping headers, string|void data)`

    Description

      Setup and run an asynchronous request, otherwise similar to thread_request() .

      request_ok (Protocols.HTTP.Query httpquery,...extra args) will be called when connection is complete, and headers are parsed.

      request_fail (Protocols.HTTP.Query httpquery,...extra args) is called if the connection fails.

    Returns

      Returns the called object

    Method thread_request

      `Protocols.HTTP.Query thread_request(string server, int port, string query)`
      `Protocols.HTTP.Query thread_request(string server, int port, string query, mapping headers, void|string data)`

    Description

      Create a new query object and begin the query.

      The query is executed in a background thread; call `() in the object to wait for the request to complete.

      query is the first line sent to the HTTP server; for instance `"GET /index.html HTTP/1.1"`.

      headers will be encoded and sent after the first line, and data will be sent after the headers.

    Returns

      Returns the called object.

    Method `()

      `int `()()`

    Description

      Wait for connection to complete.

    Returns

      Returns `1` on successfull connection, `0` on failure.

    Method data

      `string data(int|void max_length)`

    Description

      Gives back the data as a string.

    Method unicode_data

      `string unicode_data()`

    Description

      Gives back data, but decoded according to the content-type character set.

    See also

      data

    Method downloaded_bytes

      `int downloaded_bytes()`

    Description

      Gives back the number of downloaded bytes.

    Method total_bytes

      `int total_bytes()`

    Description

      Gives back the size of a file if a content-length header is present and parsed at the time of evaluation. Otherwise returns -1.

    Method cast

      `array cast("array")`

    Returns

      Array
      `mapping 0` | Headers
      `string 1` | Data
      `string 2` | Protocol
      `int 3` | Status
      `string 4` | Status description

    Method cast

      `mapping cast("mapping")`

    Returns

      The header mapping ORed with the following mapping.

      `"protocol" : string` | The protocol.
      `"status" : int` | The status code.
      `"status_desc" : string` | The status description.
      `"data" : string` | The returned data.

    Method cast

      `string cast("string")`

    Description

      Gives back the answer as a string.

    Method file

      `Protocols.HTTP.Query.PseudoFile file()`
      `Protocols.HTTP.Query.PseudoFile file(mapping newheaders, void|mapping removeheaders)`

    Description

      Gives back a pseudo-file object, with the methods `read()` and `close()`. This could be used to copy the file to disc at a proper tempo.

      newheaders , removeheaders is applied as: `(oldheaders|newheaders))-removeheaders` Make sure all new and remove-header indices are lower case.

    See also

      datafile()

    Method datafile

      `Protocols.HTTP.Query.PseudoFile datafile()`

    Description

      Gives back a pseudo-file object, with the methods `read()` and `close()`. This could be used to copy the file to disc at a proper tempo.

      datafile() doesn't give the complete request, just the data.

    See also

      file()

    Method close

      `void close()`

    Description

      Close all associated file descriptors.

    Method async_fetch

      `void async_fetch(function callback, mixed ... extra)`

    Description

      Fetch all data in background.

    See also

      timed_async_fetch() , async_request() , set_callbacks()

    Method timed_async_fetch

      `void timed_async_fetch(function(object:void) ok_callback, function(object:void) fail_callback, mixed ... extra)`

    Description

      Like async_fetch() , except with a timeout and a corresponding fail callback function.

    See also

      async_fetch() , async_request() , set_callbacks()

  CLASS Protocols.HTTP.Session

    Variable follow_redirects

      `int Protocols.HTTP.Session.follow_redirects`

    Description

      The number of redirects to follow, if any. This is the default to the created Request objects.

      A redirect automatically turns into a GET request, and all header, query, post or put information is dropped.

      Default is 20 redirects. A negative number will mean infinity.

    Bugs

      Loops will currently not be detected, only the limit works to stop loops.

    See also

      Request.follow_redirects

    Variable default_headers

      `mapping Protocols.HTTP.Session.default_headers`

    Description

      Default HTTP headers.

    Method set_http_cookie

      `void set_http_cookie(string cookie, Standards.URI at)`

    Description

      Parse and set a cookie received in the HTTP protocol. The cookie will be checked against current security levels et al.

    Method set_cookie

      `void set_cookie(Cookie cookie, Standards.URI who)`

    Description

      Set a cookie. The cookie will be checked against current security levels et al, using the parameter who . If who is zero, no security checks will be performed.

    Method encode_cookies
    Method decode_cookies

      `string encode_cookies()`
      `void decode_cookies(string data, void no_clear)`

    Description

      Dump all cookies to a string and read them back. This is useful to store cookies in between sessions (on disk, for instance). decode_cookies will throw an error upon parse failures. Also note, decode_cookies will clear out any previously learned cookies from the Session object, unless no_clear is given and true.

    Method get_cookies

      `array(string) get_cookies(Standards.URI|SessionURL for_url, void|int(0..1) no_delete)`

    Description

      Get the cookies that we should send to this server, for this url. They are presented in the form suitable for HTTP headers (as an array). This will also take in count expiration of cookies, and delete expired cookies from the Session unless no_delete is true.

    Variable hostname_cache

      `mapping Protocols.HTTP.Session.hostname_cache`

    Description

      Cache of hostname to IP lookups. Given to and used by the Query objects.

    Variable time_to_keep_unused_connections

      `int|float Protocols.HTTP.Session.time_to_keep_unused_connections`

    Description

      The time to keep unused connections in seconds. Set to zero to never save any kept-alive connections. (Might be good in a for instance totaly synchroneous script that keeps the backend thread busy and never will get call_outs.) Defaults to 10 seconds.

    Variable maximum_connections_per_server

      `int Protocols.HTTP.Session.maximum_connections_per_server`

    Description

      Maximum number of connections to the same server. Used only by async requests. Defaults to 10 connections.

    Variable maximum_total_connections

      `int Protocols.HTTP.Session.maximum_total_connections`

    Description

      Maximum total number of connections. Limits only async requests, and the number of kept-alive connections (live connections + kept-alive connections <= this number) Defaults to 50 connections.

    Variable maximum_connection_reuse

      `int Protocols.HTTP.Session.maximum_connection_reuse`

    Description

      Maximum times a connection is reused. Defaults to 1000000. <2 means no reuse at all.

    Method give_me_connection

      `Query give_me_connection(Standards.URI url)`

    Description

      Request a Query object suitable to use for the given URL. This may be a reused object from a keep-alive connection.

    Method return_connection

      `void return_connection(Standards.URI url, Query query)`

    Description

      Return a previously used Query object to the keep-alive storage. This function will determine if the given object is suitable to keep or not by checking status and headers.

    Method get_url
    Method post_url
    Method put_url
    Method delete_url

      `Request get_url(URL url, void|mapping query_variables)`
      `Request post_url(URL url, mapping|string query_variables)`
      `Request put_url(URL url, string file, void|mapping query_variables)`
      `Request delete_url(URL url, void|mapping query_variables)`

    Description

      Sends a HTTP GET, POST, PUT or DELETE request to the server in the URL and returns the created and initialized Request object. 0 is returned upon failure.

    Method get_url_nice
    Method get_url_data
    Method post_url_nice
    Method post_url_data

      `array(string) get_url_nice(URL url, mapping query_variables)`
      `string get_url_data(URL url, mapping query_variables)`
      `array(string) post_url_nice(URL url, mapping|string query_variables)`
      `string post_url_data(URL url, mapping|string query_variables)`

    Description

      Returns an array of `({content_type,data})` and just the data string respective, after calling the requested server for the information. `0` is returned upon failure.

      post* is similar to the get_url() class of functions, except that the query variables is sent as a POST request instead of as a GET.

    Method async_get_url
    Method async_put_url
    Method async_delete_url
    Method async_post_url

      `Request async_get_url(URL url, void|mapping query_variables, function callback_headers_ok, function callback_data_ok, function callback_fail, mixed ... callback_arguments)`
      `Request async_put_url(URL url, void|string file, void|mapping query_variables, function callback_headers_ok, function callback_data_ok, function callback_fail, mixed ... callback_arguments)`
      `Request async_delete_url(URL url, void|mapping query_variables, function callback_headers_ok, function callback_data_ok, function callback_fail, mixed ... callback_arguments)`
      `Request async_post_url(URL url, mapping query_variables, function callback_headers_ok, function callback_data_ok, function callback_fail, mixed ... callback_arguments)`

    Description

      Sends a HTTP GET, POST, PUT or DELETE request to the server in the URL asynchroneously, and call the corresponding callbacks when result arrives (or not). The callbacks will receive the created Request object as first argument, then the given callback_arguments , if any.

      callback_headers_ok is called when the HTTP request has received headers.

      callback_data_ok is called when the HTTP request has been received completely, data and all.

      callback_fail is called when the HTTP request has failed, on a TCP/IP or DNS level, or has received a forced timeout.

      The created Request object is returned.

    CLASS Protocols.HTTP.Session.Request

      Description

        Request

      Variable con

        `Query Protocols.HTTP.Session.Request.con`

      Description

        Raw connection object

      Variable url_requested

        `Standards.URI Protocols.HTTP.Session.Request.url_requested`

      Description

        URL requested (set by prepare_method). This will update according to followed redirects.

      Variable follow_redirects

        `int Protocols.HTTP.Session.Request.follow_redirects`

      Description

        Number of redirects to follow; the request will perform another request if the HTTP answer is a 3xx redirect. Default from the parent Session.follow_redirects .

        A redirect automatically turns into a GET request, and all header, query, post or put information is dropped.

      Bugs

        Loops will currently not be detected, only the limit works to stop loops.

      Variable cookie_encountered

        `function(string:mixed) Protocols.HTTP.Session.Request.cookie_encountered`

      Description

        Cookie callback. When a request is performed, the result is checked for cookie changes and additions. If a cookie is encountered, this function is called. Default is to call set_http_cookie in the Session object.

      Method prepare_method

        `array(string|int|mapping) prepare_method(string method, URL url, void|mapping query_variables, void|mapping extra_headers, void|string data)`

      Description

        Prepares the HTTP Query object for the connection, and returns the parameters to use with do_sync , do_async or do_thread .

        This method will also use cookie information from the parent Session , and may reuse connections (keep-alive).

      Method do_sync

        `Request do_sync(array(string|int|mapping) args)`

      Description

        Perform a request synchronously. Get arguments from prepare_method .

      Returns

        0 upon failure, this object upon success

      See also

        prepare_method , do_async , do_thread

      Method do_thread

        `Request do_thread(array(string|int|mapping) args)`

      Description

        Start a request in the background, using a thread. Call wait to wait for the thread to finish. Get arguments from prepare_method .

      Returns

        The called object.

      See also

        prepare_method , do_sync , do_async , wait

      Note

        do_thread does not rerun redirections automatically

      Method wait

        `Request wait()`

      Description

        Wait for the request thread to finish.

      Returns

        0 upon failure, or the called object upon success.

      See also

        do_thread

      Method set_callbacks

        `void set_callbacks(function(mixed ... :mixed) headers, function(mixed ... :mixed) data, function(mixed ... :mixed) fail, mixed ... callback_arguments)`

      Description

        Setup callbacks for async mode, headers will be called when the request got connected, and got data headers; data will be called when the request got the amount of data it's supposed to get and fail is called whenever the request failed.

        Note here that an error message from the server isn't considered a failure, only a failed TCP connection.

      Method do_async

        `Request do_async(array(string|int|mapping) args)`

      Description

        Start a request asyncroneously. It will perform in the background using callbacks (make sure the backend thread is free). Call set_callbacks to setup the callbacks. Get arguments from prepare_method .

      Returns

        The called object.

      See also

        set_callbacks , prepare_method , do_sync , do_thread

      Method destroy

        `void destroy()`

      Description

        destroy is called when an object is destructed. But since this clears the HTTP connection from the Request object, it can also be used to reuse a Request object.

    CLASS Protocols.HTTP.Session.SessionURL

      Description

        Class to store URL+referer

      Inherit URI

        inherit Standards.URI : URI

      Variable referer

        `URL Protocols.HTTP.Session.SessionURL.referer`

      Description

        the referer to this URL

      Method create

        `void Protocols.HTTP.Session.SessionURL(URL uri, URL base_uri, URL _referer)`

      Description

        instantiate a SessionURL object; when fed to Protocols.HTTP.Session calls, will add referer to the HTTP handshaking variables

  Module Protocols.HTTP.Server

    Constant HeaderParser

      `constant Protocols.HTTP.Server.HeaderParser`

    Description

      Fast HTTP header parser.

    Constant http_decode_string

      `constant Protocols.HTTP.Server.http_decode_string`

    Method http_decode_urlencoded_query

      `mapping(string:string|array(string)) http_decode_urlencoded_query(string query, void|mapping dest)`

    Description

      Decodes an URL-encoded query into a mapping.

    Method extension_to_type

      `string extension_to_type(string extension)`

    Description

      Looks up the file extension in a table to return a suitable MIME type.

    Method filename_to_type

      `string filename_to_type(string filename)`

    Description

      Looks up the file extension in a table to return a suitable MIME type.

    Method http_date

      `string http_date(int time)`

    Description

      Makes a time notification suitable for the HTTP protocol.

    Parameter `time`

      The time in seconds since the 00:00:00 UTC, January 1, 1970

    Returns

      The date in the HTTP standard date format. Example : Thu, 03 Aug 2000 05:40:39 GMT

    Method http_decode_date

      `int http_decode_date(string data)`

    Description

      Decode a HTTP date to seconds since 1970 (UTC)

    Returns

      zero (UNDEFINED) if the given string isn't a HTTP date

    CLASS Protocols.HTTP.Server.SSLPort

      Description

        The simplest SSL server possible. Binds a port and calls a callback with Request objects.

      Method create

        `void Protocols.HTTP.Server.SSLPort(function(Request:void) _callback, void|int _portno, void|string _interface, void|string key, void|string|array certificate)`

      Description

        Create a HTTPS (HTTP over SSL) server.

      Parameter `_callback`

        The function run when a request is received. takes one argument of type Request .

      Parameter `_portno`

        The port number to bind to, defaults to 443.

      Parameter `_interface`

        The interface address to bind to.

      Parameter `key`

        An optional SSL secret key, provided in binary format, such as that created by Standards.PKCS.RSA.private_key() .

      Parameter `certificate`

        An optional SSL certificate or chain of certificates with the host certificate first, provided in binary format.

      Method close

        `void close()`

      Description

        Closes the HTTP port.

      Method new_connection

        `void new_connection()`

      Description

        The port accept callback

      CLASS Protocols.HTTP.Server.SSLPort.MySSLPort

        Inherit sslport

          inherit SSL.sslport : sslport

        Method set_default_keycert

          `void set_default_keycert()`

        Method set_key

          `void set_key(string skey)`

        Method set_certificate

          `void set_certificate(string|array(string) certificate)`

    CLASS Protocols.HTTP.Server.Port

      Description

        The simplest server possible. Binds a port and calls a callback with Server.Request objects.

      Method create

        `void Protocols.HTTP.Server.Port(function(.Request:void) callback)`
        `void Protocols.HTTP.Server.Port(function(.Request:void) callback, int portno, void|string interface)`

      Method close

        `void close()`

      Description

        Closes the HTTP port.

    CLASS Protocols.HTTP.Server.Request

      Variable raw

        `string Protocols.HTTP.Server.Request.raw`

      Description

        raw unparsed full request (headers and body)

      Variable body_raw

        `string Protocols.HTTP.Server.Request.body_raw`

      Description

        raw unparsed body of the request (raw minus request line and headers)

      Variable request_raw

        `string Protocols.HTTP.Server.Request.request_raw`

      Description

        full request line (request_type + full_query + protocol )

      Variable request_type

        `string Protocols.HTTP.Server.Request.request_type`

      Description

        HTTP request method, eg. POST, GET, etc.

      Variable full_query

        `string Protocols.HTTP.Server.Request.full_query`

      Description

        full resource requested, including attached GET query

      Variable not_query

        `string Protocols.HTTP.Server.Request.not_query`

      Description

        resource requested minus any attached query

      Variable query

        `string Protocols.HTTP.Server.Request.query`

      Description

        query portion of requested resource, starting after the first "?"

      Variable protocol

        `string Protocols.HTTP.Server.Request.protocol`

      Description

        request protocol and version, eg. HTTP/1.0

      Variable request_headers

        `mapping(string:string|array(string)) Protocols.HTTP.Server.Request.request_headers`

      Description

        all headers included as part of the HTTP request, ie content-type.

      Variable variables

        `mapping(string:string|array(string)) Protocols.HTTP.Server.Request.variables`

      Description

        all variables included as part of a GET or POST request.

      Variable cookies

        `mapping(string:string) Protocols.HTTP.Server.Request.cookies`

      Description

        cookies set by client

      Variable misc

        `mapping Protocols.HTTP.Server.Request.misc`

      Description

        external use only

      Variable send_timeout_delay

        `int Protocols.HTTP.Server.Request.send_timeout_delay`

      Description

        send timeout (no activity for this period with data in send buffer) in seconds, default is 180

      Variable connection_timeout_delay

        `int Protocols.HTTP.Server.Request.connection_timeout_delay`

      Description

        connection timeout, delay until connection is closed while waiting for the correct headers:

      Method response_and_finish

        `void response_and_finish(mapping m, function|void _log_cb)`

      Description

        return a properly formatted response to the HTTP client

      Parameter `m`

        Contains elements for generating a response to the client.

        `"data" : string` | Data to be returned to the client.
        `"file" : object` | File object, the contents of which will be returned to the client.
        `"error" : int` | HTTP error code
        `"length" : int` | length of content returned. If file is provided, size bytes will be returned to client.
        `"modified" : string` | contains optional modification date.
        `"type" : string` | contains optional content-type
        `"extra_heads" : mapping` | contains a mapping of additional headers to be returned to client.
        `"server" : string` | contains the server identification header.

      Method sent_data

        `int sent_data()`

      Description

        Returns the amount of data sent.

Module Protocols.SMTP

  Variable replycodes

    `mapping(int:string) Protocols.SMTP.replycodes`

  Description

    A mapping(int:string) that maps SMTP return codes to english textual messages.

  CLASS Protocols.SMTP.Client

    Inherit Protocol

      inherit Protocol : Protocol

    Method create

      `void Protocols.SMTP.Client()`
      `void Protocols.SMTP.Client(Stdio.File server)`
      `void Protocols.SMTP.Client(string server, void|int port)`

    Description

      Creates an SMTP mail client and connects it to the the server provided. The server parameter may either be a string witht the hostnam of the mail server, or it may be a file object acting as a mail server. If server is a string, than an optional port parameter may be provided. If no port parameter is provided, port 25 is assumed. If no parameters at all is provided the client will look up the mail host by searching for the DNS MX record.

    Throws

      Throws an exception if the client fails to connect to the mail server.

    Method send_message

      `void send_message(string from, array(string) to, string body)`

    Description

      Sends a mail message from from to the mail addresses listed in to with the mail body body . The body should be a correctly formatted mail DATA block, e.g. produced by MIME.Message .

    See also

      simple_mail

    Throws

      If the mail server returns any other return code than 200-399 an exception will be thrown.

    Method simple_mail

      `void simple_mail(string to, string subject, string from, string msg)`

    Description

      Sends an e-mail. Wrapper function that uses send_message .

    Note

      Some important headers are set to: `"Content-Type: text/plain; charset=iso-8859-1"` and `"Content-Transfer-Encoding: 8bit"`. `"Date:"` header isn't used at all.

    Throws

      If the mail server returns any other return code than 200-399 an exception will be thrown.

    Method verify

      `array(int|string) verify(string addr)`

    Description

      Verifies the mail address addr against the mail server.

    Returns

      Array
      `int code` | The numerical return code from the VRFY call.
      `string message` | The textual answer to the VRFY call.

    Note

      Some mail servers does not answer truthfully to verfification queries in order to prevent spammers and others to gain information about the mail addresses present on the mail server.

    Throws

      If the mail server returns any other return code than 200-399 an exception will be thrown.

  CLASS Protocols.SMTP.Configuration

    Description

      Class to store configuration variable for the SMTP server

    Variable maxsize

      `int Protocols.SMTP.Configuration.maxsize`

    Description

      Message max size

    Variable maxrcpt

      `int Protocols.SMTP.Configuration.maxrcpt`

    Description

      Maximum number of recipients (default 1000)

    Variable checkdns

      `int Protocols.SMTP.Configuration.checkdns`

    Description

      Verify sender domain for MX

    Variable checkemail

      `int Protocols.SMTP.Configuration.checkemail`

    Description

      Lamme check email from validity

    Variable givedata

      `int Protocols.SMTP.Configuration.givedata`

    Description

      Give raw data and normal MIME data, if set to yes your cb_data function should take an extra string argument

  CLASS Protocols.SMTP.Connection

    Description

      The low-level class for the SMTP server

    Variable logfunction

      `function(string:mixed) Protocols.SMTP.Connection.logfunction`

    Description

      This function is called whenever the SMTP server logs something. By default the log function is werror .

  CLASS Protocols.SMTP.Server

    Description

      The use of Protocols.SMTP.server is quite easy and allow you to design custom functions to process mail. This module does not handle mail storage nor relaying to other domains. So it is your job to provide mail storage and relay mails to other servers

    Method create

      `void Protocols.SMTP.Server(array(string) _domains, void|int port, void|string ip, function _cb_mailfrom, function _cb_rcptto, function _cb_data)`

    Description

      Create a receiving SMTP server. It implements RFC 2821, 2822 and 1854.

    Parameter `domain`

      Domains name this server relay, you need to provide at least one domain (the first one will be used for MAILER-DAEMON address). if you want to relay everything you can put a '*' after this first domain.

    Parameter `port`

      Port this server listen on

    Parameter `listenip`

      IP on which server listen

    Parameter `cb_mailfrom`

      Mailfrom callback function, this function will be called when a client send a mail from command. This function must take a string as argument (corresponding to the sender's email) and return int corresponding to the SMTP code to output to the client. If you return an array the first element is the SMTP code and the second is the error string to display.

    Parameter `cb_rcptto`

      Same as cb_mailfrom but called when a client sends a rcpt to.

    Parameter `cb_data`

      This function is called each time a client send a data content. It must have the following synopsis: int cb_data(object mime, string sender, array(string) recipients, void|string rawdata) object mime : the mime data object string sender : sender of the mail (from the mailfrom command) array(string) recipients : one or more recipients given by the rcpt to command return : SMTP code to output to the client. If you return an array the first element is the SMTP code and the second is the error string to display.

    Example

          Here is an example of silly program that does nothing except outputing
            informations to stdout.
           int cb_mailfrom(string mail)
           {
             return 250;
           }
           int cb_rcptto(string email)
           {
             // check the user's mailbox here
             return 250;
           }
           int cb_data(object mime, string sender, array(string) recipients)
           {
             write(sprintf("smtpd: mailfrom=%s, to=%s, headers=%O\ndata=%s\n",
             sender, recipients * ", ", mime->headers, mime->getdata()));
             // check the data and deliver the mail here
             if(mime->body_parts)
             {
               foreach(mime->body_parts, object mpart)
                 write("smtpd: mpart data = %O\n", mpart->getdata());
             }
             return 250;
           }
           int main(int argc, array(string) argv)
           {
             Protocols.SMTP.Server(({ "ece.fr" }), 2500, "127.0.0.1",       cb_mailfrom, cb_rcptto, cb_data);
             return -1;
           }

Module Protocols.Ident

  Description

    An implementation of the IDENT protocol, specified in RFC 931.

  Method lookup

    `array(string) lookup(object fd)`

  Throws

    Throws exception upon any error.

  CLASS Protocols.Ident.AsyncLookup

    Method create

      `void Protocols.Ident.AsyncLookup(object fd, function(array(string):void) cb, mixed ... args)`

Module Protocols.IPv6

  Method parse_addr

    `array(int(0..65535)) parse_addr(string addr)`

  Description

    Parses an IPv6 address on the formatted hexadecimal `"x:x:x:x:x:x:x:x"` form, or any of the shorthand varieties (see RFC 2373, section 2.2).

    The address is returned as an 8-element array where each element is the value of the corresponding field. Zero is returned if addr is incorrectly formatted.

  See also

    format_addr_short

  Method format_addr_short

    `string format_addr_short(array(int(0..65535)) bin_addr)`

  Description

    Formats an IPv6 address to the colon-separated hexadecimal form as defined in RFC 2373, section 2.2. bin_addr must be an 8-element array containing the 16-bit fields.

    The returned address is on a canonical shortest form as follows: The longest sequence of zeroes is shortened using `"::"`. If there are several of equal length then the leftmost is shortened. All hexadecimal letters are lower-case. There are no superfluous leading zeroes in the fields.

  See also

    parse_addr

  Method normalize_addr_basic

    `string normalize_addr_basic(string addr)`

  Description

    Normalizes a formatted IPv6 address to a string with eight hexadecimal numbers separated by `":"`. addr is given on the same form, or any of the shorthand varieties as specified in RFC 2373, section 2.2.

    All hexadecimal letters in the returned address are lower-case, and there are no superfluous leading zeroes in the fields.

    Zero is returned if addr is incorrectly formatted.

  See also

    normalize_addr_short

  Method normalize_addr_short

    `string normalize_addr_short(string addr)`

  Description

    Normalizes a formatted IPv6 address to a canonical shortest form. addr is parsed according to the hexadecimal `"x:x:x:x:x:x:x:x"` syntax or any of its shorthand varieties (see RFC 2373, section 2.2).

    The returned address is normalized as follows: The longest sequence of zeroes is shortened using `"::"`. If there are several of equal length then the leftmost is shortened. All hexadecimal letters are lower-case. There are no superfluous leading zeroes in the fields.

    Zero is returned if addr is incorrectly formatted.

  See also

    normalize_addr_basic

Module Protocols.DNS_SD

  CLASS Protocols.DNS_SD.Service

    Description

      This class provides an interface to DNS Service Discovery. The functionality of DNS-SD is described at <http://www.dns-sd.org/>.

      Using the Proctocols.DNS_SD.Service class a Pike program can announce services, for example a web site or a database server, to computers on the local network.

      When registering a service you need to provide the service name. service type, domain and port number. You can also optionally specify a TXT record. The contents of the TXT record varies between different services; for example, a web server can announce a path to a web page, and a printer spooler is able to list printer features such as color support or two-sided printing.

      The service is registered on the network for as long as the instance of the Service class is valid.

    Inherit Service

      inherit _Protocols_DNS_SD.Service : Service

    Method update_txt

      `void update_txt(string|array(string) txt)`

    Description

      Updates the TXT record for the service.

    Parameter `txt`

      A TXT record with service-specific information. It can be given as a plain string or an array of property assignment strings. To remove an existing TXT record you give an empty string as the argument.

    Method create

      `void Protocols.DNS_SD.Service(string name, string service, string domain, int port, void|string|array(string) txt)`

    Description

      Registers a service on the local network.

    Parameter `name`

      User-presentable name of the service.

    Parameter `service`

      Type of service on the form `_type._protocol`. Type is an identifier related to the service type. A list of registered service types can be found at http://http://www.dns-sd.org/ServiceTypes.html/. Protocol is normally `tcp` but `udp` is also a valid choice. For example, a web server would get a service of `_http._tcp`.

    Parameter `domain`

      Domain name. Normally an empty string which the DNS-SD library will translate into `local.`.

    Parameter `port`

      Port number for the service (e.g. 80 for a web site).

    Parameter `txt`

      An optional TXT record with service-specific information. It can be given as a plain string or an array of property assignment strings. The TXT record can be changed later by calling update_txt in the object returned when you register the service.

    Example

          object svc = Protocols.DNS_SD.Service(
                           "Company Intranet Forum",  //  name
                           "_http._tcp",              //  service type
                           "",                        //  domain (default)
                           80,                        //  port
                           ({ "path=/forum/" })       //  TXT record
                         );

Module Protocols.DNS

  Description

    Support for the Domain Name System protocol.

    RFC 1034, RFC 1035 and RFC 2308

  Method async_ip_to_host

    `void async_ip_to_host(string ip, function cb, mixed ... cba)`

  Method async_host_to_ip

    `void async_host_to_ip(string host, function cb, mixed ... cba)`

  Method async_get_mx_all

    `void async_get_mx_all(string host, function cb, mixed ... cba)`

  Method async_get_mx

    `void async_get_mx(string host, function cb, mixed ... cba)`

  Method gethostbyname

    `array gethostbyname(string host)`

  Method gethostbyaddr

    `array gethostbyaddr(string host)`

  Method get_mx

    `string get_mx(string host)`

  Method get_primary_mx

    `string get_primary_mx(string host)`

  ENUM Protocols.DNS.ResourceClass

    Description

      Resource classes

    Constant C_IN

      `constant Protocols.DNS.C_IN`

    Description

      Class Internet

    Constant C_CS

      `constant Protocols.DNS.C_CS`

    Description

      Class CSNET (Obsolete)

    Constant C_CH

      `constant Protocols.DNS.C_CH`

    Description

      Class CHAOS

    Constant C_HS

      `constant Protocols.DNS.C_HS`

    Description

      Class Hesiod

    Constant C_ANY

      `constant Protocols.DNS.C_ANY`

    Description

      Class ANY

  ENUM Protocols.DNS.EntryType

    Description

      Entry types

    Constant T_A

      `constant Protocols.DNS.T_A`

    Description

      Type - host address

    Constant T_NS

      `constant Protocols.DNS.T_NS`

    Description

      Type - authoritative name server

    Constant T_MD

      `constant Protocols.DNS.T_MD`

    Description

      Type - mail destination (Obsolete - use MX)

    Constant T_MF

      `constant Protocols.DNS.T_MF`

    Description

      Type - mail forwarder (Obsolete - use MX)

    Constant T_CNAME

      `constant Protocols.DNS.T_CNAME`

    Description

      Type - canonical name for an alias

    Constant T_SOA

      `constant Protocols.DNS.T_SOA`

    Description

      Type - start of a zone of authority

    Constant T_MB

      `constant Protocols.DNS.T_MB`

    Description

      Type - mailbox domain name (EXPERIMENTAL)

    Constant T_MG

      `constant Protocols.DNS.T_MG`

    Description

      Type - mail group member (EXPERIMENTAL)

    Constant T_MR

      `constant Protocols.DNS.T_MR`

    Description

      Type - mail rename domain name (EXPERIMENTAL)

    Constant T_NULL

      `constant Protocols.DNS.T_NULL`

    Description

      Type - null RR (EXPERIMENTAL)

    Constant T_WKS

      `constant Protocols.DNS.T_WKS`

    Description

      Type - well known service description

    Constant T_PTR

      `constant Protocols.DNS.T_PTR`

    Description

      Type - domain name pointer

    Constant T_HINFO

      `constant Protocols.DNS.T_HINFO`

    Description

      Type - host information

    Constant T_MINFO

      `constant Protocols.DNS.T_MINFO`

    Description

      Type - mailbox or mail list information

    Constant T_MX

      `constant Protocols.DNS.T_MX`

    Description

      Type - mail exchange

    Constant T_TXT

      `constant Protocols.DNS.T_TXT`

    Description

      Type - text strings

    Constant T_AAAA

      `constant Protocols.DNS.T_AAAA`

    Description

      Type - IPv6 address record (RFC 1886, deprecated)

    Constant T_LOC

      `constant Protocols.DNS.T_LOC`

    Description

      Type - Location Record (RFC 1876)

    Constant T_SRV

      `constant Protocols.DNS.T_SRV`

    Description

      Type - Service location record (RFC 2782)

    Constant T_NAPTR

      `constant Protocols.DNS.T_NAPTR`

    Description

      Type - NAPTR (RFC 3403)

    Constant T_A6

      `constant Protocols.DNS.T_A6`

    Description

      Type - IPv6 address record (RFC 2874, incomplete support)

    Constant T_SPF

      `constant Protocols.DNS.T_SPF`

    Description

      Type - SPF - Sender Policy Framework (RFC 4408)

  CLASS Protocols.DNS.protocol

    Description

      Low level DNS protocol

    Method mkquery

      `string mkquery(string|mapping dnameorquery, int|void cl, int|void type)`

    Description

      create a DNS query PDU

    Parameter `dnameorquery`
    Parameter `cl`

      record class such as Protocols.DNS.C_IN

    Parameter `type`

      query type such Protocols.DNS.T_A

    Returns

      data suitable for use with Protocols.DNS.client.do_sync_query

    Example

          // generate a query PDU for a address lookup on the hostname pike.ida.liu.se
           string q=Protocols.DNS.protocol()->mkquery("pike.ida.liu.se", Protocols.DNS.C_IN, Protocols.DNS.T_A);

    Method decode_entries

      `array decode_entries(string s, int num, array(int) next)`

    Description

      Decode a set of entries from an answer.

    Parameter `s`

      Encoded entries.

    Parameter `num`

      Number of entires in s .

    Parameter `next`

      Array with a single element containing the start position in s on entry and the continuation position on return.

    Returns

      Returns an array of mappings describing the decoded entires:

      Array

      `mapping 0..`

      Mapping describing a single entry:

      `"name" : string` | Name the entry concerns.
      `"type" : EntryType` | Type of entry.
      `"cl" : ResourceClass` | Resource class. Typically C_IN .
      `"ttl" : int` | Time to live for the entry in seconds.
      `"len" : int` | Length in bytes of the encoded data section.

      Depending on the type of entry the mapping may contain different additional fields:

      `T_CNAME`

      `"cname" : string`

      `T_PTR`

      `"ptr" : string`

      `T_NS`

      `"ns" : string`

      `T_MX`

      `"preference" : int`
      `"mx" : string`

      `T_HINFO`

      `"cpu" : string`
      `"os" : string`

      `T_SRV`

      RFC 2052 and RFC 2782.

      `"priority" : int`
      `"weight" : int`
      `"port" : int`
      `"target" : string`
      `"service" : string`
      `"proto" : string`
      `"name" : string`

      `T_A`

      `"a" : string` | IPv4-address in dotted-decimal format.

      `T_AAAA`

      `"aaaa" : string` | IPv6-address in colon-separated hexadecimal format.

      `T_LOC`

      `"version" : int` | Version, currently only version `0` (zero) is supported.
      `"size" : int` |
      `"h_perc" : int` |
      `"v_perc" : int` |
      `"lat" : int` |
      `"long" : int` |
      `"alt" : int` |

      `T_SOA`

      `"mname" : string` |
      `"rname" : string` |
      `"serial" : int` |
      `"refresh" : int` |
      `"retry" : int` |
      `"expire" : int` |
      `"minimum" : int` | Note: For historical reasons this entry is named `"minimum"`, but it contains the TTL for negative answers (RFC 2308).

      `T_NAPTR`

      `"order" : int`
      `"preference" : int`
      `"flags" : string`
      `"service" : string`
      `"regexp" : string`
      `"replacement" : string`

      `T_TXT`

      `"txt" : string`

      `T_SPF`

      `"spf" : string`

  CLASS Protocols.DNS.server

    Description

      Base class for implementing a Domain Name Service (DNS) server.

      This class is typically used by inheriting it, and overloading reply_query() and handle_response() .

    Inherit protocol

      inherit protocol : protocol

    Method reply_query

      `mapping reply_query(mapping query, mapping udp_data, function(mapping:void) cb)`

    Description

      Reply to a query (stub).

    Parameter `query`

      Parsed query.

    Parameter `udp_data`

      Raw UDP data.

    Parameter `cb`

      Callback you can call with the result instead of returning it. In that case, return `0` (zero).

      Overload this function to implement the proper lookup.

    Returns

      Returns `0` (zero) on failure, or a result mapping on success:

      `"rcode" : int`

      Array

      `mapping(string:string|int) entry`

      `"name" : string|array(string)`
      `"type" : int`
      `"cl" : int`

      `"an" : array(mapping(string:string|int))|void`
      `"qd" : array|void` |
      `"ns" : array|void` |
      `"ar" : array|void` |

    Method create

      `void Protocols.DNS.server()`
      `void Protocols.DNS.server(int port)`
      `void Protocols.DNS.server(string ip)`
      `void Protocols.DNS.server(string ip, int port)`
      `void Protocols.DNS.server(string ip, int port, string|int ... more)`

    Description

      Open one or more new DNS server ports.

    Parameter `ip`

      The IP to bind to. Defaults to `"::"` or `0` (ie ANY) depending on whether IPv6 support is present or not.

    Parameter `port`

      The port number to bind to. Defaults to `53`.

    Parameter `more`

      Optional further DNS server ports to open. Must be a set of ip , port argument pairs.

  CLASS Protocols.DNS.client

    Description

      Synchronous DNS client.

    Inherit protocol

      inherit protocol : protocol

    Method create

      `void Protocols.DNS.client()`
      `void Protocols.DNS.client(void|string|array server, void|int|array domain)`

    Method do_sync_query

      `mapping do_sync_query(string s)`

    Description

      Perform a synchronous DNS query.

    Parameter `s`

      result of Protocols.DNS.protocol.mkquery

    Returns

      mapping containing query result or 0 on failure/timeout

    Example

          // perform a hostname lookup, results stored in r->an
           object d=Protocols.DNS.client();
           mapping r=d->do_sync_query(d->mkquery("pike.ida.liu.se", C_IN, T_A));

    Method gethostbyname

      `array gethostbyname(string hostname)`

    Description

      Queries the host name from the default or given DNS server. The result is an array with three elements,

    Returns

      An array with the requested information about the specified host.

      Array
      `string hostname` | Hostname.
      `array(string) ip` | IP number(s).
      `array(string) aliases` | DNS name(s).

    Note

      Prior to Pike 7.7 this function only returned IPv4 addresses.

    Method getsrvbyname

      `array getsrvbyname(string service, string protocol, string|void name)`

    Description

      Queries the service record (RFC 2782) from the default or given DNS server. The result is an array of arrays with the following six elements for each record. The array is sorted according to the priority of each record.

      Each element of the array returned represents a service record. Each service record contains the following:

    Returns

      An array with the requested information about the specified service.

      Array
      `int priority` | Priority
      `int weight` | Weight in event of multiple records with same priority.
      `int port` | port number
      `string target` | target dns name

    Method gethostbyaddr

      `array gethostbyaddr(string hostip)`

    Description

      Queries the host name or ip from the default or given DNS server. The result is an array with three elements,

    Returns

      The requested data about the specified host.

      Array
      `string hostip` | The host IP.
      `array(string) ip` | IP number(s).
      `array(string) aliases` | DNS name(s).

    Method get_primary_mx

      `string get_primary_mx(string hostname)`

    Description

      Queries the primary mx for the host.

    Returns

      Returns the hostname of the primary mail exchanger.

  CLASS Protocols.DNS.async_client

    Description

      Asynchronous DNS client.

    Inherit client

      inherit client : client

    Inherit udp

      inherit Stdio.UDP : udp

    Method host_to_ip

      `void host_to_ip(string host, function callback, mixed ... args)`

    Method ip_to_host

      `void ip_to_host(string ip, function callback, mixed ... args)`

    Method get_mx_all

      `void get_mx_all(string host, function callback, mixed ... args)`

    Method get_mx

      `void get_mx(string host, function callback, mixed ... args)`

    Method close

      `void close()`

    Description

      Close the client.

    Note

      All active requests are aborted.

Module Protocols.TELNET

  Description

    Implements TELNET as described by RFC 764 and RFC 854

    Also implements the Q method of TELNET option negotiation as specified by RFC 1143.

  Inherit TelnetCodes

    inherit TelnetCodes : TelnetCodes

  Inherit Telopts

    inherit Telopts : Telopts

  Constant TELQUAL_IS

    `constant Protocols.TELNET.TELQUAL_IS`

  Description

    option is...

  Constant TELQUAL_SEND

    `constant Protocols.TELNET.TELQUAL_SEND`

  Description

    send option

  Constant TELQUAL_INFO

    `constant Protocols.TELNET.TELQUAL_INFO`

  Description

    ENVIRON: informational version of IS

  Constant TELQUAL_REPLY

    `constant Protocols.TELNET.TELQUAL_REPLY`

  Description

    AUTHENTICATION: client version of IS

  Constant TELQUAL_NAME

    `constant Protocols.TELNET.TELQUAL_NAME`

  Description

    AUTHENTICATION: client version of IS

  Constant LFLOW_OFF

    `constant Protocols.TELNET.LFLOW_OFF`

  Description

    Disable remote flow control

  Constant LFLOW_ON

    `constant Protocols.TELNET.LFLOW_ON`

  Description

    Enable remote flow control

  Constant LFLOW_RESTART_ANY

    `constant Protocols.TELNET.LFLOW_RESTART_ANY`

  Description

    Restart output on any char

  Constant LFLOW_RESTART_XON

    `constant Protocols.TELNET.LFLOW_RESTART_XON`

  Description

    Restart output only on XON

  Constant AUTH_WHO_CLIENT

    `constant Protocols.TELNET.AUTH_WHO_CLIENT`

  Description

    Client authenticating server

  Constant AUTH_WHO_SERVER

    `constant Protocols.TELNET.AUTH_WHO_SERVER`

  Description

    Server authenticating client

  CLASS Protocols.TELNET.TelnetCodes

    Description

      Table of IAC-codes.

    Constant IAC

      `constant Protocols.TELNET.TelnetCodes.IAC`

    Description

      interpret as command.

    Constant DONT

      `constant Protocols.TELNET.TelnetCodes.DONT`

    Description

      you are not to use option

    Constant DO

      `constant Protocols.TELNET.TelnetCodes.DO`

    Description

      please, you use option

    Constant WONT

      `constant Protocols.TELNET.TelnetCodes.WONT`

    Description

      I won't use option

    Constant WILL

      `constant Protocols.TELNET.TelnetCodes.WILL`

    Description

      I will use option

    Constant SB

      `constant Protocols.TELNET.TelnetCodes.SB`

    Description

      interpret as subnegotiation

    Constant GA

      `constant Protocols.TELNET.TelnetCodes.GA`

    Description

      you may reverse the line

    Constant EL

      `constant Protocols.TELNET.TelnetCodes.EL`

    Description

      erase the current line

    Constant EC

      `constant Protocols.TELNET.TelnetCodes.EC`

    Description

      erase the current character

    Constant AYT

      `constant Protocols.TELNET.TelnetCodes.AYT`

    Description

      are you there

    Constant AO

      `constant Protocols.TELNET.TelnetCodes.AO`

    Description

      abort output--but let prog finish

    Constant IP

      `constant Protocols.TELNET.TelnetCodes.IP`

    Description

      interrupt process--permanently

    Constant BREAK

      `constant Protocols.TELNET.TelnetCodes.BREAK`

    Description

      break

    Constant DM

      `constant Protocols.TELNET.TelnetCodes.DM`

    Description

      data mark--for connect. cleaning

    Constant NOP

      `constant Protocols.TELNET.TelnetCodes.NOP`

    Description

      nop

    Constant SE

      `constant Protocols.TELNET.TelnetCodes.SE`

    Description

      end sub negotiation

    Constant EOR

      `constant Protocols.TELNET.TelnetCodes.EOR`

    Description

      end of record (transparent mode)

    Constant ABORT

      `constant Protocols.TELNET.TelnetCodes.ABORT`

    Description

      Abort process

    Constant SUSP

      `constant Protocols.TELNET.TelnetCodes.SUSP`

    Description

      Suspend process

    Constant xEOF

      `constant Protocols.TELNET.TelnetCodes.xEOF`

    Description

      End of file: EOF is already used...

    Constant SYNCH

      `constant Protocols.TELNET.TelnetCodes.SYNCH`

    Description

      for telfunc calls

  CLASS Protocols.TELNET.Telopts

    Description

      Table of TELNET options.

    Constant TELOPT_BINARY

      `constant Protocols.TELNET.Telopts.TELOPT_BINARY`

    Description

      8-bit data path

    Constant TELOPT_ECHO

      `constant Protocols.TELNET.Telopts.TELOPT_ECHO`

    Description

      echo

    Constant TELOPT_RCP

      `constant Protocols.TELNET.Telopts.TELOPT_RCP`

    Description

      prepare to reconnect

    Constant TELOPT_SGA

      `constant Protocols.TELNET.Telopts.TELOPT_SGA`

    Description

      suppress go ahead

    Constant TELOPT_NAMS

      `constant Protocols.TELNET.Telopts.TELOPT_NAMS`

    Description

      approximate message size

    Constant TELOPT_STATUS

      `constant Protocols.TELNET.Telopts.TELOPT_STATUS`

    Description

      give status

    Constant TELOPT_TM

      `constant Protocols.TELNET.Telopts.TELOPT_TM`

    Description

      timing mark

    Constant TELOPT_RCTE

      `constant Protocols.TELNET.Telopts.TELOPT_RCTE`

    Description

      remote controlled transmission and echo

    Constant TELOPT_NAOL

      `constant Protocols.TELNET.Telopts.TELOPT_NAOL`

    Description

      negotiate about output line width

    Constant TELOPT_NAOP

      `constant Protocols.TELNET.Telopts.TELOPT_NAOP`

    Description

      negotiate about output page size

    Constant TELOPT_NAOCRD

      `constant Protocols.TELNET.Telopts.TELOPT_NAOCRD`

    Description

      negotiate about CR disposition

    Constant TELOPT_NAOHTS

      `constant Protocols.TELNET.Telopts.TELOPT_NAOHTS`

    Description

      negotiate about horizontal tabstops

    Constant TELOPT_NAOHTD

      `constant Protocols.TELNET.Telopts.TELOPT_NAOHTD`

    Description

      negotiate about horizontal tab disposition

    Constant TELOPT_NAOFFD

      `constant Protocols.TELNET.Telopts.TELOPT_NAOFFD`

    Description

      negotiate about formfeed disposition

    Constant TELOPT_NAOVTS

      `constant Protocols.TELNET.Telopts.TELOPT_NAOVTS`

    Description

      negotiate about vertical tab stops

    Constant TELOPT_NAOVTD

      `constant Protocols.TELNET.Telopts.TELOPT_NAOVTD`

    Description

      negotiate about vertical tab disposition

    Constant TELOPT_NAOLFD

      `constant Protocols.TELNET.Telopts.TELOPT_NAOLFD`

    Description

      negotiate about output LF disposition

    Constant TELOPT_XASCII

      `constant Protocols.TELNET.Telopts.TELOPT_XASCII`

    Description

      extended ascic character set

    Constant TELOPT_LOGOUT

      `constant Protocols.TELNET.Telopts.TELOPT_LOGOUT`

    Description

      force logout

    Constant TELOPT_BM

      `constant Protocols.TELNET.Telopts.TELOPT_BM`

    Description

      byte macro

    Constant TELOPT_DET

      `constant Protocols.TELNET.Telopts.TELOPT_DET`

    Description

      data entry terminal

    Constant TELOPT_SUPDUP

      `constant Protocols.TELNET.Telopts.TELOPT_SUPDUP`

    Description

      supdup protocol

    Constant TELOPT_SUPDUPOUTPUT

      `constant Protocols.TELNET.Telopts.TELOPT_SUPDUPOUTPUT`

    Description

      supdup output

    Constant TELOPT_SNDLOC

      `constant Protocols.TELNET.Telopts.TELOPT_SNDLOC`

    Description

      send location

    Constant TELOPT_TTYPE

      `constant Protocols.TELNET.Telopts.TELOPT_TTYPE`

    Description

      terminal type

    Constant TELOPT_EOR

      `constant Protocols.TELNET.Telopts.TELOPT_EOR`

    Description

      end or record

    Constant TELOPT_TUID

      `constant Protocols.TELNET.Telopts.TELOPT_TUID`

    Description

      TACACS user identification

    Constant TELOPT_OUTMRK

      `constant Protocols.TELNET.Telopts.TELOPT_OUTMRK`

    Description

      output marking

    Constant TELOPT_TTYLOC

      `constant Protocols.TELNET.Telopts.TELOPT_TTYLOC`

    Description

      terminal location number

    Constant TELOPT_3270REGIME

      `constant Protocols.TELNET.Telopts.TELOPT_3270REGIME`

    Description

      3270 regime

    Constant TELOPT_X3PAD

      `constant Protocols.TELNET.Telopts.TELOPT_X3PAD`

    Description

      X.3 PAD

    Constant TELOPT_NAWS

      `constant Protocols.TELNET.Telopts.TELOPT_NAWS`

    Description

      window size

    Constant TELOPT_TSPEED

      `constant Protocols.TELNET.Telopts.TELOPT_TSPEED`

    Description

      terminal speed

    Constant TELOPT_LFLOW

      `constant Protocols.TELNET.Telopts.TELOPT_LFLOW`

    Description

      remote flow control

    Constant TELOPT_LINEMODE

      `constant Protocols.TELNET.Telopts.TELOPT_LINEMODE`

    Description

      Linemode option

    Constant TELOPT_XDISPLOC

      `constant Protocols.TELNET.Telopts.TELOPT_XDISPLOC`

    Description

      X Display Location

    Constant TELOPT_OLD_ENVIRON

      `constant Protocols.TELNET.Telopts.TELOPT_OLD_ENVIRON`

    Description

      Old - Environment variables

    Constant TELOPT_AUTHENTICATION

      `constant Protocols.TELNET.Telopts.TELOPT_AUTHENTICATION`

    Description

      Authenticate

    Constant TELOPT_ENCRYPT

      `constant Protocols.TELNET.Telopts.TELOPT_ENCRYPT`

    Description

      Encryption option

    Constant TELOPT_NEW_ENVIRON

      `constant Protocols.TELNET.Telopts.TELOPT_NEW_ENVIRON`

    Description

      New - Environment variables

    Constant TELOPT_EXOPL

      `constant Protocols.TELNET.Telopts.TELOPT_EXOPL`

    Description

      extended-options-list

  CLASS Protocols.TELNET.protocol

    Description

      Implementation of the TELNET protocol.

    Variable fd

      `protected object Protocols.TELNET.protocol.fd`

    Description

      The connection.

    Variable cb

      `protected mapping Protocols.TELNET.protocol.cb`

    Description

      Mapping containing extra callbacks.

    Variable id

      `protected mixed Protocols.TELNET.protocol.id`

    Description

      Value to send to the callbacks.

    Variable write_cb

      `protected function(mixed|void:string) Protocols.TELNET.protocol.write_cb`

    Description

      Write callback.

    Variable read_cb

      `protected function(mixed:void) Protocols.TELNET.protocol.read_cb`

    Description

      Read callback.

    Variable close_cb

      `protected function(mixed|void:void) Protocols.TELNET.protocol.close_cb`

    Description

      Close callback.

      `protected array(int) Protocols.TELNET.protocol.remote_options`
      `protected array(int) Protocols.TELNET.protocol.local_options`

    Description

      Negotiation states of all WILL/WON'T options. See RFC 1143 for a description of the states.

    Variable to_send

      `protected string Protocols.TELNET.protocol.to_send`

    Description

      Data queued to be sent.

    Variable done

      `protected int Protocols.TELNET.protocol.done`

    Description

      Indicates that connection should be closed

    Variable nonblocking_write

      `protected int Protocols.TELNET.protocol.nonblocking_write`

    Description

      Tells if we have set the nonblocking write callback or not.

    Method enable_write

      `void enable_write()`

    Description

      Turns on the write callback if apropriate.

    Method disable_write

      `void disable_write()`

    Description

      Turns off the write callback if apropriate.

    Method write

      `void write(string s)`

    Description

      Queues data to be sent to the other end of the connection.

    Parameter `s`

      String to send.

    Method write_raw

      `void write_raw(string s)`

    Description

      Queues raw data to be sent to the other end of the connection.

    Parameter `s`

      String with raw telnet data to send.

    Method close

      `void close()`

    Description

      Closes the connetion neatly

    Method send_data

      `void send_data()`

    Description

      Callback called when it is clear to send data over the connection. This function does the actual sending.

    Method send_synch

      `void send_synch()`

    Description

      Sends a TELNET synch command.

    Method send_DO

      `void send_DO(int option)`

    Description

      Starts negotiation to enable a TELNET option.

    Parameter `option`

      The option to enable.

    Method send_DONT

      `void send_DONT(int option)`

    Description

      Starts negotiation to disable a TELNET option.

    Parameter `option`

      The option to disable.

    Variable synch

      `protected int Protocols.TELNET.protocol.synch`

    Description

      Indicates whether we are in synch-mode or not.

    Method got_oob

      `void got_oob(mixed ignored, string s)`

    Description

      Callback called when Out-Of-Band data has been received.

    Parameter `ignored`

      The id from the connection.

    Parameter `s`

      The Out-Of-Band data received.

    Method call_read_cb

      `void call_read_cb(string data)`

    Description

      Calls read_cb() .

      Specifically provided for overloading

    Method got_data

      `void got_data(mixed ignored, string line)`

    Description

      Callback called when normal data has been received. This function also does most of the TELNET protocol parsing.

    Parameter `ignored`

      The id from the connection.

    Parameter `s`

      The received data.

    Method set_read_callback

      `void set_read_callback(function(mixed:void) r_cb)`

    Method query_read_callback

      `function(mixed:void) query_read_callback()`

    Method set_write_callback

      `void set_write_callback(function(mixed|void:string) w_cb)`

    Description

      Sets the callback to be called when it is clear to send.

    Parameter `w_cb`

      The new write callback.

    Method query_write_callback

      `function(mixed|void:string) query_write_callback()`

    Method set_close_callback

      `void set_close_callback(function(mixed|void:void) c_cb)`

    Method query_close_callback

      `function(mixed|void:void) query_close_callback()`

    Method setup

      `void setup()`

    Description

      Called when the initial setup is done.

      Created specifically for overloading

    Method create

      `void Protocols.TELNET.protocol(object f, function(mixed:void) r_cb, function(mixed|void:string) w_cb, function(mixed|void:void) c_cb, mapping callbacks, mixed|void new_id)`

    Description

      Creates a TELNET protocol handler, and sets its callbacks.

    Parameter `f`

      File to use for the connection.

    Parameter `r_cb`

      Function to call when data has arrived.

    Parameter `w_cb`

      Function to call when the send buffer is empty.

    Parameter `c_cb`

      Function to call when the connection is closed.

    Parameter `callbacks`

      Mapping with callbacks for the various TELNET commands.

    Parameter `new_id`

      Value to send to the various callbacks.

    Method set_nonblocking

      `void set_nonblocking(function(mixed:void) r_cb, function(mixed|void:string) w_cb, function(mixed|void:void) c_cb)`

    Description

      Change the asynchronous I/O callbacks.

    Parameter `r_cb`

      Function to call when data has arrived.

    Parameter `w_cb`

      Function to call when the send buffer is empty.

    Parameter `c_cb`

      Function to call when the connection is closed.

    See also

      create()

  CLASS Protocols.TELNET.LineMode

    Description

      Line-oriented TELNET protocol handler.

    Inherit protocol

      inherit protocol : protocol

    Description

      Based on the generic TELNET protocol handler.

    Method setup

      `void setup()`

    Description

      Perform the initial TELNET handshaking for LINEMODE.

  CLASS Protocols.TELNET.Readline

    Description

      Line-oriented TELNET protocol handler with Stdio.Readline support.

      Implements the Stdio.NonblockingStream API.

    Inherit LineMode

      inherit LineMode : LineMode

    Description

      Based on the Line-oriented TELNET protocol handler.

    Variable readline

      `Stdio.Readline Protocols.TELNET.Readline.readline`

    Description

      Stdio.Readline object handling the connection.

    Method tcgetattr

      `mapping(string:int) tcgetattr()`

    Description

      Get current terminal attributes.

      Currently only the following attributes are supported:

      `"columns"` | Number of columns.
      `"rows"` | Number of rows.
      `"ECHO"` | Local character echo on (`1`) or off (`0` (zero)).
      `"ICANON"` | Canonical input on (`1`) or off (`0` (zero)).

    Note

      Using this function currently bypasses the Readline layer.

    See also

      Stdio.File()->tcgetattr()

    Method tcsetattr

      `int tcsetattr(mapping(string:int) options, string|void when)`

    Description

      Set terminal attributes.

      Currently only the following attributes are supported:

      `"ECHO"` | Local character echo on (`1`) or off (`0` (zero)).
      `"ICANON"` | Canonical input on (`1`) or off (`0` (zero)).

    Note

      Using this function currently bypasses the Readline layer.

    See also

      Stdio.File()->tcsetattr()

    Method set_secret

      `void set_secret(int onoff)`

    Description

      Turn on/off echo mode.

    Method message

      `void message(string s, void|int word_wrap)`

    Description

      Write a message.

    Method set_prompt

      `void set_prompt(string s)`

    Description

      Set the readline prompt.

    Method close

      `void close()`

    Description

      Close the connection.

    Method create

      `void Protocols.TELNET.Readline(object f, function(mixed:void) r_cb, function(mixed|void:string) w_cb, function(mixed|void:void) c_cb, mapping callbacks, mixed|void new_id)`

    Description

      Creates a TELNET protocol handler, and sets its callbacks.

    Parameter `f`

      File to use for the connection.

    Parameter `r_cb`

      Function to call when data has arrived.

    Parameter `w_cb`

      Function to call when the send buffer is empty.

    Parameter `c_cb`

      Function to call when the connection is closed.

    Parameter `callbacks`

      Mapping with callbacks for the various TELNET commands.

    Parameter `new_id`

      Value to send to the various callbacks.

    Method set_nonblocking

      `void set_nonblocking(function(mixed:void) r_cb, function(mixed|void:string) w_cb, function(mixed|void:void) c_cb)`

    Description

      Change the asynchronous I/O callbacks.

    Parameter `r_cb`

      Function to call when data has arrived.

    Parameter `w_cb`

      Function to call when the send buffer is empty.

    Parameter `c_cb`

      Function to call when the connection is closed.

    See also

      create()

    Method set_read_callback

      `void set_read_callback(function(mixed:void) r_cb)`

    Method query_read_callback

      `function(mixed:void) query_read_callback()`

    Method set_write_callback

      `void set_write_callback(function(mixed|void:string) w_cb)`

    Method query_write_callback

      `function(mixed|void:string) query_write_callback()`

    Method set_close_callback

      `void set_close_callback(function(mixed|void:void) c_cb)`

    Method query_close_callback

      `function(mixed|void:void) query_close_callback()`

    Method set_blocking

      `void set_blocking()`

    Method write

      `void write(string s)`

    Description

      Queues data to be sent to the other end of the connection.

    Parameter `s`

      String to send.

Module Protocols.Line

  CLASS Protocols.Line.simple

    Description

      Simple nonblocking line-oriented I/O.

    Constant line_separator

      `constant Protocols.Line.simple.line_separator`

    Description

      The sequence separating lines from eachother. "\r\n" by default.

    Variable handle_data

      `function(string:void) Protocols.Line.simple.handle_data`

    Description

      If this variable has been set, multiple lines will be accumulated, until a line with a single `"."` (period) is received. handle_data() will then be called with the accumulated data as the argument.

    Note

      handle_data() is one-shot, ie it will be cleared when it is called.

      The line with the single `"."` (period) will not be in the accumulated data.

    See also

      handle_command()

    Method handle_command

      `void handle_command(string line)`

    Description

      This function will be called once for every line that is received.

      Overload this function as appropriate.

    Note

      It will not be called if handle_data() has been set.

      line will not contain the line separator.

    See also

      handle_data()

    Method send

      `void send(string s)`

    Description

      Queue some data to send.

    See also

      handle_command() , handle_data() , disconnect()

    Method do_timeout

      `void do_timeout()`

    Description

      This function is called when a timeout occurrs.

      Overload this function as appropriate.

      The default action is to shut down the connection immediately.

    See also

      create() , touch_time()

    Method touch_time

      `void touch_time()`

    Description

      Reset the timeout timer.

    See also

      create() , do_timeout()

    Method read_line

      `string read_line()`

    Description

      Read a line from the input.

    Returns

      Returns `0` when more input is needed. Returns the requested line otherwise.

    Note

      The returned line will not contain the line separator.

    See also

      handle_command() , line_separator

    Method read_callback

      `void read_callback(mixed ignored, string data)`

    Description

      Called when data has been received.

      Overload as appropriate.

      Calls the handle callbacks repeatedly until no more lines are available.

    See also

      handle_data() , handle_command() , read_line()

    Variable send_q

      `ADT.Queue Protocols.Line.simple.send_q`

    Description

      Queue of data that is pending to send.

      The elements in the queue are either strings with data to send, or `0` (zero) which is the end of file marker. The connection will be closed when the end of file marker is reached.

    See also

      send() , disconnect()

    Method disconnect

      `void disconnect()`

    Description

      Disconnect the connection.

      Pushes an end of file marker onto the send queue send_q .

    Note

      Note that the actual closing of the connection is delayed until all data in the send queue has been sent.

      No more data will be read from the other end after this function has been called.

    Method close_callback

      `void close_callback()`

    Description

      This function is called when the connection has been closed at the other end.

      Overload this function as appropriate.

      The default action is to shut down the connection on this side as well.

    Method create

      `void Protocols.Line.simple(Stdio.File con, int|void timeout)`

    Description

      Create a simple nonblocking line-based protocol handler.

      con is the connection.

      timeout is an optional timeout in seconds after which the connection will be closed if there has been no data sent or received.

      If timeout is `0` (zero), no timeout will be in effect.

    See also

      touch_time() , do_timeout()

  CLASS Protocols.Line.smtp_style

    Description

      Nonblocking line-oriented I/O with support for sending SMTP-style codes.

    Inherit simple

      inherit simple : simple

    Variable errorcodes

      `mapping(int:string|array(string)) Protocols.Line.smtp_style.errorcodes`

    Description

      Mapping from return-code to error-message.

      Overload this constant as apropriate.

    Method send

      `void send(int(100..999) code, array(string)|string|void lines)`

    Description

      Send an SMTP-style return-code.

      code is an SMTP-style return-code.

      If lines is omitted, errorcodes will be used to lookup an appropriate error-message.

      If lines is a string, it will be split on `"\n"` (newline), and the error-code interspersed as appropriate.

    See also

      errorcodes

  CLASS Protocols.Line.imap_style

    Description

      Nonblocking line-oriented I/O with support for reading literals.

    Inherit simple

      inherit simple : simple

    Variable literal_length

      `int Protocols.Line.imap_style.literal_length`

    Description

      Length in bytes of the literal to read.

    Variable handle_literal

      `function(string:void) Protocols.Line.imap_style.handle_literal`

    Description

      If this variable has been set, literal_length bytes will be accumulated, and this function will be called with the resulting data.

    Note

      handle_literal() is one-shot, ie it will be cleared when it is called.

    Variable handle_line

      `function(string:void) Protocols.Line.imap_style.handle_line`

    Description

      This function will be called once for every line that is received.

    Note

      This API is provided for backward compatibility; overload handle_command() instead.

    See also

      Protocols.Line.simple()->handle_command()

    Method handle_command

      `void handle_command(string line)`

    Description

      Function called once for every received line.

    Method expect_literal

      `void expect_literal(int length, function(string:void) callback)`

    Description

      Enter literal reading mode.

      Sets literal_length and handle_literal() .

    See also

      literal_length , handle_literal()

Module Protocols.NNTP

  CLASS Protocols.NNTP.protocol

    Description

      NNTP protocol

    Inherit sock

      inherit Stdio.FILE : sock

    Method readreturncode

      `int readreturncode()`

    Description

      reads the server result code for last request used internally by command().

    Method read_body_lines

      `array(string) read_body_lines()`

    Description

      reads the message from the server as an array of lines

    Method readreturnbody

      `string readreturnbody()`

    Description

      reads the message from the server

    Method writebody

      `void writebody(string s)`

    Description

      send the body of a message to the server.

    Method command

      `int command(string cmd)`

    Description

      send a command to the server

    Returns

      the result code sent by the server

    Method get_response_message

      `string get_response_message()`

    Description

      gets the result message supplied by the server for the last response

    Method failsafe_command

      `int failsafe_command(string cmd)`

    Description

      send a command and require an ok response (200 series). throws an error if the command result was not success.

    Method do_cmd_with_body

      `string do_cmd_with_body(string cmd)`

    Description

      send a command that should return a message body.

    Returns

      the message body

  CLASS Protocols.NNTP.client

    Description

      An NNTP client

    Inherit protocol

      inherit protocol : protocol

    Method list_groups

      `array(Group) list_groups()`

    Description

      Returns a list of all active groups.

    Variable current_group

      `Group Protocols.NNTP.client.current_group`

    Description

      The current news group.

    Method set_group

      `void set_group(Group o)`

    Description

      Sets the current news group to o .

    Method go_to_group

      `Group go_to_group(string group)`

    Description

      Sets the current group to group .

    Method head

      `string head(void|int|string x)`

    Method body

      `string body(void|int|string x)`

    Method article

      `string article(void|int|string x)`

    Method create

      `void Protocols.NNTP.client(string|void server)`

Module Protocols.OBEX

  Description

    The IrDA® Object Exchange Protocol. OBEX is a protocol for sending and receiving binary objects to mobile devices using transports such as IR and Bluetooth.

  Constant SETPATH_BACKUP

    `constant Protocols.OBEX.SETPATH_BACKUP`

  Description

    A flag for the REQ_SETPATH command indicating that the parent directory should be selected

  Constant SETPATH_NOCREATE

    `constant Protocols.OBEX.SETPATH_NOCREATE`

  Description

    A flag for the REQ_SETPATH command indicating that the selected directory should not be created if it doesn't exist

  Typedef Headers

    `typedef mapping(HeaderIdentifier:string|int|array) Protocols.OBEX.Headers`

  Description

    A set of request or response headers. Each HI can be associated with either a single value (int or string, depending on the HI in question) or an array with multiple such values.

  Method encode_headers

    `string encode_headers(Headers h)`

  Description

    Serialize a set of headers to wire format

  See also

    split_headers()

  Method decode_headers

    `Headers decode_headers(string h)`

  Description

    Deserialize a set of headers from wire format

  Method split_headers

    `array(string) split_headers(string h, int chunklen)`

  Description

    Given a set of headers in wire format, divide them into portions of no more than chunklen octets each (if possible). No individual header definition will be split into two portions.

  ENUM Protocols.OBEX.Request

    Description

      A request opcode, for use with the client.do_request() function.

    Constant REQ_CONNECT

      `constant Protocols.OBEX.REQ_CONNECT`

    Description

      Establish a new OBEX connection

    Constant REQ_DISCONNECT

      `constant Protocols.OBEX.REQ_DISCONNECT`

    Description

      Terminate an OBEX connection

    Constant REQ_PUT

      `constant Protocols.OBEX.REQ_PUT`

    Description

      Send an object to the mobile device

    Constant REQ_GET

      `constant Protocols.OBEX.REQ_GET`

    Description

      Receive an object from the mobile devuce

    Constant REQ_SETPATH

      `constant Protocols.OBEX.REQ_SETPATH`

    Description

      Change the working directory

    Constant REQ_SESSION

      `constant Protocols.OBEX.REQ_SESSION`

    Description

      Manage a session

    Constant REQ_ABORT

      `constant Protocols.OBEX.REQ_ABORT`

    Description

      Abort the request currently being processed

    Constant REQ_FINAL

      `constant Protocols.OBEX.REQ_FINAL`

    Description

      For REQ_PUT and REQ_GET requests, REQ_FINAL must be set for the request block containing the last portion of the headers. Other requests must be sent as a single block and have the REQ_FINAL bit encoded in their request opcode.

  ENUM Protocols.OBEX.HeaderIdentifier

    Description

      An identifier for a request or response header

    Constant HI_COUNT

      `constant Protocols.OBEX.HI_COUNT`

    Description

      Number of objects to transfer (used by REQ_CONNECT )

    Constant HI_NAME

      `constant Protocols.OBEX.HI_NAME`

    Description

      Name of the object (string)

    Constant HI_TYPE

      `constant Protocols.OBEX.HI_TYPE`

    Description

      Type of the object (IANA media type)

    Constant HI_LENGTH

      `constant Protocols.OBEX.HI_LENGTH`

    Description

      Length of the object transferred, in octets

    Constant HI_TIME

      `constant Protocols.OBEX.HI_TIME`

    Description

      ISO 8601 timestamp (string)

    Constant HI_DESCRIPTION

      `constant Protocols.OBEX.HI_DESCRIPTION`

    Description

      Text description of the object

    Constant HI_TARGET

      `constant Protocols.OBEX.HI_TARGET`

    Description

      Name of service that operation is targeted to

    Constant HI_HTTP

      `constant Protocols.OBEX.HI_HTTP`

    Description

      Any HTTP 1.x header

    Constant HI_BODY

      `constant Protocols.OBEX.HI_BODY`

    Description

      A chunk of the object body

    Constant HI_ENDOFBODY

      `constant Protocols.OBEX.HI_ENDOFBODY`

    Description

      The final chunk of the object body

    Constant HI_WHO

      `constant Protocols.OBEX.HI_WHO`

    Description

      Identifies the OBEX application (string)

    Constant HI_CONNID

      `constant Protocols.OBEX.HI_CONNID`

    Description

      An identifier used for OBEX connection multiplexing

    Constant HI_APPPARAM

      `constant Protocols.OBEX.HI_APPPARAM`

    Description

      Extended application request & response information

    Constant HI_AUTHCHALL

      `constant Protocols.OBEX.HI_AUTHCHALL`

    Description

      Authentication digest-challenge

    Constant HI_AUTHRESP

      `constant Protocols.OBEX.HI_AUTHRESP`

    Description

      Authentication digest-response

    Constant HI_CREATORID

      `constant Protocols.OBEX.HI_CREATORID`

    Description

      Indicates the creator of an object

    Constant HI_WANUUID

      `constant Protocols.OBEX.HI_WANUUID`

    Description

      Uniquely identifies the OBEX server

    Constant HI_OBJCLASS

      `constant Protocols.OBEX.HI_OBJCLASS`

    Description

      OBEX object class of object

    Constant HI_SESSPARAM

      `constant Protocols.OBEX.HI_SESSPARAM`

    Description

      Parameters used in session commands/responses

    Constant HI_SESSSEQNR

      `constant Protocols.OBEX.HI_SESSSEQNR`

    Description

      Sequence number used in each OBEX packet for reliability

  CLASS Protocols.OBEX.Client

    Description

      An OBEX client

    See also

      ATclient

    Method low_do_request

      `array(int|string) low_do_request(Request r, string data)`

    Description

      Perform a request/response exchange with the server. No interpretation is preformed of either the request or response data, they are just passed literally.

    Parameter `r`

      Request opcode

    Parameter `data`

      Raw request data

    Returns

      An array with the response information

      Array
      `int returncode` | An HTTP response code
      `string data` | Response data, if any

    See also

      do_request()

    Method do_request

      `array(int|Headers) do_request(Request r, Headers|void headers, string|void extra_req)`

    Description

      Perform a request/response exchange with the server, including processing of headers and request splitting.

    Parameter `r`

      Request opcode

    Parameter `headers`

      Request headers

    Parameter `extra_req`

      Any request data that should appear before the headers, but after the opcode

    Returns

      An array with the response information

      Array
      `int returncode` | An HTTP response code
      `Headers headers` | Response headers

    See also

      low_do_request() , do_abort() , do_put() , do_get() , do_setpath() , do_session()

    Method do_abort

      `array(int|Headers) do_abort(Headers|void headers)`

    Description

      Perform a REQ_ABORT request.

    See also

      do_request()

    Method do_put

      `array(int|Headers) do_put(string|Stdio.Stream data, Headers|void extra_headers)`

    Description

      Perform a REQ_PUT request.

    Parameter `data`

      Body data to send, or a stream to read the data from

    Parameter `extra_headers`

      Any additional headers to send (HI_LENGTH and HI_BODY are generated by this function)

    See also

      do_get() , do_request()

    Method do_get

      `array(int|Headers) do_get(Stdio.Stream data, Headers|void headers)`

    Description

      Perform a REQ_GET request.

    Parameter `data`

      A stream to write the body data to

    Parameter `headers`

      Headers for the request

    Returns

      See do_request() . The Headers do not contain any HI_BODY headers, they are written to the data stream.

    See also

      do_put() , do_request()

    Method do_setpath

      `array(int|Headers) do_setpath(string path, int|void flags, Headers|void extra_headers)`

    Description

      Perform a REQ_SETPATH request.

    Parameter `path`

      The directory to set as current working directory

      `"/"` | Go to the root directory
      `".."` | Go to the parent directory

    Parameter `flags`

      Logical or of zero or more of SETPATH_BACKUP and SETPATH_NOCREATE

    Parameter `extra_headers`

      Any additional request headers (the HI_NAME header is generated by this function)

    See also

      do_request()

    Method do_session

      `array(int|Headers) do_session(Headers|void headers)`

    Description

      Perform a REQ_SESSION request.

    See also

      do_request()

    Method connect

      `int(0..1) connect()`

    Description

      Establish a new connection using the REQ_CONNECT opcode to negotiate transfer parameters

    Returns

      If the connection succeeds, 1 is returned. Otherwise, 0 is returned.

    Method disconnect

      `int(0..1) disconnect()`

    Description

      Terminate a connection using the REQ_DISCONNECT opcode

    Returns

      If the disconnection succeeds, 1 is returned. Otherwise, 0 is returned.

    Method create

      `void Protocols.OBEX.Client(Stdio.Stream _con)`

    Description

      Initialize the client by establishing a connection to the server at the other end of the provided transport stream

    Parameter `_con`

      A stream for writing requests and reading back responses. Typically this is some kind of serial port.

  CLASS Protocols.OBEX.ATClient

    Description

      An extension of the client which uses the AT*EOBEX modem command to enter OBEX mode. Use together with Sony Ericsson data cables.

    Inherit Client

      inherit Client : Client

Module Protocols.LPD

  CLASS Protocols.LPD.client

    Description

      A client for communicating with printers and print spoolers that support the BSD lpd protocol (RFC 1179).

    Method set_job_type

      `int set_job_type(string type)`

    Description

      Set the type of job to be sent to the printer to type. Valid types are: text, postscript and raw.

    Method set_job_name

      `int set_job_name(string name)`

    Description

      Sets the name of the print job to name.

    Method start_queue

      `int start_queue(string queue)`

    Description

      Start the queue queue if not already printing.

    Returns

      Returns 0 if unable to connect, 1 otherwise.

    Method send_job

      `string|int send_job(string queue, string job)`

    Description

      Send print job consisting of data job to printer queue.

    Returns

      Returns 1 if success, 0 otherwise.

    Method delete_job

      `int delete_job(string queue, int|void job)`

    Description

      Delete job job from printer queue.

    Returns

      Returns 1 on success, 0 otherwise.

    Method status

      `string|int status(string queue)`

    Description

      Check the status of queue queue.

    Returns

      Returns 0 on failure, otherwise returns the status response from the printer.

    Method create

      `void Protocols.LPD.client(string|void hostname, int|void portnum)`

    Description

      Create a new LPD client connection.

    Parameter `hostname`

      Contains the hostname or ipaddress of the print host. if not provided, defaults to localhost.

    Parameter `portnum`

      Contains the port the print host is listening on. if not provided, defaults to port 515, the RFC 1179 standard.

Module Protocols.LMTP

  CLASS Protocols.LMTP.Server

    Description

      A LMTP server. It has been fairly well tested against Postfix client. Actually this module is only an extention to the SMTP server.

    Method create

      `void Protocols.LMTP.Server(array(string) _domains, void|int port, void|string ip, function _cb_mailfrom, function _cb_rcptto, function _cb_data)`

    Description

      Create a receiving LMTP server. It implements RFC 2821, 2822, 2033 and 1854.

    Parameter `domain`

      Domains name this server relay, you need to provide at least one domain (the first one will be used for MAILER-DAEMON address). if you want to relay everything you can put a '*' after this first domain.

    Parameter `port`

      Port this server listen on

    Parameter `listenip`

      IP on which server listen

    Parameter `cb_mailfrom`

      Mailfrom callback function, this function will be called when a client send a mail from command. This function must take a string as argument (corresponding to the sender's email) and return int corresponding to the SMTP code to output to the client. If you return an array the first element is the SMTP code and the second is the error string to display.

    Parameter `cb_rcptto`

      Same as cb_mailfrom but called when a client sends a rcpt to.

    Parameter `cb_data`

      This function is called for each recipient in the "rcpt to" command after the client sends the "data" command It must have the following synopsis: int|array cb_data(object mime, string sender, string recipient, void|string rawdata) object mime : the mime data object string sender : sender of the mail (from the mailfrom command) string recipient : one recipient given by one rcpt command. return : SMTP code to output to the client. If you return an array the first element is the SMTP code and the second is the error string to display. Note that to comply with LMTP protocol you must output a code each time this function is called.

    Example

          Here is an example of silly program that does nothing except outputing
            informations to stdout.
           int cb_mailfrom(string mail)
           {
             return 250;
           }
           int cb_rcptto(string email)
           {
             // check the user's mailbox here
             return 250;
           }
           int cb_data(object mime, string sender, string recipient)
           {
             write(sprintf("smtpd: mailfrom=%s, to=%s, headers=%O\ndata=%s\n",
             sender, recipient, mime->headers, mime->getdata()));
             // check the data and deliver the mail here
             if(mime->body_parts)
             {
             {
               foreach(mime->body_parts, object mpart)
                 write(sprintf("smtpd: mpart data = %O\n", mpart->getdata()));
             }
             return 250;
           }
           int main(int argc, array(string) argv)
           {
             Protocols.LMTP.Server(({ "ece.fr" }), 2500, "127.0.0.1",       cb_mailfrom, cb_rcptto, cb_data);
             return -1;
           }