.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)
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.
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)
Low level asynchronous HTTP call method.
methodThe HTTP method to use, e.g. "GET".
urlThe URL to perform method on. Should be a complete URL,
including protocol, e.g. "https://pike.lysator.liu.se/".
query_variablesCalls http_encode_query and appends the result to the URL.
request_headersThe 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.
conPreviously initialized connection object.
In particular the callbacks must have been set
(Query.set_callbacks()).
dataData payload to be transmitted in the request.
do_method(), Query.set_callbacks()
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)
Low level asynchronous proxied HTTP call method.
Makes an HTTP request through a proxy.
proxyURL for the proxy.
userpasswordProxy authentication credentials.
methodThe HTTP method to use, e.g. "GET".
urlThe URL to perform method on. Should be a complete URL,
including protocol, e.g. "https://pike.lysator.liu.se/".
query_variablesCalls http_encode_query and appends the result to the URL.
request_headersThe 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.
conPreviously initialized connection object.
In particular the callbacks must have been set
(Query.set_callbacks()).
dataData payload to be transmitted in the request.
do_async_method(), do_proxied_method(), Query.set_callbacks()
.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)
Low level HTTP call method.
methodThe HTTP method to use, e.g. "GET".
urlThe URL to perform method on. Should be a complete URL,
including protocol, e.g. "https://pike.lysator.liu.se/".
query_variablesCalls http_encode_query and appends the result to the URL.
request_headersThe 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.
conOld connection object.
dataData payload to be transmitted in the request.
do_sync_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)
Makes an HTTP request through a proxy.
proxyURL for the proxy.
userpasswordProxy authentication credentials.
methodurlquery_variablesrequest_headerscondataThe remaining arguments are identical to do_method().
do_method(), do_async_proxied_method()
.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)
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.
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)
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.
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)
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.
__deprecated__ string http_encode_cookie(string f)
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.
string http_encode_query(mapping(string:int|string|array(string)) variables)
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( (["&":"&","'=\"":"\0\0\0"]) );
Result: "%26amp%3b=%26&%27%3d%22=%00%00%00"
__deprecated__ string http_encode_string(string in)
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).
Replaced by uri_encode.
string iri_encode(string s)
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.
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.
percent_decode, uri_encode
string iri_normalize(string s)
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.
iri_decode, uri_normalize
string percent_decode(string s)
Decodes URI-style %XX encoded chars in the given string.
percent_encode, uri_decode
This function currently does not accept wide string input, which
is necessary to work as the reverse of iri_encode.
string percent_encode(string s)
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.
.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)
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.
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)
Similar to get_url_data, except that query variables is sent as
a POST request instead of a GET request.
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)
Similar to get_url_nice, except that query variables is sent as
a POST request instead of a GET request.
.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)
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.
string quoted_string_decode(string s)
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.
quoted_string_encode
string quoted_string_encode(string s)
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.
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.
quoted_string_decode
constant Protocols.HTTP.response_codes
Mapping from StatusCode to descriptive string.
StatusCode
__deprecated__ string unentity(string s)
Helper function for replacing HTML entities with the corresponding unicode characters.
Replaced by Parser.parse_html_entities.
string uri_decode(string s)
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.
uri_encode, uri_encode_invalids
string uri_encode(string s)
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.
uri_decode, uri_encode_invalids, iri_encode
string uri_encode_invalids(string s)
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.
The characters in the URI reserved set are: :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, =. In addition, this function doesn't touch the escape char %.
uri_decode, uri_encode
string uri_normalize(string s)
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.
uri_decode, uri_encode, iri_normalize
HTTP Status codes.
response_codes,
https://www.iana.org/assignments/http-status-codes/http-status-codes.txt
constant Protocols.HTTP.DAV_ALREADY_REPORTED
RFC 5842 section 7.1: 208 Already Reported
constant Protocols.HTTP.DAV_FAILED_DEP
RFC 2518 section 10.5: 424 Failed Dependency
constant Protocols.HTTP.DAV_LOCKED
RFC 2518 section 10.4: 423 Locked
constant Protocols.HTTP.DAV_LOOP_DETECTED
RFC 5842 section 7.2: 508 Loop Detected
constant Protocols.HTTP.DAV_MULTISTATUS
RFC 2518 section 10.2: 207 Multi-Status
constant Protocols.HTTP.DAV_PROCESSING
RFC 2518 section 10.1: 102 Processing
constant Protocols.HTTP.DAV_STORAGE_FULL
RFC 2518 section 10.6: 507 Insufficient Storage
constant Protocols.HTTP.DAV_UNPROCESSABLE
RFC 2518 section 10.3: 422 Unprocessable Entry
constant Protocols.HTTP.DELTA_HTTP_IM_USED
RFC 3229 section 10.4.1: 226 IM Used
constant Protocols.HTTP.HTCPCP_TEAPOT
RFC 2324 section 2.3.2: 418 I'm a teapot
constant Protocols.HTTP.HTTP_ACCEPTED
RFC 2616 section 10.2.3: 202 Accepted
constant Protocols.HTTP.HTTP_BAD
RFC 2616 section 10.4.1: 400 Bad Request
constant Protocols.HTTP.HTTP_BAD_GW
RFC 2616 section 10.5.3: 502 Bad Gateway
constant Protocols.HTTP.HTTP_BAD_RANGE
RFC 2616 section 10.4.17: 416 Requested Range Not Satisfiable
constant Protocols.HTTP.HTTP_CONFLICT
RFC 2616 section 10.4.10: 409 Conflict
constant Protocols.HTTP.HTTP_CONTINUE
RFC 2616 section 10.1.1: 100 Continue
constant Protocols.HTTP.HTTP_CREATED
RFC 2616 section 10.2.2: 201 Created
constant Protocols.HTTP.HTTP_EARLY_HINTS
RFC 8297 section 2: 103 Early Hints
constant Protocols.HTTP.HTTP_EXPECT_FAILED
RFC 2616 section 10.4.18: 417 Expectation Failed
constant Protocols.HTTP.HTTP_FORBIDDEN
RFC 2616 section 10.4.4: 403 Forbidden
constant Protocols.HTTP.HTTP_FOUND
RFC 2616 section 10.3.3: 302 Found
constant Protocols.HTTP.HTTP_GONE
RFC 2616 section 10.4.11: 410 Gone
constant Protocols.HTTP.HTTP_GW_TIMEOUT
RFC 2616 section 10.5.5: 504 Gateway Timeout
constant Protocols.HTTP.HTTP_HEADERS_TOO_LARGE
RFC 6585 section 5: 431 Request Header Fields Too Large
constant Protocols.HTTP.HTTP_INTERNAL_ERR
RFC 2616 section 10.5.1: 500 Internal Server Error
constant Protocols.HTTP.HTTP_LEGALLY_RESTRICTED
RFC 7725 section 3: 451 Unavailable For Legal Reasons
constant Protocols.HTTP.HTTP_LENGTH_REQ
RFC 2616 section 10.4.12: 411 Length Required
constant Protocols.HTTP.HTTP_METHOD_INVALID
RFC 2616 section 10.4.6: 405 Method Not Allowed
constant Protocols.HTTP.HTTP_MISDIRECTED_REQ
RFC 7540 section 9.1.2: 421 Misdirected Request
constant Protocols.HTTP.HTTP_MOVED_PERM
RFC 2616 section 10.3.2: 301 Moved Permanently
constant Protocols.HTTP.HTTP_MULTIPLE
RFC 2616 section 10.3.1: 300 Multiple Choices
constant Protocols.HTTP.HTTP_NET_AUTH_REQUIRED
RFC 6585 section 6: 511 Network Authentication Required
constant Protocols.HTTP.HTTP_NONAUTHORATIVE
RFC 2616 section 10.2.4: 203 Non-Authorative Information
constant Protocols.HTTP.HTTP_NOT_ACCEPTABLE
RFC 2616 section 10.4.7: 406 Not Acceptable
constant Protocols.HTTP.HTTP_NOT_EXTENDED
RFC 2774 section 7: 510 Not Extended (obsolete)
constant Protocols.HTTP.HTTP_NOT_FOUND
RFC 2616 section 10.4.5: 404 Not Found
constant Protocols.HTTP.HTTP_NOT_IMPL
RFC 2616 section 10.5.2: 501 Not Implemented
constant Protocols.HTTP.HTTP_NOT_MODIFIED
RFC 2616 section 10.3.5: 304 Not Modified
constant Protocols.HTTP.HTTP_NO_CONTENT
RFC 2616 section 10.2.5: 204 No Content
constant Protocols.HTTP.HTTP_OK
RFC 2616 section 10.2.1: 200 OK
constant Protocols.HTTP.HTTP_PARTIAL_CONTENT
RFC 2616 section 10.2.7: 206 Partial Content
constant Protocols.HTTP.HTTP_PAY
RFC 2616 section 10.4.3: 402 Payment Required
constant Protocols.HTTP.HTTP_PERM_REDIRECT
RFC 7538 section 3: 308 Permanent Redirect
constant Protocols.HTTP.HTTP_PRECOND_FAILED
RFC 2616 section 10.4.13: 412 Precondition Failed
constant Protocols.HTTP.HTTP_PRECOND_REQUIRED
RFC 6585 section 3: 428 Precondition required
constant Protocols.HTTP.HTTP_PROXY_AUTH_REQ
RFC 2616 section 10.4.8: 407 Proxy Authentication Required
constant Protocols.HTTP.HTTP_REQ_TOO_LARGE
RFC 2616 section 10.4.14: 413 Request Entity Too Large
constant Protocols.HTTP.HTTP_RESET_CONTENT
RFC 2616 section 10.2.6: 205 Reset Content
constant Protocols.HTTP.HTTP_SEE_OTHER
RFC 2616 section 10.3.4: 303 See Other
constant Protocols.HTTP.HTTP_SWITCH_PROT
RFC 2616 section 10.1.2: 101 Switching protocols
constant Protocols.HTTP.HTTP_TEMP_REDIRECT
RFC 2616 section 10.3.8: 307 Temporary Redirect
constant Protocols.HTTP.HTTP_TIMEOUT
RFC 2616 section 10.4.9: 408 Request Timeout
constant Protocols.HTTP.HTTP_TOO_MANY_REQUESTS
RFC 6585 section 4: 429 Too Many Requests
constant Protocols.HTTP.HTTP_UNAUTH
RFC 2616 section 10.4.2: 401 Unauthorized
constant Protocols.HTTP.HTTP_UNAVAIL
RFC 2616 section 10.5.4: 503 Service Unavailable
constant Protocols.HTTP.HTTP_UNSUPP_MEDIA
RFC 2616 section 10.4.16: 415 Unsupported Media Type
constant Protocols.HTTP.HTTP_UNSUPP_VERSION
RFC 2616 section 10.5.6: 505 HTTP Version Not Supported
constant Protocols.HTTP.HTTP_URI_TOO_LONG
RFC 2616 section 10.4.15: 414 Request-URI Too Long
constant Protocols.HTTP.HTTP_USE_PROXY
RFC 2616 section 10.3.6: 305 Use Proxy
constant Protocols.HTTP.TCN_VARIANT_NEGOTIATES
RFC 2295 section 8.1: 506 Variant Also Negotiates
constant Protocols.HTTP.TLS_TOO_EARLY
RFC 8470 section 5.2: 425 Too Early
constant Protocols.HTTP.TLS_UPGRADE_REQUIRED
RFC 2817 section 4.2: 426 Upgrade Required
Open and execute an HTTP query.
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.lysator.liu.se", 80, "HEAD / HTTP/1.0"); return -1; }
int res = Protocols.HTTP.Query()()
Wait for connection to complete.
Returns 1 on successfull connection, 0 on failure.
void async_fetch(function(:void) callback, mixed ... extra)
Fetch all data in background.
timed_async_fetch(), async_request(), set_callbacks()
Protocols.HTTP.Query set_callbacks(function(:void) request_ok, function(:void) 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)
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 the called object
(array)Protocols.HTTP.Query()
| Array | |
| Headers |
| Data |
| Protocol |
| Status |
| Status description |
(mapping)Protocols.HTTP.Query()
The header mapping ORed with the following mapping.
| The protocol. |
| The status code. |
| The status description. |
| The returned data. |
(string)Protocols.HTTP.Query()
Gives back the answer as a string.
void close()
Close all associated file descriptors.
string data(int|void max_length)
Gives back the data as a string.
Protocols.HTTP.Query.PseudoFile datafile()
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.
file()
int downloaded_bytes()
Gives back the number of downloaded bytes.
int Protocols.HTTP.Query.errno
Errno copied from the connection or simulated for async operations.
In Pike 7.8 and earlier hardcoded Linux values were used in
async operations, 110 instead of System.ETIMEDOUT and
113 instead of System.EHOSTUNREACH.
Protocols.HTTP.Query.PseudoFile file()
Protocols.HTTP.Query.PseudoFile file(mapping newheaders, void|mapping removeheaders)
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.
datafile()
mapping Protocols.HTTP.Query.headers
Headers as a mapping. All header names are in lower case, for convinience.
string Protocols.HTTP.Query.host
string Protocols.HTTP.Query.real_host
int Protocols.HTTP.Query.port
Connected host and port.
Used to detect whether keep-alive can be used.
mapping Protocols.HTTP.Query.hostname_cache
Set this to a global mapping if you want to use a cache, prior of calling *request().
int Protocols.HTTP.Query.ok
Tells if the connection is successfull.
string Protocols.HTTP.Query.protocol
Protocol string, ie "HTTP/1.0".
int Protocols.HTTP.Query.status
string Protocols.HTTP.Query.status_desc
Status number and description (eg 200 and "ok").
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)
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 the called object.
void timed_async_fetch(function(object, mixed ... :void) ok_callback, function(object, mixed ... :void) fail_callback, mixed ... extra)
Like async_fetch(), except with a timeout and a corresponding fail
callback function.
async_fetch(), async_request(), set_callbacks()
int total_bytes()
Gives back the size of a file if a content-length header is present and parsed at the time of evaluation. Otherwise returns -1.
string unicode_data()
Gives back data, but decoded according to the content-type character set.
data
Minimal simulation of a Stdio.File object.
Objects of this class are returned by file() and datafile().
Do not attempt further queries using this Query object
before having read all data.
void close()
string read(int n, bool|void not_all)
Request async_get_url(URL url, void|mapping query_variables, function(:void) callback_headers_ok, function(:void) callback_data_ok, function(:void) callback_fail, mixed ... callback_arguments)
Request async_put_url(URL url, void|string file, void|mapping query_variables, function(:void) callback_headers_ok, function(:void) callback_data_ok, function(:void) callback_fail, mixed ... callback_arguments)
Request async_delete_url(URL url, void|mapping query_variables, function(:void) callback_headers_ok, function(:void) callback_data_ok, function(:void) callback_fail, mixed ... callback_arguments)
Request async_post_url(URL url, mapping query_variables, function(:void) callback_headers_ok, function(:void) callback_data_ok, function(:void) callback_fail, mixed ... callback_arguments)
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.
string encode_cookies()
void decode_cookies(string data, void no_clear)
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.
mapping Protocols.HTTP.Session.default_headers
Default HTTP headers.
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)
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.
int Protocols.HTTP.Session.follow_redirects
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.
Loops will currently not be detected, only the limit works to stop loops.
Request.follow_redirects
array(string) get_cookies(Standards.URI|SessionURL for_url, void|bool no_delete)
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.
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)
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.
Query give_me_connection(Standards.URI url)
Request a Query object suitable to use for the
given URL. This may be a reused object from a keep-alive
connection.
mapping Protocols.HTTP.Session.hostname_cache
Cache of hostname to IP lookups. Given to and used by the
Query objects.
int Protocols.HTTP.Session.maximum_connection_reuse
Maximum times a connection is reused. Defaults to 1000000. <2 means no reuse at all.
int Protocols.HTTP.Session.maximum_connections_per_server
Maximum number of connections to the same server. Used only by async requests. Defaults to 10 connections.
int Protocols.HTTP.Session.maximum_total_connections
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.
void return_connection(Standards.URI url, Query query)
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.
void set_cookie(Cookie cookie, Standards.URI who)
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.
void set_http_cookie(string cookie, Standards.URI at)
Parse and set a cookie received in the HTTP protocol. The cookie will be checked against current security levels et al.
int|float Protocols.HTTP.Session.time_to_keep_unused_connections
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.
Request
Query Protocols.HTTP.Session.Request.con
Raw connection object
function(string, Standards.URI:mixed) Protocols.HTTP.Session.Request.cookie_encountered
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.
void destroy()
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.
Request do_async(array(string|int|mapping) args)
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.
The called object.
set_callbacks, prepare_method, do_sync, do_thread
Request do_sync(array(string|int|mapping) args)
Perform a request synchronously.
Get arguments from prepare_method.
0 upon failure, this object upon success
prepare_method, do_async, do_thread
Request do_thread(array(string|int|mapping) args)
Start a request in the background, using a thread.
Call wait to wait for the thread to finish.
Get arguments from prepare_method.
The called object.
prepare_method, do_sync, do_async, wait
do_thread does not rerun redirections automatically
int Protocols.HTTP.Session.Request.follow_redirects
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.
Loops will currently not be detected, only the limit works to stop loops.
array(string|int|mapping) prepare_method(string method, URL url, void|mapping query_variables, void|mapping extra_headers, void|string data)
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).
void set_callbacks(function(mixed ... :mixed) headers, function(mixed ... :mixed) data, function(mixed ... :mixed) fail, mixed ... callback_arguments)
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.
Standards.URI Protocols.HTTP.Session.Request.url_requested
URL requested (set by prepare_method). This will update according to followed redirects.
Request wait()
Wait for the request thread to finish.
0 upon failure, or the called object upon success.
do_thread
Class to store URL+referer
Protocols.HTTP.Session.SessionURL Protocols.HTTP.Session.SessionURL(URL uri, URL base_uri, URL _referer)
instantiate a SessionURL object; when fed to Protocols.HTTP.Session calls, will add referer to the HTTP handshaking variables
inherit Standards.URI : URI
URL Protocols.HTTP.Session.SessionURL.referer
the referer to this URL
constant Protocols.HTTP.Server.HeaderParser
Fast HTTP header parser.
string extension_to_type(string extension)
Looks up the file extension in a table to return a suitable MIME type.
string filename_to_type(string filename)
Looks up the file extension in a table to return a suitable MIME type.
string http_date(int time)
Makes a time notification suitable for the HTTP protocol.
timeThe time in seconds since the 00:00:00 UTC, January 1, 1970
The date in the HTTP standard date format. Example : Thu, 03 Aug 2000 05:40:39 GMT
int http_decode_date(string data)
Decode a HTTP date to seconds since 1970 (UTC)
zero (UNDEFINED) if the given string isn't a HTTP date
constant Protocols.HTTP.Server.http_decode_string
mapping(string:string|array(string)) http_decode_urlencoded_query(string query, void|mapping dest)
Decodes an URL-encoded query into a mapping.
The simplest server possible. Binds a port and calls
a callback with request_program objects.
void close()
Closes the HTTP port.
Protocols.HTTP.Server.Port Protocols.HTTP.Server.Port(function(.Request:void) callback)
Protocols.HTTP.Server.Port Protocols.HTTP.Server.Port(function(.Request:void) callback, int portno, void|string interface)
object|function(:void)|program Protocols.HTTP.Server.Port.request_program
string Protocols.HTTP.Server.Request.body_raw
raw unparsed body of the request (raw minus request line and headers)
int Protocols.HTTP.Server.Request.connection_timeout_delay
connection timeout, delay until connection is closed while waiting for the correct headers:
mapping(string:string) Protocols.HTTP.Server.Request.cookies
cookies set by client
string Protocols.HTTP.Server.Request.full_query
full resource requested, including attached GET query
string get_ip()
Return the IP address that originated the request, or 0 if
the IP address could not be determined. In the event of an
error, my_fd->errno() will be set.
mapping Protocols.HTTP.Server.Request.misc
external use only
Stdio.NonblockingStream Protocols.HTTP.Server.Request.my_fd
The socket that this request came in on.
string Protocols.HTTP.Server.Request.not_query
resource requested minus any attached query
string Protocols.HTTP.Server.Request.protocol
request protocol and version, eg. HTTP/1.0
string Protocols.HTTP.Server.Request.query
query portion of requested resource, starting after the first "?"
string Protocols.HTTP.Server.Request.raw
raw unparsed full request (headers and body)
mapping(string:string|array(string)) Protocols.HTTP.Server.Request.request_headers
all headers included as part of the HTTP request, ie content-type.
string Protocols.HTTP.Server.Request.request_raw
full request line (request_type + full_query + protocol)
string Protocols.HTTP.Server.Request.request_type
HTTP request method, eg. POST, GET, etc.
void response_and_finish(mapping m, function(:void)|void _log_cb)
Return a properly formatted response to the HTTP client
mContains elements for generating a response to the client.
| Data to be returned to the client. |
| File object, the contents of which will be returned to the client. |
| HTTP error code |
| Length of content to be returned. If file is provided, size bytes will be returned to client. |
| Contains optional modification date. |
| Contains optional content-type |
| Contains a mapping of additional headers to be returned to client. |
| Contains the server identification header. |
int Protocols.HTTP.Server.Request.send_timeout_delay
send timeout (no activity for this period with data in send buffer) in seconds, default is 180
int sent_data()
Returns the amount of data sent.
mapping(string:string|array(string)) Protocols.HTTP.Server.Request.variables
all variables included as part of a GET or POST request.
A very simple SSL server. Binds a port and calls a callback with
request_program objects.
Protocols.HTTP.Server.SSLPort Protocols.HTTP.Server.SSLPort(function(Request:void) callback, void|int port, void|string interface, void|string|Crypto.Sign.State key, void|string|array(string) certificate, void|int share)
Create a HTTPS (HTTP over SSL) server.
callbackThe function run when a request is received.
takes one argument of type Request.
portThe port number to bind to, defaults to 443.
interfaceThe interface address to bind to.
keyAn optional SSL secret key, provided in binary format, such
as that created by Standards.PKCS.RSA.private_key().
certificateAn optional SSL certificate or chain of certificates with the host certificate first, provided in binary format.
shareIf true, the connection will be shared if possible. See
Stdio.Port.bind for more information
inherit SSL.Port : Port
protected void new_connection()
The port accept callback
object|function(:void)|program Protocols.HTTP.Server.SSLPort.request_program
__deprecated__ void set_certificate(string|array(string) certificate)
Replaced by add_cert.
__deprecated__ void set_key(string skey)
Replaced by add_cert.
Secure Socket Layer (SSL) version 3.0 and Transport Layer Security (TLS) versions 1.0 - 1.2.
RFC 2246 (TLS 1.0): "The primary goal of the TLS Protocol is to provide privacy and data integrity between two communicating applications."
The classes that typical users need to use are
File
This is an object that attempts to behave as a Stdio.File
as much as possible.
Port
This is an object that attempts to behave as a Stdio.Port
as much as possible, with Port()->accept() returning
File objects.
Context
The configurated context for the File.
Constants.CertificatePair
A class for keeping track of certificate chains and their private keys.
The Constants module also contains lots of constants that are
used by the various APIs, as well as functions for formatting
the constants for output.
File, Port, Context, Constants.CertificatePair,
Constants
Alert packet.
SSL.Alert SSL.Alert(int(1..2) level, int(8bit) description, ProtocolVersion version, string|void message)
inherit .Packet : Packet
Based on the base Packet.
Client-side connection state.
array(int) SSL.ClientConnection.client_cert_types
array(string(8bit)) SSL.ClientConnection.client_cert_distinguished_names
A few storage variables for client certificate handling on the client side.
Packet client_hello(string(8bit)|void server_name)
SSL.ClientConnection SSL.ClientConnection(Context ctx, string(8bit)|void server_name, Session|void session)
Initialize a new ClientConnection.
ctxContext to use.
server_nameOptional host name of the server.
sessionOptional Session to resume.
int(-1..1) handle_handshake(int type, string(8bit) data, string(8bit) raw)
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 handshake is in progress, 1 if handshake is finished, and -1 if a fatal error occurred. It uses the send_packet() function to transmit packets.
inherit Connection : Connection
void send_renegotiate()
Renegotiate the connection (client initiated).
Sends a client_hello to force a new round of handshaking.
SSL.Connection keeps the state relevant for a single SSL connection.
This includes the Context object (which doesn't change), various
buffers, the Session object (reused or created as appropriate),
and pending read and write states being negotiated.
Each connection will have two sets of read and write States: 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.
This object is also responsible for managing incoming and outgoing packets. Outgoing packets are stored in queue objects and sent in priority order.
This class should never be created directly, instead one of the
classes that inherits it should be used (ie either
ClientConnection or ServerConnection) depending on whether
this is to be a client-side or server-side connection. These in
turn are typically created by File()->create().
ClientConnection, ServerConnection, Context,
Session, File, State
string(8bit) SSL.Connection.application_protocol
Selected ALPN (RFC 7301) protocol (if any).
Note that this is a connection property, and needs to be renegotiated on session resumption.
string(8bit) SSL.Connection.client_random
string(8bit) SSL.Connection.server_random
Random cookies, sent and received with the hello-messages.
SSL.Connection SSL.Connection(Context ctx)
Initialize the connection state.
ctxThe context for the connection.
string describe_state()
Returns a string describing the current connection state.
string(8bit)|int got_data(string(8bit) data)
Main receive handler.
dataString of data received from the peer.
Returns one of:
| Returns an empty string if there's neither application data nor errors (eg during the initial handshake). |
| Returns a string of received application data. |
| Returns |
| Returns These are the main cases of errors:
|
This function is intended to be called from an i/o read callback.
int(-1..1) handle_alert(int level, int description)
Handle an alert received from the peer.
levelAlert level; either ALERT_warning or ALERT_fatal.
descriptionAlert description code; one of
indices(SSL.Constants.ALERT_descriptions).
| Returns |
| Returns |
| Returns |
int(-1..1) handle_handshake(int type, string(8bit) data, string(8bit) raw)
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 handshake is in progress, 1 if handshake is finished, and -1 if a fatal error occurred. It uses the send_packet() function to transmit packets.
.Cipher.KeyExchange SSL.Connection.ke
The active Cipher.KeyExchange (if any).
int query_write_queue_size()
Returns the number of packets queued for writing.
Returns the number of times to_write() can be called before
it stops returning non-empty strings.
protected Packet recv_packet(string(8bit) data)
Low-level receive handler. Returns a packet, an alert, or zero if more data is needed to get a complete packet.
void send_close()
Initiate close.
void send_packet(Packet packet, int|void priority)
Queues a packet for write. Handshake and and change cipher must use the same priority, so must application data and close_notifies.
void send_renegotiate()
Renegotiate the connection.
int send_streaming_data(string(8bit) data)
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.
int SSL.Connection.sent
Number of application data bytes sent by us.
void set_alert_callback(function(object, int|object, string:void) callback)
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.
ConnectionState SSL.Connection.state
Bitfield with the current connection state.
string|int to_write()
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.
query_write_queue_size(), send_streaming_data().
Keeps the state that is shared by all SSL-connections on a client, or for one port on a server. It includes policy configuration, the server or client certificate(s), the corresponding private key(s), etc. It also includes the session cache.
The defaults are usually suitable for a client, but for a server some configuration is necessary.
Typical use is to:
Call add_cert() with the certificates belonging to the server
or client. Note that clients often don't have or need any
certificates, and also that certificate-less server operation is
possible, albeit discouraged and not enabled by default.
Suitable self-signed certificates can be created with
Standards.X509.make_selfsigned_certificate().
Optionally call get_suites() to get a set of cipher_suites
to assign to preferred_suites. This is only needed if the
default set of suites from get_suites(128, 1) isn't
satisfactory.
The initialized Context object is then passed to
File()->create() or used as is embedded in Port.
File, Port, Standards.X509
void add_cert(Crypto.Sign.State key, array(string(8bit)) certs, array(string(8bit))|void extra_name_globs)
variant void add_cert(string(8bit) key, array(string(8bit)) certs, array(string(8bit))|void extra_name_globs)
variant void add_cert(CertificatePair cp)
Add a certificate.
This function is used on both servers and clients to add
a key and chain of certificates to the set of certificate
candidates to use in find_cert().
On a server these are used in the normal initial handshake, while on a client they are only used if a server requests client certificate authentication.
keyPrivate key matching the first certificate in certs.
Supported key types are currently:
| Rivest-Shamir-Adelman. |
| Digital Signing Algorithm. |
| Elliptic Curve Digital Signing Algorithm. |
This key MUST match the public key in the first certificate
in certs.
certsA chain of X509.v1 or X509.v3 certificates, with the local certificate first and root-most certificate last.
extra_name_globsFurther SNI globs (than the ones in the first certificate), that
this certificate should be selected for. Typically used to set
the default certificate(s) by specifying ({ "*" }).
The SNI globs are only relevant for server-side certificates.
cpAn alternative is to send an initialized CertificatePair.
The function performs various validations of the key
and certs, and throws errors if the validation fails.
find_cert()
array(string(8bit)) SSL.Context.advertised_protocols
List of advertised protocols using using TLS application level protocol negotiation.
Alert alert_factory(SSL.Connection con, int level, int description, ProtocolVersion version, string|void message, mixed|void trace)
Alert factory.
This function may be overloaded to eg obtain logging of generated alerts.
conConnection which caused the alert.
levelLevel of alert.
descriptionDescription code for the alert.
messageOptional log message for the alert.
Not all alerts are fatal, and some (eg ALERT_close_notify) are used
during normal operation.
int SSL.Context.auth_level
Policy for client authentication. One of
SSL.Constants.AUTHLEVEL_none, SSL.Constants.AUTHLEVEL_ask
and SSL.Constants.AUTHLEVEL_require.
__deprecated__ array(string(8bit)) SSL.Context.certificates
Getting
The server's certificate, or a chain of X509.v3 certificates, with the server's certificate first and root certificate last.
Compatibility, don't use.
Replaced by find_cert.
`rsa, find_cert()
Setting
The server's certificate, or a chain of X509.v3 certificates, with the server's certificate first and root certificate last.
Compatibility, don't use.
Replaced by find_cert.
`rsa, find_cert()
__deprecated__ array(array(string(8bit))) SSL.Context.client_certificates
Getting
The client's certificate, or a chain of X509.v3 certificates, with the client's certificate first and root certificate last.
Compatibility, don't use.
Replaced by find_cert.
`rsa, find_cert()
Setting
The client's certificate, or a chain of X509.v3 certificates, with the client's certificate first and root certificate last.
Compatibility, don't use.
Replaced by find_cert.
`rsa, find_cert()
__deprecated__ Crypto.RSA.State SSL.Context.client_rsa
Getting
The clients RSA private key.
Compatibility, don't use.
Replaced by find_cert.
`certificates, find_cert()
Setting
The clients RSA private key.
Compatibility, don't use.
Replaced by find_cert.
`certificates, find_cert()
void configure_suite_b(int(128..)|void min_keylength, int(0..)|void strictness_level)
Configure the context for Suite B compliant operation.
This restricts the context to the cipher suites specified by RFC 6460 in strict mode.
Additional suites may be enabled, but they will only be selected if a Suite B suite isn't available.
min_keylengthMinimum supported key length in bits. Either 128
or 192.
strictness_levelAllow additional suites.
| Strict mode. Allow only the Suite B suites from RFC 6460 and TLS 1.2. |
| Transitional mode. Also allow the transitional suites from RFC 5430 for use with TLS 1.0 and 1.1. |
| Permissive mode (default). Also allow other suites that conform to the minimum key length. |
This function is only present when Suite B compliant operation is possible (ie both elliptic curves and GCM are available).
Note also that for Suite B server operation compliant certificates
need to be added with add_cert().
get_suites()
Session decode_ticket(string(8bit) ticket)
Decode a session ticket and return the corresponding session if valid or zero if invalid.
The default implementation just calls lookup_session().
Override this function (and encode_ticket()) to implement
server-side state-less session resumption.
encode_ticket(), lookup_session()
array(Crypto.DH.Parameters) SSL.Context.dh_groups
Supported DH groups for DHE key exchanges, in order of preference. Defaults to FFDHE-2048.
__deprecated__ void dhe_dss_mode(int(0..)|void min_keylength)
Set preferred_suites to DSS based methods.
min_keylengthMinimum acceptable key length in bits.
rsa_mode(), filter_weak_suites()
Replaced by get_suites.
__deprecated__ Crypto.DSA.State SSL.Context.dsa
Getting
Compatibility.
Replaced by find_cert.
Setting
Compatibility.
Replaced by find_cert.
array(int) SSL.Context.ecc_curves
Supported elliptical curve cipher curves in order of preference.
array(string(8bit)|int) encode_ticket(Session session)
Generate a session ticket for a session.
The default implementation just generates a random ticket
and calls record_session() to store it.
Over-ride this function (and decode_ticket()) to implement
server-side state-less session resumption.
| Array | |
| Non-empty string with the ticket. |
| Lifetime hint for the ticket. |
If the context signals that it does offer tickets via
offers_tickets(), this function must offer an encoded ticket
for the session as the connection may have signalled to the client
that a ticket will be offered. However, tickets are not guaranteed
to be actually usable, so if you cannot offer a ticket when you must,
"INVALID" might be an option...
decode_ticket(), record_session(), RFC 4507 section 3.3
int SSL.Context.encrypt_then_mac
Attempt to enable encrypt-then-mac mode.
void filter_weak_suites(int min_keylength)
Filter cipher suites from preferred_suites that don't have a
key with an effective length of at least min_keylength bits.
array(CertificatePair) find_cert_domain(string(8bit) domain)
Look up a suitable set of certificates for the specified domain.
UNDEFINED if no certificate was found.
array(CertificatePair) find_cert_issuer(array(string) ders)
Look up a suitable set of certificates for the specified issuer.
UNDEFIEND if no certificate was found.
array(string) get_authorities()
Get the list of allowed authorities. See set_authorities.
array(CertificatePair) get_certificates()
Returns a list of all server certificates added with add_cert.
array(array(int)) get_signature_algorithms(array(array(int))|void signature_algorithms)
Get the (filtered) set of locally supported signature algorithms.
signature_algorithms
array(int) get_suites(int(-1..)|void min_keylength, int(0..2)|void ke_flags, multiset(int)|void blacklisted_ciphers, multiset(KeyExchangeType)|void blacklisted_kes, multiset(HashAlgorithm)|void blacklisted_hashes, multiset(CipherModes)|void blacklisted_ciphermodes)
Get the prioritized list of supported cipher suites that satisfy the requirements.
min_keylengthMinimum supported effective keylength in bits. Defaults to 128.
Specify -1 to enable null ciphers.
ke_modeLevel of protection for the key exchange.
| Require forward secrecy (ephemeral keys). |
| Also allow certificate based key exchanges. |
| Allow anonymous server key exchange. Note that this allows for man in the middle attacks. |
blacklisted_ciphersMultiset of ciphers that are NOT to be used.
blacklisted_kesMultiset of key exchange methods that are NOT to be used.
blacklisted_hashesMultiset of hash algoriths that are NOT to be used.
blacklisted_ciphermodesMultiset of cipher modes that are NOT to be used.
Note that the effective keylength may differ from the actual keylength for old ciphers where there are known attacks.
array(array(string)) get_trusted_issuers()
Get the list of trusted issuers. See set_trusted_issuers.
bool SSL.Context.heartbleed_probe
If set, the other peer will be probed for the heartbleed bug during handshake. If heartbleed is found the connection is closed with insufficient security fatal error.
Crypto.RSA.State SSL.Context.long_rsa
Crypto.RSA.State SSL.Context.short_rsa
Temporary, non-certified, private keys, used for RSA key exchange in export mode. They are used as follows:
short_rsa is a 512-bit RSA key used for the SSL 3.0 and TLS 1.0
export cipher suites.
long_rsa is a 1024-bit RSA key to be used for the RSA_EXPORT1024
suites from draft-ietf-tls-56-bit-ciphersuites-01.txt.
They have associated counters short_rsa_counter and long_rsa_counter,
which are decremented each time the keys are used.
When the counters reach zero, the corresponding RSA key is cleared, and a new generated on demand at which time the counter is reset.
int SSL.Context.long_rsa_counter
int SSL.Context.short_rsa_counter
Counters for export RSA keys.
Session lookup_session(string id)
Lookup a session identifier in the cache. Returns the corresponding session, or zero if it is not found or caching is disabled.
int SSL.Context.max_sessions
Maximum number of sessions to keep in the cache.
ProtocolVersion SSL.Context.max_version
The maximum supported protocol version.
Defaults to PROTOCOL_TLS_MAX.
This value should not be less than min_version.
ProtocolVersion SSL.Context.min_version
The minimum supported protocol version.
Defaults to PROTOCOL_TLS_1_0.
This value should not be greater than max_version.
Session new_session()
Create a new session.
bool offers_tickets()
Signals if the context will offer a session ticket via
encode_ticket().
int SSL.Context.packet_max_size
The maximum amount of data that is sent in each SSL packet by
File. A value between 1 and Constants.PACKET_MAX_SIZE.
array(int) SSL.Context.preferred_auth_methods
For client authentication. Used only if auth_level is AUTH_ask or AUTH_require.
array(int) SSL.Context.preferred_compressors
Lists the supported compression algorithms in order of preference.
Defaults to ({ COMPRESSION_null }) due to SSL attacks that
target compression.
array(int) SSL.Context.preferred_suites
Cipher suites we want to support, in order of preference, best first.
void purge_session(Session s)
Invalidate a session for resumption and remove it from the cache.
function(int(0..):string(8bit)) SSL.Context.random
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. By
default set to Crypto.Random.random_string.
void record_session(Session s)
Add a session to the cache (if caching is enabled).
int SSL.Context.require_trust
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.
__deprecated__ Crypto.RSA.State SSL.Context.rsa
Getting
The servers default private RSA key.
Compatibility, don't use.
Replaced by find_cert.
`certificates, find_cert()
Setting
The servers default private RSA key.
Compatibility, don't use.
Replaced by find_cert.
`certificates, find_cert()
__deprecated__ void rsa_mode(int(0..)|void min_keylength)
Set preferred_suites to RSA based methods.
min_keylengthMinimum acceptable key length in bits.
dhe_dss_mode(), filter_weak_suites()
Replaced by get_suites.
int SSL.Context.session_lifetime
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.
void set_authorities(array(string) a)
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 Standards.PEM.Messages 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.
void set_trusted_issuers(array(array(string)) i)
Sets the list of trusted certificate issuers.
aAn 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
Standards.PEM.Messages 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.
array(array(int)) SSL.Context.signature_algorithms
The set of <hash, signature> combinations to use by us.
Only used with TLS 1.2 and later.
Defaults to all combinations supported by Pike except for MD5.
This list is typically filtered by get_signature_algorithms()
to get rid of combinations not supported by the runtime.
According to RFC 5246 7.4.2 all certificates needs to be signed by any of the supported signature algorithms. To be forward compatible this list needs to be limited to the combinations that have existing PKCS identifiers.
get_signature_algorithms()
array(int) sort_suites(array(int) suites)
Sort a set of cipher suites according to our preferences.
Returns the array sorted with the most preferrable (aka "best") cipher suite first.
The original array (suites) is modified destructively,
but is not the same array as the result.
int SSL.Context.use_cache
Non-zero to enable caching of sessions
mapping(Standards.ASN1.Types.Identifier:Crypto.Hash) SSL.Context.verifier_algorithms
Mapping of supported verifier algorithms to hash implementation.
Standards.X509.get_algorithms()
int SSL.Context.verify_certificates
Determines whether certificates presented by the peer are verified, or just accepted as being valid.
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 may each do both reading and writing. In callback mode that means that installing either a read or a write callback may install both internally.
In Pike 8.0 and later, blocking read and write in concurrent threads is supported.
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.
bool accept(string|void pending_data)
Configure as server and set up the connection.
pending_dataAny data that has already been read from the stream. This is typically used with protocols that use START TLS or similar, where there's a risk that "too much" data (ie part of the TLS ClientHello) has been read from the stream before deciding that the connection is to enter TLS-mode.
Returns 0 on handshaking failure in blocking mode,
and otherwise 1.
connect()
string SSL.File.application_protocol
The application protocol chosen by the client during application layer protocol negotiation (ALPN).
Read only
protected int(0..0)|float backend_once(int|void nonwaiting_mode)
Run one pass of the backend.
int close(void|string how, void|int clean_close, void|int dont_throw)
Close the connection. Both the read and write ends are always closed
howThis argument is only for Stdio.File compatibility
and must be either "rw" or 0.
clean_closeIf 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.
dont_throwI/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.
If a clean close is requested in nonblocking mode then the stream
is most likely not closed right away, and the backend is then
still needed for a while afterwards to exchange the close packets.
is_open returns 2 in that time window.
I/O errors from both reading and writing might occur in blocking mode.
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.
shutdown
SSL.Session connect(string|void dest_addr, SSL.Session|void session)
Configure as client and set up the connection.
dest_addrOptional name of the server that we are connected to.
sessionSession to resume (if any).
Returns 0 on handshaking failure in blocking mode,
and otherwise the Session object for the connection.
Throws an error if a connection already has been established.
accept()
SSL.File SSL.File(Stdio.File stream, SSL.Context ctx)
Create an SSL connection over an open stream.
streamOpen socket or pipe to create the connection over.
ctxThe SSL context.
The backend used by stream is taken over and restored after the
connection is closed (see close and shutdown). The callbacks
and id in stream are overwritten.
The operation mode defaults to nonblocking mode.
accept(), connect()
protected void destroy()
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.
close
int errno()
Returns the current error number for the connection. Notable values are:
| No error |
| Connection closed by other end. |
protected int SSL.File.fragment_max_size
The max amount of data to send in each packet. Initialized from the context when the object is created.
mapping get_peer_certificate_info()
Returns peer certificate information, if any.
array get_peer_certificates()
Returns the peer certificate chain, if any.
protected void internal_poll()
Check whether any callbacks may need to be called.
Always run via the real_backend.
schedule_poll()
int is_open()
Returns 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.
If a clean close has been requested in nonblocking mode, then 2 is returned until the close packet exchanged has been completed.
In Pike 7.8 and earlier, this function returned zero in the case above where it now returns 2.
bool linger(int(-1..65535)|void seconds)
Set the linger time on close().
function(void|object, void|mixed:int) query_accept_callback()
Returns the current accept callback.
set_accept_callback
string query_address(int|void arg)
Returns the address and port of the connection.
See Stdio.File.query_address for details.
Stdio.File.query_address
function(object, int|object, string:void) query_alert_callback()
Returns the current alert callback.
set_alert_callback
string(8bit) query_application_protocol()
Returns the negotiated application level protocol (ALPN)
if any, and otherwise 0 (zero).
Context.advertised_protocols
Pike.Backend query_backend()
Return the backend used for the file callbacks.
set_backend
array(Stdio.Buffer|int(0..0)) query_buffer_mode()
Get the active input and output buffers that have been
set with set_buffer_mode() (if any).
Returns an array with two elements:
| Array | |
| The current input buffer. |
| The current output buffer. |
set_buffer_mode()
array(function(mixed, void|string:int)) query_callbacks()
Returns the currently set callbacks in the same order
as the arguments to set_callbacks.
set_callbacks, set_nonblocking
function(void|mixed:int) query_close_callback()
Returns the current close callback.
set_close_callback, set_nonblocking, query_callbacks
.Connection query_connection()
Return the SSL connection object.
This returns the low-level SSL.connection object.
SSL.Context query_context()
Return the SSL context object.
int query_fd()
Returns the file descriptor number associated with this object.
mixed query_id()
Returns the currently set id.
set_id
Stdio.read_callback_t query_read_callback()
Returns the current read callback.
set_read_callback, set_nonblocking, query_callbacks
Stdio.File query_stream()
Return the underlying stream.
Avoid any temptation to do
destruct(file_obj->query_stream()). That almost certainly
creates more problems than it solves.
You probably want to use shutdown.
shutdown
int query_suite()
Return the currently active cipher suite.
int(0..0)|float query_timeout()
Get the timeout for blocking operations.
set_timeout()
ProtocolVersion query_version()
Return the currently active SSL/TLS version.
Stdio.write_callback_t query_write_callback()
Returns the current write callback.
set_write_callback, set_nonblocking, query_callbacks
string read(void|int length, void|bool not_all)
Read some (decrypted) data from the connection. Works like
Stdio.File.read.
I/O errors from both reading and writing might occur in blocking mode.
write
int renegotiate()
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.
The read buffer is not cleared - a read() afterwards will
return data from both before and after the renegotiation.
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.
protected void schedule_poll()
Schedule calling of any relevant callbacks the next
time the real_backend is run.
internal_poll()
void set_accept_callback(function(void|object, void|mixed:int) accept)
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 File object and the
additional id arguments (set with set_id).
Like the read, write and close callbacks, installing this callback implies callback mode, even after the handshake is done.
set_nonblocking, set_callbacks,
query_accept_callback, query_callbacks
void set_alert_callback(function(object, int|object, string:void) alert)
Install a function that will be called when an alert packet is about
to be sent. It doesn't affect the callback mode - it's called both
from backends and from within normal function calls like read
and write.
This callback can be used to implement fallback to other protocols
when used on the server side together with shutdown().
This object is part of a cyclic reference whenever this is set, just like setting any other callback.
This callback is not cleared by set_blocking, or settable
by set_callbacks or set_nonblocking. It is also not
part of the set returned by query_callbacks.
query_alert_callback
void set_backend(Pike.Backend backend)
Set the backend used for the file callbacks.
query_backend
void set_blocking()
Set the stream in blocking mode. All but the alert callback are zapped.
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.
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.
Prior to version 7.5.12, this function didn't clear the accept callback.
set_nonblocking, set_blocking_keep_callbacks,
set_nonblocking_keep_callbacks
void set_blocking_keep_callbacks()
Set blocking mode like set_blocking, but don't alter any
callbacks.
set_blocking, set_nonblocking
void set_buffer_mode(Stdio.Buffer|int(0..0) in, Stdio.Buffer|int(0..0) out)
Toggle the file to Buffer mode.
In this mode reading and writing will be done via Buffer objects, in the directions you included buffers.
inInput buffer. If this buffer is non-empty, its contents will be returned after any already received data.
outOutput buffer. If this buffer is non-empty, its contents will be sent after any data already queued for sending.
query_buffer_mode()
void set_callbacks(void|Stdio.read_callback_t read, void|Stdio.write_callback_t write, void|function(mixed:int) close, void|function(mixed, string:int) read_oob, void|function(mixed:int) write_oob, void|function(void|mixed:int) accept)
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.
read_oob and write_oob are currently ignored.
set_read_callback, set_write_callback,
set_close_callback, set_accept_callback, query_callbacks
void set_close_callback(function(void|mixed:int) close)
Install a function to be called when the connection is closed,
either normally or due to an error (use errno to retrieve it).
query_close_callback, set_nonblocking, query_callbacks
void set_id(mixed id)
Set the value to be sent as the first argument to the
callbacks installed by set_callbacks.
query_id
void set_nonblocking(void|Stdio.read_callback_t read, void|Stdio.write_callback_t 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)
Set the stream in nonblocking mode, installing the specified callbacks. The alert callback isn't touched.
Prior to version 7.5.12, this function didn't set the accept callback.
read_oob and write_oob are currently ignored.
set_callbacks, query_callbacks, set_nonblocking_keep_callbacks,
set_blocking
void set_nonblocking_keep_callbacks()
Set nonblocking mode like set_nonblocking, but don't alter any
callbacks.
set_nonblocking, set_blocking, set_blocking_keep_callbacks
void set_read_callback(Stdio.read_callback_t read)
Install a function to be called when data is available.
query_read_callback, set_nonblocking, query_callbacks
void set_timeout(int(0..0)|float seconds)
Set timeout for blocking operations.
secondsTime in seconds allowed for blocking operations
before triggering a timeout. Set to 0
(zero) to disable.
By default there is no timeout.
query_timeout()
void set_write_callback(Stdio.write_callback_t write)
Install a function to be called when data can be written.
query_write_callback, set_nonblocking, query_callbacks
Stdio.File shutdown()
Shut down the SSL connection without sending any more packets.
If the connection is open then the underlying (still open) stream is returned.
If a nonclean (i.e. normal) close has been requested then the underlying stream is closed now if it wasn't closed already, and zero is returned.
If a clean close has been requested (see the second argument to
close) then the behavior depends on the state of the close
packet exchange: The first shutdown call after a successful
exchange returns the (still open) underlying stream, and later
calls return zero and clears errno. If the exchange hasn't
finished then the stream is closed, zero is returned, and errno
will return System.EPIPE.
close, set_alert_callback
int write(string|array(string) data, mixed ... args)
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.
This function returns zero if attempts are made to write data during the handshake phase and the mode is nonblocking.
I/O errors from both reading and writing might occur in blocking mode.
read
SSL Record Layer. Handle formatting and parsing of packets.
SSL.Packet SSL.Packet(ProtocolVersion version, void|int extra)
versionThe version sent packets will be created for.
extraAdditional fragment size, over the 2^14 bytes for a plaintext TLS fragment.
string(8bit)|.Packet recv(string(8bit) data)
Receive data read from the network.
dataRaw data from the network.
Returns a string of leftover data if packet is complete,
otherwise 0.
If there's an error, an alert object is returned.
string send()
Serialize the packet for sending.
Returns the serialized packet.
Interface similar to Stdio.Port.
File accept()
Get the next pending File from the accept_queue.
Returns the next pending File if any, and 0 (zero) if
there are none.
function(object, mixed|void:void) SSL.Port.accept_callback
int bind(int port, function(SSL.File|void, mixed|void:int) callback, string|void ip, int|void share)
Bind an SSL port.
portPort number to bind.
callbackCallback to call when the SSL connection has been negotiated.
The callback is called with an File as the first argument,
and the id for the File as the second.
If the callback is 0 (zero), then negotiated Files
will be enqueued for later retrieval with accept().
ipOptional IP-number to bind.
shareIf true, share the port with other processes
Returns 1 if binding of the port succeeded,
and 0 (zero) on failure.
Stdio.Port()->bind(), File()->set_accept_callback(),
listen_fd()
SSL.Port SSL.Port(Context|void ctx)
Create a new port for accepting SSL connections.
bind(), listen_fd()
Context SSL.Port.ctx
Context to use for the connections.
void finished_callback(SSL.File f, mixed|void id)
SSL connection accept callback.
fThe File that just finished negotiation.
This function is installed as the File accept callback by
ssl_callback(), and enqueues the newly negotiated File on
the accept queue.
If there has been an accept_callback installed by bind() or
listen_fd(), it will be called with all pending Files on the
accept queue.
If there's no accept_callback, then the File will have to be
retrieved from the queue by calling accept().
inherit Stdio.Port : socket
int listen_fd(int fd, function(File|void, mixed|void:int) callback)
Set up listening for SSL connections on an already opened fd.
fdFile descriptor to listen on.
callbackCallback to call when the SSL connection has been negotiated.
The callback is called with an File as the first argument,
and the id for the File as the second.
If the callback is 0 (zero), then negotiated Files
will be enqueued for later retrieval with accept().
Returns 1 if listening on the fd succeeded,
and 0 (zero) on failure.
Stdio.Port()->listen_fd(), File()->set_accept_callback(),
bind()
Stdio.File socket_accept()
Low-level accept.
Stdio.Port()->accept()
void ssl_callback(mixed id)
Connection accept callback.
This function is installed as the Stdio.Port callback, and
accepts the connection and creates a corresponding File with
finished_callback() as the accept callback.
bind(), finished_callback()
Server-side connection state.
int(-1..1) handle_handshake(int type, string(8bit) data, string(8bit) raw)
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 handshake is in progress, 1 if handshake is finished, and -1 if a fatal error occurred. It uses the send_packet() function to transmit packets.
inherit Connection : Connection
void send_renegotiate()
Renegotiate the connection (server initiated).
Sends a hello_request to force a new round of handshaking.
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.
mapping SSL.Session.cert_data
Information about the certificate in use by the peer, such as issuing authority, and verification status.
array(string(8bit)) SSL.Session.certificate_chain
our certificate chain
Cipher.CipherSpec SSL.Session.cipher_spec
Information about the encryption method derived from the cipher_suite.
int SSL.Session.cipher_suite
Constant defining a choice of keyexchange, encryption and mac algorithm.
int SSL.Session.compression_algorithm
Always COMPRESSION_null.
Crypto.ECC.Curve SSL.Session.curve
The ECC curve selected by the key exchange.
| The curve from the server certificate. |
| |
| The curve selected for the ECDHE key exchange (typically the largest curve supported by both the client and the server). |
| |
|
array(int) SSL.Session.ecc_curves
Supported elliptical curve cipher curves in order of preference.
int SSL.Session.ecc_point_format
The selected elliptical curve point format.
May be -1 to indicate that there's no supported overlap
between the server and client.
int SSL.Session.encrypt_then_mac
Negotiated encrypt-then-mac mode.
array(string(8bit)) generate_keys(string(8bit) client_random, string(8bit) server_random, ProtocolVersion version)
Generates keys appropriate for the SSL version given in version,
based on the client_random and server_random.
| Array | |
| Client write MAC secret |
| Server write MAC secret |
| Client write key |
| Server write key |
| Client write IV |
| Server write IV |
bool has_required_certificates()
Indicates if this session has the required server certificate keys set. No means that no or the wrong type of certificate was sent from the server.
HeartBeatModeType SSL.Session.heartbeat_mode
Heartbeat mode.
string(8bit) SSL.Session.identity
Identifies the session to the server
protected bool is_supported_cert(CertificatePair cp, int ke_mask, int h_max, ProtocolVersion version, array(int) ecc_curves)
Used to filter certificates not supported by the peer.
cpCandidate CertificatePair.
versionNegotiated version of SSL.
ecc_curvesThe set of ecc_curves supported by the peer.
bool is_supported_suite(int suite, int ke_mask, ProtocolVersion version)
Used to filter the set of cipher suites suggested by the peer based on our available certificates.
suiteCandidate cipher suite.
ke_maskThe bit mask of the key exchange algorithms supported by the set of available certificates.
versionThe negotiated version of SSL/TLS.
string(8bit) SSL.Session.master_secret
48 byte secret shared between the client and the server. Used for deriving the actual keys.
int SSL.Session.max_packet_size
The max fragment size requested by the client.
array(State) new_client_states(.Connection con, string(8bit) client_random, string(8bit) server_random, ProtocolVersion version)
Computes a new set of encryption states, derived from the client_random, server_random and master_secret strings.
| Array | |
| Read state |
| Write state |
array(State) new_server_states(.Connection con, string(8bit) client_random, string(8bit) server_random, ProtocolVersion version)
Computes a new set of encryption states, derived from the client_random, server_random and master_secret strings.
| Array | |
| Read state |
| Write state |
array(string(8bit)) SSL.Session.peer_certificate_chain
the peer certificate chain
Crypto.Sign.State SSL.Session.peer_public_key
The peer's public key (from the certificate).
Crypto.Sign.State SSL.Session.private_key
Our private key.
bool reusable_as(Session other)
Returns true if this session object can be used in place of the
session object other.
int select_cipher_suite(array(CertificatePair) certs, array(int) cipher_suites, ProtocolVersion version)
Selects an apropriate certificate, authentication method and cipher suite for the parameters provided by the client.
certsThe list of CertificatePairs that are applicable to the
server_name of this session.
client_suitesThe set of cipher suites that the client claims to support.
versionThe SSL protocol version to use.
Typical client extensions that also are used:
signature_algorithms
The set of signature algorithm tuples that the client claims to support.
string(8bit) SSL.Session.server_name
RFC 6066 3.1 (SNI)
int set_cipher_suite(int suite, ProtocolVersion version, array(array(int)) signature_algorithms, int max_hash_size)
Sets the proper authentication method and cipher specification for the given parameters.
suiteThe cipher suite to use, selected from the set that the client claims to support.
versionThe SSL protocol version to use.
signature_algorithmsThe set of signature algorithms tuples that the client claims to support.
max_hash_sizevoid set_compression_method(int compr)
Sets the compression method. Currently only COMPRESSION_null
and COMPRESSION_deflate are supported.
array(array(int)) SSL.Session.signature_algorithms
The set of <hash, signature> combinations supported by the peer.
Only used with TLS 1.2 and later.
Defaults to the settings from RFC 5246 7.4.1.4.1.
string(8bit) SSL.Session.ticket
Alternative identification of the session to the server.
int SSL.Session.ticket_expiry_time
Expiry time for ticket.
bool SSL.Session.truncated_hmac
Indicates that the packet HMACs should be truncated to the first 10 bytes (80 bits). Cf RFC 3546 3.5.
ProtocolVersion SSL.Session.version
Negotiated protocol version.
The state object handles a one-way stream of packets, and operates in either decryption or encryption mode. A connection switches from one set of state objects to another, one or more times during its lifetime.
Cipher.CipherAlgorithm SSL.State.crypt
Encryption or decryption object.
Alert|Packet decrypt_packet(Packet packet)
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.
Alert|Packet encrypt_packet(Packet packet)
Encrypts a packet (including deflating and MAC-generation).
Cipher.MACAlgorithm SSL.State.mac
Message Authentication Code
string SSL.State.salt
TLS 1.2 IV salt. This is used as a prefix for the IV for the AEAD cipher algorithms.
int SSL.State.seq_num
64-bit sequence number.
Session SSL.State.session
Information about the used algorithms.
int SSL.State.tls_iv
TLS IV prefix length.
Dummy HTTPS server/client
Encryption and MAC algorithms used in SSL.
protected string(8bit) P_hash(Crypto.Hash hashfn, string(8bit) secret, string(8bit) seed, int len)
Hashfn is either a Crypto.MD5, Crypto.SHA or Crypto.SHA256.
CipherSpec lookup(int suite, ProtocolVersion|int version, array(array(int)) signature_algorithms, int max_hash_size)
Lookup the crypto parameters for a cipher suite.
suiteCipher suite to lookup.
versionVersion of the SSL/TLS protocol to support.
signature_algorithmsThe set of <hash, signature> combinations that are supported by the other end.
max_hash_sizeThe maximum hash size supported for the signature algorithm.
Returns 0 (zero) for unsupported combinations, otherwise
returns an initialized CipherSpec for the suite.
string(8bit) prf_sha384(string(8bit) secret, string(8bit) label, string(8bit) seed, int len)
This Pseudo Random Function is used to derive secret keys for some ciphers suites defined after TLS 1.2.
string(8bit) prf_sha512(string(8bit) secret, string(8bit) label, string(8bit) seed, int len)
This Pseudo Random Function could be used to derive secret keys for some ciphers suites defined after TLS 1.2.
string(8bit) prf_ssl_3_0(string(8bit) secret, string(8bit) label, string(8bit) seed, int len)
This Pseudo Random Function is used to derive secret keys in SSL 3.0.
The argument label is ignored.
string(8bit) prf_tls_1_0(string(8bit) secret, string(8bit) label, string(8bit) seed, int len)
This Pseudo Random Function is used to derive secret keys in TLS 1.0 and 1.1.
string(8bit) prf_tls_1_2(string(8bit) secret, string(8bit) label, string(8bit) seed, int len)
This Pseudo Random Function is used to derive secret keys in TLS 1.2.
Cipher algorithm interface.
int(0..) block_size()
Return the block size for this crypto.
this_program set_encrypt_key(string)
this_program set_decrypt_key(string)
Set the key used for encryption/decryption, and enter encryption mode.
Cipher specification.
program SSL.Cipher.CipherSpec.bulk_cipher_algorithm
The algorithm to use for the bulk of the transfered data.
int SSL.Cipher.CipherSpec.explicit_iv_size
The number of bytes of explicit data needed for initialization vectors.
This is used by AEAD ciphers, where there's a secret part of the iv
"salt" of length iv_size, and an explicit part that is sent in
the clear.
This is usually bulk_cipher_algorithm->iv_size() - iv_size,
but may be set to zero to just have the sequence number expanded
to the same size as an implicit iv. This is used by the suites
with Crypto.ChaCha20.POLY1305.
Crypto.Hash SSL.Cipher.CipherSpec.hash
The hash algorithm for signing the handshake.
Usually the same hash as is the base for the prf.
Only used in TLS 1.2 and later.
int SSL.Cipher.CipherSpec.hash_size
The number of bytes in the MAC hashes.
int SSL.Cipher.CipherSpec.is_exportable
Indication whether the combination uses strong or weak (aka exportable) crypto.
int SSL.Cipher.CipherSpec.iv_size
The number of bytes of random data needed for initialization vectors.
program SSL.Cipher.CipherSpec.ke_factory
Key exchange factory.
int SSL.Cipher.CipherSpec.key_bits
The effective number of bits in key_material.
This is typically key_material * 8, but for eg DES
this is key_material * 7.
int SSL.Cipher.CipherSpec.key_material
The number of bytes of key material used on initialization.
program SSL.Cipher.CipherSpec.mac_algorithm
The Message Authentication Code to use for the packets.
function(string(8bit), string(8bit), string(8bit), int:string(8bit)) SSL.Cipher.CipherSpec.prf
The Pseudo Random Function to use.
prf_ssl_3_0(), prf_tls_1_0(), prf_tls_1_2()
ADT.struct sign(object session, string(8bit) cookie, ADT.struct struct)
The function used to sign packets.
SignatureAlgorithm SSL.Cipher.CipherSpec.signature_alg
The signature algorithm used for key exchange signatures.
HashAlgorithm SSL.Cipher.CipherSpec.signature_hash
The hash algorithm used for key exchange signatures.
bool verify(object session, string cookie, ADT.struct struct, ADT.struct input)
The function used to verify the signature for packets.
inherit Crypto.DES.CBC.Buffer.State : State
inherit Crypto.DES3.CBC.Buffer.State : State
Implements Diffie-Hellman key-exchange.
The following key exchange methods are implemented here:
KE_dhe_dss, KE_dhe_rsa and KE_dh_anon.
SSL.Cipher.DHKeyExchange SSL.Cipher.DHKeyExchange(Crypto.DH.Parameters p)
Crypto.DH.Parameters SSL.Cipher.DHKeyExchange.parameters
Finite field Diffie-Hellman parameters.
this_program set_other(Gmp.mpz o)
Set the value received from the peer.
Returns UNDEFINED if o is invalid for the set parameters.
Otherwise returns the current object.
KeyExchange method base class.
int SSL.Cipher.KeyExchange.anonymous
Indicates whether a certificate isn't required.
string client_key_exchange_packet(string client_random, string server_random, ProtocolVersion version)
Returns the payload for a HANDSHAKE_client_key_exchange packet.
May return 0 (zero) to generate an ALERT_unexpected_message.
object SSL.Cipher.KeyExchange.context
object SSL.Cipher.KeyExchange.session
object SSL.Cipher.KeyExchange.connection
ProtocolVersion SSL.Cipher.KeyExchange.client_version
SSL.Cipher.KeyExchange SSL.Cipher.KeyExchange(object context, object session, object connection, ProtocolVersion client_version)
string derive_master_secret(string premaster_secret, string client_random, string server_random, ProtocolVersion version)
Derive the master secret from the premaster_secret and the random seeds.
Returns the master secret.
int SSL.Cipher.KeyExchange.message_was_bad
Indicates whether the key exchange has failed due to bad MACs.
ADT.struct parse_server_key_exchange(ADT.struct input)
inputADT.struct with the content of a HANDSHAKE_server_key_exchange.
The key exchange information should be extracted from input,
so that it is positioned at the signature.
Returns a new ADT.struct with the unsigned payload of input.
string(8bit)|int(8bit) server_derive_master_secret(string(8bit) data, string(8bit) client_random, string(8bit) server_random, ProtocolVersion version)
dataPayload from a HANDSHAKE_client_key_exchange.
Master secret or alert number.
May set message_was_bad and return a fake master secret.
int server_key_exchange(ADT.struct input, string client_random, string server_random)
inputADT.struct with the content of a HANDSHAKE_server_key_exchange.
The default implementation calls parse_server_key_exchange(),
and then verifies the signature.
| Returns zero on success. |
| Returns negative on verification failure. |
string server_key_exchange_packet(string client_random, string server_random)
The default implementation calls server_key_params() to generate
the base payload.
Returns the signed payload for a HANDSHAKE_server_key_exchange.
ADT.struct server_key_params()
Returns an ADT.struct with the
HANDSHAKE_server_key_exchange payload.
Key exchange for KE_dh_dss and KE_dh_dss.
KeyExchange that uses Diffie-Hellman with a key from
a DSS certificate.
inherit KeyExchange : KeyExchange
string(8bit)|int(8bit) server_derive_master_secret(string(8bit) data, string(8bit) client_random, string(8bit) server_random, ProtocolVersion version)
Master secret or alert number.
KeyExchange for KE_dhe_rsa, KE_dhe_dss and KE_dh_anon.
KeyExchange that uses Diffie-Hellman to generate an Ephemeral key.
inherit KeyExchangeDH : KeyExchangeDH
string(8bit)|int(8bit) server_derive_master_secret(string(8bit) data, string(8bit) client_random, string(8bit) server_random, ProtocolVersion version)
Master secret or alert number.
KeyExchange for KE_ecdh_rsa and KE_ecdh_ecdsa.
NB: The only difference between the two is whether the certificate is signed with RSA or ECDSA.
This KeyExchange uses the Elliptic Curve parameters from the ECDSA certificate on the server side, and ephemeral parameters on the client side.
inherit KeyExchange : KeyExchange
string(8bit)|int(8bit) server_derive_master_secret(string(8bit) data, string(8bit) client_random, string(8bit) server_random, ProtocolVersion version)
Master secret or alert number.
KeyExchange for KE_ecdhe_rsa and KE_ecdhe_ecdsa.
KeyExchange that uses Elliptic Curve Diffie-Hellman to generate an Ephemeral key.
inherit KeyExchangeECDH : KeyExchangeECDH
string(8bit)|int(8bit) server_derive_master_secret(string(8bit) data, string(8bit) client_random, string(8bit) server_random, ProtocolVersion version)
Master secret or alert number.
Key exchange for KE_null.
This is the NULL KeyExchange, which is only used for the
SSL_null_with_null_null cipher suite, which is usually disabled.
inherit KeyExchange : KeyExchange
string(8bit) server_derive_master_secret(string(8bit) data, string(8bit) client_random, string(8bit) server_random, ProtocolVersion version)
Master secret or alert number.
Key exchange for KE_rsa.
KeyExchange that uses the Rivest Shamir Adelman algorithm.
inherit KeyExchange : KeyExchange
string(8bit)|int(8bit) server_derive_master_secret(string(8bit) data, string(8bit) client_random, string(8bit) server_random, ProtocolVersion version)
Master secret or alert number.
Message Authentication Code interface.
int block_size()
The block size of the underlying hash algorithm.
string hash(string data)
Creates a HMAC hash of the data with the underlying hash
algorithm.
constant int SSL.Cipher.MACAlgorithm.hash_header_size
The length of the header prefixed by hash().
string hash_packet(object packet, int seq_num, int|void adjust_len)
Generates a header and creates a HMAC hash for the given
packet.
packetPacket to generate a MAC hash for.
seq_numSequence number for the packet in the stream.
adjust_lenAdded to sizeof(packet) to get the packet length.
Returns the MAC hash for the packet.
string hash_raw(string data)
Creates a normal hash of the data using the underlying hash
algorithm.
HMAC using MD5.
This is the MAC algorithm used by TLS 1.0 and later.
inherit MAChmac_sha : MAChmac_sha
HMAC using SHA.
This is the MAC algorithm used by TLS 1.0 and later.
SSL.Cipher.MAChmac_sha SSL.Cipher.MAChmac_sha(string|void s)
inherit MACAlgorithm : MACAlgorithm
HMAC using SHA256.
This is the MAC algorithm used by some cipher suites in TLS 1.2 and later.
inherit MAChmac_sha : MAChmac_sha
HMAC using SHA384.
This is a MAC algorithm used by some cipher suites in TLS 1.2 and later.
inherit MAChmac_sha : MAChmac_sha
HMAC using SHA512.
This is a MAC algorithm used by some cipher suites in TLS 1.2 and later.
inherit MAChmac_sha : MAChmac_sha
MAC using MD5.
Note: This uses the algorithm from the SSL 3.0 draft.
inherit MACsha : MACsha
MAC using SHA.
Note: This uses the algorithm from the SSL 3.0 draft.
inherit MACAlgorithm : MACAlgorithm
inherit Crypto.Arctwo.CBC.Buffer.State : State
Protocol constants
constant SSL.Constants.CIPHER_effective_keylengths
Mapping from cipher algorithm to effective key length.
constant SSL.Constants.ECC_NAME_TO_CURVE
Lookup for Pike ECC name to NamedCurve.
constant SSL.Constants.HASH_lookup
Lookup from HashAlgorithm to corresponding Crypto.Hash.
constant SSL.Constants.KE_Anonymous
Lists KeyExchangeType that doesn't require certificates.
constant SSL.Constants.PROTOCOL_SSL_MAX
constant SSL.Constants.PROTOCOL_TLS_MAX
Max supported SSL version.
Certificate format types as per RFC 6091 and RFC 7250.
Cipher operation modes.
constant SSL.Constants.MODE_cbc
CBC - Cipher Block Chaining mode.
constant SSL.Constants.MODE_ccm
CCM - Counter with CBC-MAC mode.
constant SSL.Constants.MODE_ccm_8
CCM - Counter with 8 bit CBC-MAC mode.
constant SSL.Constants.MODE_gcm
GCM - Galois Cipher Mode.
constant SSL.Constants.MODE_poly1305
Poly1305 - Used only with ChaCha20.
Compression methods.
constant SSL.Constants.COMPRESSION_deflate
Deflate compression. RFC 3749
constant SSL.Constants.COMPRESSION_lzs
LZS compression. RFC 3943
constant SSL.Constants.COMPRESSION_null
No compression.
Connection states.
These are the states that a [Connection] may have.
Queueing of more application data is only
allowed in the states CONNECTION_ready and
CONNECTION_handshaking.
constant SSL.Constants.CONNECTION_closed
Closed at both ends.
constant SSL.Constants.CONNECTION_closing
Connection closing mask.
constant SSL.Constants.CONNECTION_failing
Connection failing mask.
constant SSL.Constants.CONNECTION_handshaking
Handshaking not done.
constant SSL.Constants.CONNECTION_local_closed
Local close packet sent.
constant SSL.Constants.CONNECTION_local_closing
Local close packet pending.
constant SSL.Constants.CONNECTION_local_down
Local mask.
constant SSL.Constants.CONNECTION_local_failing
Fatal alert pending.
constant SSL.Constants.CONNECTION_local_fatal
Fatal alert sent.
constant SSL.Constants.CONNECTION_peer_closed
Peer has closed the connection.
constant SSL.Constants.CONNECTION_peer_down
Peer mask.
constant SSL.Constants.CONNECTION_peer_fatal
Peer has issued a fatal alert.
constant SSL.Constants.CONNECTION_ready
Connection is ready for use.
Fragment lengths for EXTENSION_max_fragment_length.
Hash algorithms as per RFC 5246 7.4.1.4.1.
Key exchange methods.
constant SSL.Constants.KE_dh_anon
Diffie-Hellman Anonymous
constant SSL.Constants.KE_dh_dss
Diffie-Hellman cert signed with DSS
constant SSL.Constants.KE_dh_rsa
Diffie-Hellman cert signed with RSA
constant SSL.Constants.KE_dhe_dss
Diffie-Hellman Ephemeral DSS
constant SSL.Constants.KE_dhe_psk
Preshared Key with DHE
constant SSL.Constants.KE_dhe_rsa
Diffie-Hellman Ephemeral RSA
constant SSL.Constants.KE_ecdh_anon
Elliptic Curve DH Anonymous
constant SSL.Constants.KE_ecdh_ecdsa
Elliptic Curve DH cert signed with ECDSA
constant SSL.Constants.KE_ecdh_rsa
Elliptic Curve DH cert signed with RSA
constant SSL.Constants.KE_ecdhe_ecdsa
Elliptic Curve DH Ephemeral with ECDSA
constant SSL.Constants.KE_ecdhe_rsa
Elliptic Curve DH Ephemeral with RSA
constant SSL.Constants.KE_null
None.
constant SSL.Constants.KE_psk
Preshared Key
constant SSL.Constants.KE_rsa
Rivest-Shamir-Adelman
constant SSL.Constants.KE_rsa_fips
Rivest-Shamir-Adelman with FIPS keys.
constant SSL.Constants.KE_rsa_psk
Preshared Key signed with RSA
constant SSL.Constants.KE_srp_sha
Secure Remote Password (SRP)
constant SSL.Constants.KE_srp_sha_dss
SRP signed with DSS
constant SSL.Constants.KE_srp_sha_rsa
SRP signed with RSA
Constants for specifying the versions of SSL/TLS to use.
Context
constant SSL.Constants.PROTOCOL_SSL_3_0
SSL 3.0 - The original SSL3 draft version.
constant SSL.Constants.PROTOCOL_SSL_3_1
SSL 3.1 - The RFC 2246 version of SSL.
constant SSL.Constants.PROTOCOL_SSL_3_2
SSL 3.2 - The RFC 4346 version of SSL.
constant SSL.Constants.PROTOCOL_SSL_3_3
SSL 3.3 - The RFC 5246 version of SSL.
constant SSL.Constants.PROTOCOL_TLS_1_0
TLS 1.0 - The RFC 2246 version of TLS.
constant SSL.Constants.PROTOCOL_TLS_1_1
TLS 1.1 - The RFC 4346 version of TLS.
constant SSL.Constants.PROTOCOL_TLS_1_2
TLS 1.2 - The RFC 5246 version of TLS.
Signature algorithms from TLS 1.2.
constant SSL.Constants.SIGNATURE_anonymous
No signature.
constant SSL.Constants.SIGNATURE_dsa
DSS signature.
constant SSL.Constants.SIGNATURE_ecdsa
ECDSA signature.
constant SSL.Constants.SIGNATURE_rsa
RSASSA PKCS1 v1.5 signature.
A chain of X509 certificates with corresponding private key.
It also contains some derived metadata.
int SSL.Constants.CertificatePair.cert_type
Cerificate type for the leaf cert.
One of the AUTH_* constants.
array(string(8bit)) SSL.Constants.CertificatePair.certs
Chain of certificates, root cert last.
SSL.Constants.CertificatePair SSL.Constants.CertificatePair(Crypto.Sign.State key, array(string(8bit)) certs, array(string(8bit))|void extra_name_globs)
Initializa a new CertificatePair.
keyPrivate key.
certsChain of certificates, root cert last.
extra_globsThe set of globs from the first certificate
is optionally extended with these.
Performs various validation checks.
array(string(8bit)) SSL.Constants.CertificatePair.globs
Array of commonName globs from the first certificate in certs.
array(string(8bit)) SSL.Constants.CertificatePair.issuers
Array of DER for the issuers matching certs.
int(0..) SSL.Constants.CertificatePair.ke_mask
Bitmask of the key exchange algorithms supported by the main certificate. This is used for TLS 1.1 and earlier.
ke_mask_invariant
int(0..) SSL.Constants.CertificatePair.ke_mask_invariant
Bitmask of the key exchange algorithms supported by the main certificate.
This is the same as ke_mask, but unified with respect to
KE_dh_dss/KE_dh_rsa and KE_ecdh_ecdsa/KE_ecdh_rsa,
as supported by TLS 1.2 and later.
Crypto.Sign.State SSL.Constants.CertificatePair.key
Private key.
array(array(HashAlgorithm|SignatureAlgorithm)) SSL.Constants.CertificatePair.sign_algs
TLS 1.2-style hash and signature pairs matching the certs.
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.
mixed XXX(mixed ... args)
object async_XXX(mixed ... args)
object async_cb_XXX(function(:void) callback, mixed ... args)
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.
Protocols.LysKOM.Connection Protocols.LysKOM.Connection(string server)
Protocols.LysKOM.Connection Protocols.LysKOM.Connection(string server, mapping options)
The options argument is a mapping with the following members:
| login as this person number (get number from name). |
| send this login password. |
| if set, login invisible. |
| server port (default is 4894). |
| present as this user (default is from uid/getpwent and hostname). |
int Protocols.LysKOM.Connection.protocol_level
string Protocols.LysKOM.Connection.session_software
string Protocols.LysKOM.Connection.software_version
Description of the connected server.
Conference conference(int no)
Returns conference number no.
Protocols.LysKOM.Session Protocols.LysKOM.Session(string server)
Protocols.LysKOM.Session Protocols.LysKOM.Session(string server, mapping options)
Initializes the session object, and opens a connection to that server.
options is a mapping of options:
| login as this person number (get number from name). |
| create a new person and login with it. |
| send this login password. |
| if set, login invisible. |
| server port (default is 4894). |
| present as this user (default is from uid/getpwent and hostname). |
Connection
object create_person(string name, string password)
Create a person, which will be logged in. returns the new person object
object create_text(string subject, string body, mapping options)
object create_text(string subject, string body, mapping options, function(:void) callback, mixed ... extra)
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:
| recipient conferences. |
| cc-recipient conferences. |
| bcc-recipient conferences*. |
| The text(s) to be commented. |
| The text(s) to be footnoted. |
| send text anonymously. |
| AuxItems you want to set for the text*. |
The items above marked with '*' are only available on protocol 10 servers. A LysKOM error will be thrown if the call fails.
Conference.create_text(), Text.comment(), Text.footnote()
object login(int user_no, string password)
object login(int user_no, string password, int invisible)
Performs a login. Throws a lyskom error if unsuccessful.
The session object logged in.
this_program logout()
Logouts from the server. returns the called object
Person person(int no)
Returns the Person no.
void register_async_message_callback(function(int, int, string:void) cb)
object|void send_message(string textstring, mapping options)
Sends a message.
options is a mapping that may contain:
| recipient conference. |
Text text(int no)
Returns the text no.
array(ProtocolTypes.ConfZInfo) try_complete_person(string orig)
Runs a LysKOM completion on the given string, returning an array of confzinfos of the match.
object Protocols.LysKOM.Session.user
This variable contains the
Protocols.LysKOM.Session.Person
that is logged in.
Undocumented
inherit ProtocolTypes.AuxItemInput : AuxItemInput
Undocumented
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
Undocumented
Protocols.LysKOM.Session.Conference Protocols.LysKOM.Session.Conference(int no)
All variables in this class is read only.
object Protocols.LysKOM.Session.Membership.added_at
object Protocols.LysKOM.Session.Membership.conf
int Protocols.LysKOM.Session.Membership.last_text_read
object Protocols.LysKOM.Session.Membership.last_time_read
int number_unread()
int Protocols.LysKOM.Session.Membership.position
int(8bit) Protocols.LysKOM.Session.Membership.priority
void query_read_texts()
array(int) Protocols.LysKOM.Session.Membership.read_texts
multiset(string) Protocols.LysKOM.Session.Membership.type
array(object) unread_texts()
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
Undocumented
Protocols.LysKOM.Session.Person Protocols.LysKOM.Session.Person(int no)
int Protocols.LysKOM.Session.Person.no
mixed Protocols.LysKOM.Session.Person.prefetch_stat
mixed Protocols.LysKOM.Session.Person.prefetch_conf
mixed Protocols.LysKOM.Session.Person.prefetch_membership
Undocumented
All variables in this class is read only.
Undocumented
string Protocols.LysKOM.Session.Text.author
The author of the text.
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
Undocumented
Protocols.LysKOM.Session.Text Protocols.LysKOM.Session.Text(string textnumber)
Initializes a Text object.
mixed Protocols.LysKOM.Session.Text.creation_time
The time the text was created on the server.
object Protocols.LysKOM.Session.Text.err
Undocumented
void mark_as_read()
Undocumented.
int Protocols.LysKOM.Session.Text.marks
The number of marks on this text.
mixed Protocols.LysKOM.Session.Text.misc
Misc info, including what conferences the message is posted to.
Needs a more complete description.
int Protocols.LysKOM.Session.Text.no
The text number, as spicified to create.
string Protocols.LysKOM.Session.Text.subject
The message subject.
string Protocols.LysKOM.Session.Text.text
The actual text (or body if you wish).
Data types as defined by the LysKOM protocol specification.
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.
This is the main request class. All lyskom request classes inherit this class.
void _async(int call, mixed_data)
mixed _sync(int call, mixed_data)
Initialise an asynchronous or a synchronous call, the latter is also evaluating the result. These are called by async and sync respectively.
mixed _reply(object|array what)
mixed reply(object|array what)
_reply() is called as callback to evaluate the result,
and calls reply() in itself to do the real work.
mixed res = Protocols.LysKOM.Request._Request()()
Wait for the call to finish.
void async(mixed ... args)
mixed sync(mixed ... args)
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.
object Protocols.LysKOM.Request._Request.error
How the call failed.
The call has completed if (ok||error).
bool Protocols.LysKOM.Request._Request.ok
Tells if the call has executed ok
Support for the Domain Name System protocol.
RFC 1034, RFC 1035 and RFC 2308
final constantint Protocols.DNS.FORMERR
The name server was unable to interpret the request due to a format error.
final constantint Protocols.DNS.NOERROR
No error condition.
final constantint Protocols.DNS.NOTIMPL
The name server does not support the specified Opcode.
final constantint Protocols.DNS.NXDOMAIN
Some name that ought to exist, does not exist.
final constantint Protocols.DNS.NXRRSET
Some RRset that ought to exist, does not exist.
final constantint Protocols.DNS.REFUSED
The name server refuses to perform the specified operation for policy or security reasons.
final constantint Protocols.DNS.SERVFAIL
The name server encountered an internal failure while processing this request, for example an operating system error or a forwarding timeout.
void async_get_mx(string host, function(:void) cb, mixed ... cba)
void async_get_mx_all(string host, function(:void) cb, mixed ... cba)
void async_host_to_ip(string host, function(:void) cb, mixed ... cba)
void async_ip_to_host(string ip, function(:void) cb, mixed ... cba)
string get_mx(string host)
string get_primary_mx(string host)
array gethostbyaddr(string host)
array gethostbyname(string host)
Entry types
constant Protocols.DNS.T_A
Type - host address
constant Protocols.DNS.T_A6
Type - IPv6 address record (RFC 2874 Obsolete RFC 6563)
constant Protocols.DNS.T_AAAA
Type - IPv6 address record (RFC 1886)
constant Protocols.DNS.T_AFSDB
Type - AFC database record (RFC 1183)
constant Protocols.DNS.T_ANY
Type - ANY - A request for all records
constant Protocols.DNS.T_APL
Type - Address Prefix List (RFC 3123)
constant Protocols.DNS.T_ATMA
Type - ATM End System Address (af-saa-0069.000)
constant Protocols.DNS.T_AXFR
Type - Authoritative Zone Transfer (RFC 1035)
constant Protocols.DNS.T_CAA
Type - Certificate Authority Authorization (RFC 6844)
constant Protocols.DNS.T_CERT
Type - Certificate Record (RFC 4398)
constant Protocols.DNS.T_CNAME
Type - canonical name for an alias
constant Protocols.DNS.T_DHCID
Type - DHCP identifier (RFC 4701)
constant Protocols.DNS.T_DLV
Type - DNSSEC Lookaside Validation Record (RFC 4431)
constant Protocols.DNS.T_DNAME
Type - Delegation Name (RFC 2672)
constant Protocols.DNS.T_DNSKEY
Type - DNS Key record (RFC 4034)
constant Protocols.DNS.T_DS
Type - Delegation Signer (RFC 4034)
constant Protocols.DNS.T_EID
Type - Nimrod Endpoint IDentifier (draft)
constant Protocols.DNS.T_GPOS
Type - Global Position (RFC 1712 Obsolete use LOC).
constant Protocols.DNS.T_HINFO
Type - host information
constant Protocols.DNS.T_HIP
Type - Host Identity Protocol (RFC 5205)
constant Protocols.DNS.T_IPSECKEY
Type - IPsec Key (RFC 4025)
constant Protocols.DNS.T_ISDN
Type - ISDN address (RFC 1183)
constant Protocols.DNS.T_IXFR
Type - Incremental Zone Transfer (RFC 1996)
constant Protocols.DNS.T_KEY
Type - Key record (RFC 2535 and RFC 2930)
constant Protocols.DNS.T_KX
Type - Key eXchanger record (RFC 2230)
constant Protocols.DNS.T_LOC
Type - Location Record (RFC 1876)
constant Protocols.DNS.T_MAILA
Type - Mail Agent (both MD and MF) (Obsolete - use MX)
constant Protocols.DNS.T_MAILB
Type - Mail Box (MB, MG or MR) (Obsolete - use MX)
constant Protocols.DNS.T_MB
Type - mailbox domain name (Obsolete)
constant Protocols.DNS.T_MD
Type - mail destination (Obsolete - use MX)
constant Protocols.DNS.T_MF
Type - mail forwarder (Obsolete - use MX)
constant Protocols.DNS.T_MG
Type - mail group member (Obsolete)
constant Protocols.DNS.T_MINFO
Type - mailbox or mail list information (Obsolete)
constant Protocols.DNS.T_MR
Type - mail rename domain name (Obsolete)
constant Protocols.DNS.T_MX
Type - mail exchange
constant Protocols.DNS.T_NAPTR
Type - NAPTR (RFC 3403)
constant Protocols.DNS.T_NIMLOC
Type - Nimrod Locator (draft)
constant Protocols.DNS.T_NS
Type - authoritative name server
constant Protocols.DNS.T_NSAP
Type - OSI Network Service Access Protocol (RFC 1348, RFC 1637, RFC 1706)
constant Protocols.DNS.T_NSAP_PTR
Type - OSI NSAP Pointer (RFC 1348, Obsolete RFC 1637)
constant Protocols.DNS.T_NSEC
Type - Next-Secure record (RFC 4034)
constant Protocols.DNS.T_NSEC3
Type - NSEC record version 3 (RFC 5155)
constant Protocols.DNS.T_NSEC3PARAM
Type - NSEC3 parameters (RFC 5155)
constant Protocols.DNS.T_NULL
Type - null RR (Obsolete RFC 1035)
constant Protocols.DNS.T_NXT
Type - Next (RFC 2065, Obsolete RFC 3755)
constant Protocols.DNS.T_OPT
Type - Option (RFC 2671)
constant Protocols.DNS.T_PTR
Type - domain name pointer
constant Protocols.DNS.T_PX
Type - Pointer to X.400 mapping information (RFC 1664)
constant Protocols.DNS.T_RP
Type - Responsible Person
constant Protocols.DNS.T_RRSIG
Type - DNSSEC signature (RFC 4034)
constant Protocols.DNS.T_RT
Type - Route Through (RFC 1183)
constant Protocols.DNS.T_SIG
Type - Signature (RFC 2535)
constant Protocols.DNS.T_SINK
Type - Kitchen Sink (draft)
constant Protocols.DNS.T_SOA
Type - start of a zone of authority
constant Protocols.DNS.T_SPF
Type - SPF - Sender Policy Framework (RFC 4408)
constant Protocols.DNS.T_SRV
Type - Service location record (RFC 2782)
constant Protocols.DNS.T_SSHFP
Type - SSH Public Key Fingerprint (RFC 4255)
constant Protocols.DNS.T_TA
Type - DNSSEC Trust Authorities (draft)
constant Protocols.DNS.T_TKEY
Type - Secret key record (RFC 2930)
constant Protocols.DNS.T_TLSA
Type - TLSA certificate association (RFC 6698)
constant Protocols.DNS.T_TSIG
Type - Transaction Signature (RFC 2845)
constant Protocols.DNS.T_TXT
Type - text strings
constant Protocols.DNS.T_WKS
Type - well known service description (Obsolete RFC 1123, RFC 1127)
constant Protocols.DNS.T_X25
Type - X25 PSDN address (RFC 1183)
Resource classes
constant Protocols.DNS.C_ANY
Class ANY
constant Protocols.DNS.C_CH
Class CHAOS
constant Protocols.DNS.C_CS
Class CSNET (Obsolete)
constant Protocols.DNS.C_HS
Class Hesiod
constant Protocols.DNS.C_IN
Class Internet
Asynchronous DNS client.
void close()
Close the client.
All active requests are aborted.
Protocols.DNS.async_client Protocols.DNS.async_client(void|string|array(string) server, void|string|array(string) domain)
Request do_query(string domain, int cl, int type, function(string, mapping, mixed ... :void) callback, mixed ... args)
Enqueue a new raw DNS request.
Returns a Request object.
Pike versions prior to 8.0 did not return the Request object.
Request get_mx(string host, function(:void) callback, mixed ... args)
Request get_mx_all(string host, function(:void) callback, mixed ... args)
Request host_to_ip(string host, function(:void) callback, mixed ... args)
inherit client : client
inherit Stdio.UDP : udp
Request ip_to_host(string ip, function(:void) callback, mixed ... args)
Both an async_client and an async_tcp_client.
Request do_query(string domain, int cl, int type, function(string, mapping, mixed ... :void) callback, mixed ... args)
inherit async_tcp_client : TCP
inherit async_client : UDP
Asynchronous DNS client using TCP
Request do_query(string domain, int cl, int type, function(string, mapping, mixed ... :void) callback, mixed ... args)
inherit async_client : async_client
inherit ::this_program : this_program
Synchronous DNS client.
Protocols.DNS.client Protocols.DNS.client()
Protocols.DNS.client Protocols.DNS.client(void|string|array server, void|int|array domain)
mapping do_sync_query(string s)
Perform a synchronous DNS query.
sResult of Protocols.DNS.protocol.mkquery
mapping containing query result or 0 on failure/timeout
// Perform a hostname lookup, results stored in r->an object d=Protocols.DNS.client(); mapping r=d->do_sync_query(d->mkquery("pike.lysator.liu.se", C_IN, T_A));
array(string) get_mx(string host)
string get_primary_mx(string hostname)
Queries the primary mx for the host.
Returns the hostname of the primary mail exchanger.
array gethostbyaddr(string hostip)
Queries the host name or ip from the default or given DNS server. The result is an array with three elements,
The requested data about the specified host.
| Array | |
| The host IP. |
| IP number(s). |
| DNS name(s). |
array gethostbyname(string hostname)
Queries the host name from the default or given DNS server. The result is an array with three elements,
An array with the requested information about the specified host.
| Array | |
| Hostname. |
| IP number(s). |
| DNS name(s). |
Prior to Pike 7.7 this function only returned IPv4 addresses.
array getsrvbyname(string service, string protocol, string|void name)
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:
An array with the requested information about the specified service.
| Array | |
| Priority |
| Weight in event of multiple records with same priority. |
| port number |
| target dns name |
inherit protocol : protocol
string Protocols.DNS.client.Request.domain
string Protocols.DNS.client.Request.req
function(string, mapping, mixed ... :void) Protocols.DNS.client.Request.callback
array(mixed) Protocols.DNS.client.Request.args
void cancel()mixed Protocols.DNS.client.Request.retry_co
Cancel the current request.
Protocols.DNS.client.Request Protocols.DNS.client.Request(string domain, string req, function(string, mapping, mixed ... :void) callback, array(mixed) args)
Both a client and a tcp_client.
mapping do_sync_query(string s)
inherit tcp_client : TCP
inherit client : UDP
This is both a server and tcp_server.
inherit tcp_server : TCP
inherit server : UDP
Low level DNS protocol
array decode_entries(string s, int num, array(int) next)
Decode a set of entries from an answer.
sEncoded entries.
numNumber of entires in s.
nextArray with a single element containing the start position in s
on entry and the continuation position on return.
Returns an array of mappings describing the decoded entires:
| Array | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Mapping describing a single entry:
Depending on the type of entry the mapping may contain different additional fields:
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
string mkquery(string|mapping dnameorquery, int|void cl, int|void type)
create a DNS query PDU
dnameorqueryclrecord class such as Protocols.DNS.C_IN
typequery type such Protocols.DNS.T_A
data suitable for use with
Protocols.DNS.client.do_sync_query
// generate a query PDU for a address lookup on the hostname pike.lysator.liu.se string q=Protocols.DNS.protocol()->mkquery("pike.lysator.liu.se", Protocols.DNS.C_IN, Protocols.DNS.T_A);
Base class for implementing a Domain Name Service (DNS) server operating over UDP.
This class is typically used by inheriting it,
and overloading reply_query() and handle_response().
dual_server
Protocols.DNS.server Protocols.DNS.server()
Protocols.DNS.server Protocols.DNS.server(int port)
Protocols.DNS.server Protocols.DNS.server(string ip)
Protocols.DNS.server Protocols.DNS.server(string ip, int port)
Protocols.DNS.server Protocols.DNS.server(string ip, int port, string|int ... more)
Open one or more new DNS server ports.
ipThe IP to bind to. Defaults to "::" or 0 (ie ANY)
depending on whether IPv6 support is present or not.
portThe port number to bind to. Defaults to 53.
moreOptional further DNS server ports to open.
Must be a set of ip, port argument pairs.
inherit server_base : server_base
Base class for server, tcp_server.
protected void handle_decode_error(mapping err, mapping m, Stdio.UDP|object udp)
Respond to a query that cannot be decoded.
This method exists so that servers can override the default behaviour.
protected void handle_query(mapping q, mapping m, Stdio.UDP|object udp)
Handle a query.
This function calls reply_query(),
and dispatches the result to send_reply().
protected void handle_response(mapping r, mapping m, Stdio.UDP|object udp)
Handle a query response (stub).
Overload this function to handle responses to possible recursive queries.
inherit protocol : protocol
protected void rec_data(mapping m, Stdio.UDP|object udp)
Low-level DNS-data receiver.
This function receives the raw DNS-data from the Stdio.UDP socket
or TCP connection object udp, decodes it, and dispatches the decoded
DNS request to handle_query() and handle_response().
protected mapping reply_query(mapping query, mapping udp_data, function(mapping:void) cb)
Reply to a query (stub).
queryParsed query.
udp_dataRaw UDP data. If the server operates in TCP mode (tcp_server),
it will contain an additional tcp_con entry. In that case,
udp_data->tcp_con->con will contain the TCP connection the
request was received on as Stdio.File object.
cbCallback you can call with the result instead of returning it.
In that case, return 0 (zero).
Overload this function to implement the proper lookup.
To indicate the default failure cb must be called with an
argument of 0 (zero), and 0 (zero) be returned.
Returns 0 (zero) when the cb callback will be used,
or a result mapping if not:
| 0 (or omit) for success, otherwise one of the Protocols.DNS.* constants | |||||||
| Answer section:
| |||||||
| Question section, same format as | |||||||
| Authority section (usually NS records), same format as | |||||||
| Additional section, same format as | |||||||
| Set to 1 to include the Authoritative Answer bit in the response | |||||||
| Set to 1 to include the TrunCated bit in the response | |||||||
| Set to 1 to include the Recursion Desired bit in the response | |||||||
| Set to 1 to include the Recursion Available bit in the response | |||||||
| Set to 1 to include the Checking Disabled bit in the response | |||||||
| Set to 1 to include the Authenticated Data bit in the response | |||||||
protected void report_decode_error(mixed err, mapping m, Stdio.UDP|object udp)
Report a failure to decode a DNS request.
The default implementation writes a backtrace to stderr. This method exists so that derived servers can replace it with more appropriate error handling for their environment.
Synchronous DNS client using TCP
Can handle larger responses than client can.
mapping do_sync_query(string s)
Perform a synchronous DNS query.
sResult of Protocols.DNS.protocol.mkquery
mapping containing query result or 0 on failure/timeout
// Perform a hostname lookup, results stored in r->an object d=Protocols.DNS.tcp_client(); mapping r=d->do_sync_query(d->mkquery("pike.lysator.liu.se", C_IN, T_A));
inherit client : client
Base class for implementing a Domain Name Service (DNS) server operating over TCP.
This class is typically used by inheriting it,
and overloading reply_query() and handle_response().
Protocols.DNS.tcp_server Protocols.DNS.tcp_server()
Protocols.DNS.tcp_server Protocols.DNS.tcp_server(int port)
Protocols.DNS.tcp_server Protocols.DNS.tcp_server(string ip)
Protocols.DNS.tcp_server Protocols.DNS.tcp_server(string ip, int port)
Protocols.DNS.tcp_server Protocols.DNS.tcp_server(string ip, int port, string|int ... more)
Open one or more new DNS server ports.
ipThe IP to bind to. Defaults to "::" or 0 (ie ANY)
depending on whether IPv6 support is present or not.
portThe port number to bind to. Defaults to 53.
moreOptional further DNS server ports to open.
Must be a set of ip, port argument pairs.
inherit server_base : server_base
Generate a .torrent binary string from files in the filesystem
// 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; }
this_program add(string path, void|string base)
Add a file, or a directory tree to the torrent. This will call add_directory_tree or add_file.
this_program add_announce(string|array(string) announce_url)
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.
this_program add_directory_tree(string path, void|string dirbase)
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.
this_program add_file(string path, void|string filename)
Add a file to the torrent. The second argument is what the file will be called in the torrent.
void build_sha1s(void|function(int, int:void) progress_callback)
Build the SHA hashes from the files.
Protocols.Bittorrent.Generator Protocols.Bittorrent.Generator(void|string base, void|int piece_size)
Create a generator.
baseThe base filename/path in the torrent.
piece_sizeThe size of the pieces that the SHA hashes are calculated on. Default 262144 and this value should probably be 2^n.
string digest(void|function(int, int:void) progress_callback)
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.
inherit .Torrent : Torrent
void connect()
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).
void disconnect()
Disconnect a peer.
Does nothing if we aren't online.
status/mode will change to "disconnected",1 if we were online.
multiset(int) downloading_pieces()
Returns as multiset what this peer is downloading.
int is_activated()
Returns true if this peer is activated, as in we're downloading from it.
int is_available()
Returns true if this peer is available, as in we can use it to download stuff.
int is_choked()
Returns true if this peer is choking, as in doesn't send more data to us.
int is_completed()
Returns true if this peer is completed, as in has downloaded everything already - and we shouldn't need to upload to get stuff.
int is_connectable()
Returns true if we can connect to this peer, when new or disconnected but not fatally.
int is_online()
Returns true if this peer is online and connected.
int is_strangled()
Returns true if this peer is strangled; as in we don't want to upload more, because we're not getting any back.
void request(int piece, int offset, int bytes, function(int, int, string, object:void|mixed) callback)
Called to request a chunk from this peer.
void send_have(int n)
Send a have message to tell I now have piece n. Ignored if not online.
void status(string type, void|int|string data)
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.
Protocols.Bittorrent.Port Protocols.Bittorrent.Port(.Torrent _parent)
Bind a port for this Torrent.
Bittorrent peer - download and share. Read more about bittorrent at http://bitconjurer.org/BitTorrent/introduction.html
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; }
int bytes_done()
Calculate the bytes successfully downloaded (full pieces).
int bytes_left()
Calculate the bytes left to download.
void contact_peers(void|int n)
Contact all or n peers.
function(.Peer, int, int:bool) Protocols.Bittorrent.Torrent.do_we_strangle
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.
function(:void) Protocols.Bittorrent.Torrent.download_completed_callback
If set, called when download is completed.
function(:void) Protocols.Bittorrent.Torrent.downloads_update_status
If set, called when we start to download another piece (no args).
string file_got_bitfield()
Returns the file got field as a string bitfield (cached).
int fix_targets(void|int(-1..2) allocate, void|string base_filename, void|function(int, int:void) progress_callback)
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.
allocateDetermines allocation procedure if the file doesn't exist:
| Don't allocate. |
| Allocate virtual file size (seek, write end byte). |
| Allocate for real (will call progress_callback(pos,length)). |
| Means never create a file, only open old files. |
my_filenameA new base filename to substitute the metainfo base target filename with.
| The (a) file was already there. |
| All target files were created. |
void load_metainfo(string filename)
Loads the metainfo from a file.
void open_port(void|int port)
Open the port we're listening on.
function(:void) Protocols.Bittorrent.Torrent.peer_update_status
If set, called when peer status changes.
function(:void) Protocols.Bittorrent.Torrent.pieces_update_status
If set, called when we got another piece downloaded (no args).
void start_download()
Initiate the downloading scheme.
void start_update_tracker(void|int interval)
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.
void stop_update_tracker(void|string event)
Stops updating the tracker; will send the event as a last event, if set. It will not contact new peers.
void update_tracker(void|string event, void|int contact)
Contact and update the tracker with current status will fill the peer list.
void verify_targets(void|function(int, int:void) progress_callback)
Verify the file and fill file_got (necessary after load_info, but needs open_file before this call). [ progress_callback(at chunk,total chunks) ]
function(string, mixed ... :void|mixed) Protocols.Bittorrent.Torrent.warning
Called if there is a protocol error.
Each bittorrent has one or more target files. This represents one of those.
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
Protocols.Bittorrent.Torrent.Target Protocols.Bittorrent.Torrent.Target(string base, int length, int offset, void|array path)
void add_torrent(string id)
Add a torrent to the tracker.
idThe info hash of the torrent file.
string announce(mapping args, string ip)
Handles HTTP announce queries to the tracker.
bool Protocols.Bittorrent.Tracker.dynamic_add_torrents
Allow clients to dynamically add torrents to the tracker.
int(0..) Protocols.Bittorrent.Tracker.interval
The query interval reported back to clients. Defaults to
1800.
string scrape(mapping args)
Returns the result of a scrape query.
array(string|int|array|mapping) _decode(string what)
Decodes a Bittorrent bencoded data chunk.
| Array | |
| The decoded data. UNDEFINED if no data could be decoded. |
| The trailing data that wasn't decoded. |
string bits2string(array(bool) v)
Convert an array of int(0..1) to a Bittorrent style
bitstring. Input will be padded to even bytes.
string|int|array|mapping decode(string what)
Decodes a Bittorrent bencoded data chunk and ignores the remaining string. Returns UNDEFINED if the data is incomplete.
string encode(string|int|array|mapping data)
Encodes a Bittorrent bencoded data chunk.
array(int) string2arr(string s)
Convert a Bittorrent style bitstring to an array of indices.
array(bool) string2bits(string s)
Convert a Bittorrent style bitstring to an array of
int(0..1).
string identify_peer(string peerid)
Decodes the given peerid, returning an identification string
for the client software. Assumes the peerid string is exactly
20 characters long.
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.
Protocols.DNS_SD.Service Protocols.DNS_SD.Service(string name, string service, string domain, int port, void|string|array(string) txt)
Registers a service on the local network.
nameUser-presentable name of the service.
serviceType 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.
domainDomain name. Normally an empty string which the DNS-SD library will translate into local..
portPort number for the service (e.g. 80 for a web site).
txtAn 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.
object svc = Protocols.DNS_SD.Service( "Company Intranet Forum", // name "_http._tcp", // service type "", // domain (default) 80, // port ({ "path=/forum/" }) // TXT record );
inherit _Protocols_DNS_SD.Service : Service
void update_txt(string|array(string) txt)
Updates the TXT record for the service.
txtA 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.
string format_addr_short(array(int(16bit)) bin_addr)
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.
parse_addr
string normalize_addr_basic(string addr)
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.
normalize_addr_short
string normalize_addr_short(string addr)
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.
normalize_addr_basic
array(int(16bit)) parse_addr(string addr)
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.
format_addr_short
Abstract class for a IRC channel.
string Protocols.IRC.Channel.name
The name of the channel.
void close()
Closes the connection to the server.
Protocols.IRC.Client Protocols.IRC.Client(string|object server, void|mapping(string:mixed) options)
serverThe IRC server to connect to.
If server is an object, it is assumed to be a newly established
connection to the IRC server to be used. Pass SSL.File
connections here to connect to SSL secured IRC networks.
optionsAn optional mapping with additional IRC client options.
| Defaults to 6667. |
| Defaults to |
| Defaults to |
| Server password, if any. Public servers seldom require this. |
| Defaults to |
| Defaults to |
| Defaults to 120. |
| Defaults to 120. |
| 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. |
| This function is called when a KILL or ERROR command is recieved from the IRC server. |
| |
| |
| |
| The arguments are from, type, to, message and extra. |
| The arguments are who and why. |
| The arguments are originator, message and to. |
| The arguments are originator, message and to. |
| The arguments are originator and to. |
Abstract class for a person.
string Protocols.IRC.Person.ip
User domain, e.g. "mistel.idonex.se".
int Protocols.IRC.Person.last_action
Time of last action, represented as posix time.
string Protocols.IRC.Person.nick
User nickname, e.g. "Mirar".
string Protocols.IRC.Person.user
User name, e.g. "mirar".
An implementation of the IDENT protocol, specified in RFC 931.
array(string) lookup(object fd)
Throws exception upon any error.
Protocols.Ident.AsyncLookup Protocols.Ident.AsyncLookup(object fd, function(array(string), mixed ... :void) cb, mixed ... args)
constant string Protocols.LDAP.GUID_USERS_CONTAINER
constant string Protocols.LDAP.GUID_COMPUTERS_CONTAINER
constant string Protocols.LDAP.GUID_SYSTEMS_CONTAINER
constant string Protocols.LDAP.GUID_DOMAIN_CONTROLLERS_CONTAINER
constant string Protocols.LDAP.GUID_INFRASTRUCTURE_CONTAINER
constant string Protocols.LDAP.GUID_DELETED_OBJECTS_CONTAINER
constant string Protocols.LDAP.GUID_LOSTANDFOUND_CONTAINER
constant string Protocols.LDAP.GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER
constant string Protocols.LDAP.GUID_PROGRAM_DATA_CONTAINER
constant string Protocols.LDAP.GUID_MICROSOFT_PROGRAM_DATA_CONTAINER
constant string Protocols.LDAP.GUID_NTDS_QUOTAS_CONTAINER
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>"
constant int Protocols.LDAP.LDAP_SUCCESS
constant int Protocols.LDAP.LDAP_OPERATIONS_ERROR
constant int Protocols.LDAP.LDAP_PROTOCOL_ERROR
constant int Protocols.LDAP.LDAP_TIMELIMIT_EXCEEDED
constant int Protocols.LDAP.LDAP_SIZELIMIT_EXCEEDED
constant int Protocols.LDAP.LDAP_COMPARE_FALSE
constant int Protocols.LDAP.LDAP_COMPARE_TRUE
constant int Protocols.LDAP.LDAP_AUTH_METHOD_NOT_SUPPORTED
constant Protocols.LDAP.LDAP_STRONG_AUTH_NOT_SUPPORTED
constant int Protocols.LDAP.LDAP_STRONG_AUTH_REQUIRED
constant int Protocols.LDAP.LDAP_PARTIAL_RESULTS
constant int Protocols.LDAP.LDAP_REFERRAL
constant int Protocols.LDAP.LDAP_ADMINLIMIT_EXCEEDED
constant int Protocols.LDAP.LDAP_UNAVAILABLE_CRITICAL_EXTENSION
constant int Protocols.LDAP.LDAP_CONFIDENTIALITY_REQUIRED
constant int Protocols.LDAP.LDAP_SASL_BIND_IN_PROGRESS
constant int Protocols.LDAP.LDAP_NO_SUCH_ATTRIBUTE
constant int Protocols.LDAP.LDAP_UNDEFINED_TYPE
constant int Protocols.LDAP.LDAP_INAPPROPRIATE_MATCHING
constant int Protocols.LDAP.LDAP_CONSTRAINT_VIOLATION
constant int Protocols.LDAP.LDAP_TYPE_OR_VALUE_EXISTS
constant int Protocols.LDAP.LDAP_INVALID_SYNTAX
constant int Protocols.LDAP.LDAP_NO_SUCH_OBJECT
constant int Protocols.LDAP.LDAP_ALIAS_PROBLEM
constant int Protocols.LDAP.LDAP_INVALID_DN_SYNTAX
constant int Protocols.LDAP.LDAP_IS_LEAF
constant int Protocols.LDAP.LDAP_ALIAS_DEREF_PROBLEM
constant int Protocols.LDAP.LDAP_INAPPROPRIATE_AUTH
constant int Protocols.LDAP.LDAP_INVALID_CREDENTIALS
constant int Protocols.LDAP.LDAP_INSUFFICIENT_ACCESS
constant int Protocols.LDAP.LDAP_BUSY
constant int Protocols.LDAP.LDAP_UNAVAILABLE
constant int Protocols.LDAP.LDAP_UNWILLING_TO_PERFORM
constant int Protocols.LDAP.LDAP_LOOP_DETECT
constant int Protocols.LDAP.LDAP_SORT_CONTROL_MISSING
constant int Protocols.LDAP.LDAP_NAMING_VIOLATION
constant int Protocols.LDAP.LDAP_OBJECT_CLASS_VIOLATION
constant int Protocols.LDAP.LDAP_NOT_ALLOWED_ON_NONLEAF
constant int Protocols.LDAP.LDAP_NOT_ALLOWED_ON_RDN
constant int Protocols.LDAP.LDAP_ALREADY_EXISTS
constant int Protocols.LDAP.LDAP_NO_OBJECT_CLASS_MODS
constant int Protocols.LDAP.LDAP_RESULTS_TOO_LARGE
constant int Protocols.LDAP.LDAP_AFFECTS_MULTIPLE_DSAS
constant int Protocols.LDAP.LDAP_OTHER
LDAP result codes.
Protocols.LDAP.client.error_number,
Protocols.LDAP.client.result.error_number
constant string Protocols.LDAP.LDAP_CONTROL_MANAGE_DSA_IT
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 string Protocols.LDAP.LDAP_CONTROL_VLVREQUEST
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 string Protocols.LDAP.LDAP_CONTROL_VLVRESPONSE
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 string Protocols.LDAP.LDAP_PAGED_RESULT_OID_STRING
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 string Protocols.LDAP.LDAP_SERVER_ASQ_OID
LDAP control: Microsoft AD: Control to force the query to be based on a specific DN-valued attribute.
constant string Protocols.LDAP.LDAP_SERVER_CROSSDOM_MOVE_TARGET_OID
LDAP control: Microsoft AD: Control used with an extended LDAP rename function to move an LDAP object from one domain to another.
constant string Protocols.LDAP.LDAP_SERVER_DIRSYNC_OID
LDAP control: Microsoft AD: Control that enables an application to search the directory for objects changed from a previous state.
constant string Protocols.LDAP.LDAP_SERVER_DOMAIN_SCOPE_OID
LDAP control: Microsoft AD: Control used to instruct the LDAP server not to generate any referrals when completing a request.
constant string Protocols.LDAP.LDAP_SERVER_EXTENDED_DN_OID
LDAP control: Microsoft AD: Control to request an extended form of an Active Directory object distinguished name.
constant string Protocols.LDAP.LDAP_SERVER_LAZY_COMMIT_OID
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 string Protocols.LDAP.LDAP_SERVER_NOTIFICATION_OID
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 string Protocols.LDAP.LDAP_SERVER_PERMISSIVE_MODIFY_OID
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 string Protocols.LDAP.LDAP_SERVER_QUOTA_CONTROL_OID
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 string Protocols.LDAP.LDAP_SERVER_RESP_SORT_OID
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 string Protocols.LDAP.LDAP_SERVER_SD_FLAGS_OID
LDAP control: Microsoft AD: Control used to pass flags to the server to control various security descriptor results.
constant string Protocols.LDAP.LDAP_SERVER_SEARCH_OPTIONS_OID
LDAP control: Microsoft AD: Control used to pass flags to the server to control various search behaviors.
constant string Protocols.LDAP.LDAP_SERVER_SHOW_DELETED_OID
LDAP control: Microsoft AD: Control used to specify that the search results include any deleted objects that match the search filter.
constant string Protocols.LDAP.LDAP_SERVER_SORT_OID
LDAP control: Microsoft AD: Control used to instruct the server to sort the search results before returning them to the client application.
constant string Protocols.LDAP.LDAP_SERVER_TREE_DELETE_OID
LDAP control: Microsoft AD: Control used to delete an entire subtree in the directory.
constant string Protocols.LDAP.LDAP_SERVER_VERIFY_NAME_OID
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 int Protocols.LDAP.MODIFY_ADD
constant int Protocols.LDAP.MODIFY_DELETE
constant int Protocols.LDAP.MODIFY_REPLACE
Constants used in the attropval argument to
Protocols.LDAP.client.modify.
constant int Protocols.LDAP.SCOPE_BASE
constant int Protocols.LDAP.SCOPE_ONE
constant int Protocols.LDAP.SCOPE_SUB
Constants for the search scope used with e.g.
Protocols.LDAP.client.set_scope.
Return the object specified by the DN.
Return the immediate subobjects of the object specified by the DN.
Return the object specified by the DN and all objects below it (on any level).
constant int Protocols.LDAP.SEARCH_LOWER_ATTRS
constant int Protocols.LDAP.SEARCH_MULTIVAL_ARRAYS_ONLY
constant int Protocols.LDAP.SEARCH_RETURN_DECODE_ERRORS
Bitfield flags given to Protocols.LDAP.client.search:
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.
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.
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 Charset.DecodeError object.
constant string Protocols.LDAP.SYNTAX_AD_CASE_IGNORE_STR
constant string Protocols.LDAP.SYNTAX_AD_LARGE_INT
constant string Protocols.LDAP.SYNTAX_AD_OBJECT_SECURITY_DESCRIPTOR
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 string Protocols.LDAP.SYNTAX_ATTR_TYPE_DESCR
constant string Protocols.LDAP.SYNTAX_BINARY
constant string Protocols.LDAP.SYNTAX_BIT_STRING
constant string Protocols.LDAP.SYNTAX_BOOLEAN
constant string Protocols.LDAP.SYNTAX_CERT
constant string Protocols.LDAP.SYNTAX_CERT_LIST
constant string Protocols.LDAP.SYNTAX_CERT_PAIR
constant string Protocols.LDAP.SYNTAX_COUNTRY_STR
constant string Protocols.LDAP.SYNTAX_DN
constant string Protocols.LDAP.SYNTAX_DIRECTORY_STR
constant string Protocols.LDAP.SYNTAX_DIT_CONTENT_RULE_DESCR
constant string Protocols.LDAP.SYNTAX_FACSIMILE_PHONE_NUM
constant string Protocols.LDAP.SYNTAX_FAX
constant string Protocols.LDAP.SYNTAX_GENERALIZED_TIME
constant string Protocols.LDAP.SYNTAX_IA5_STR
constant string Protocols.LDAP.SYNTAX_INT
constant string Protocols.LDAP.SYNTAX_JPEG
constant string Protocols.LDAP.SYNTAX_MATCHING_RULE_DESCR
constant string Protocols.LDAP.SYNTAX_MATCHING_RULE_USE_DESCR
constant string Protocols.LDAP.SYNTAX_MHS_OR_ADDR
constant string Protocols.LDAP.SYNTAX_NAME_AND_OPTIONAL_UID
constant string Protocols.LDAP.SYNTAX_NAME_FORM_DESCR
constant string Protocols.LDAP.SYNTAX_NUMERIC_STRING
constant string Protocols.LDAP.SYNTAX_OBJECT_CLASS_DESCR
constant string Protocols.LDAP.SYNTAX_OID
constant string Protocols.LDAP.SYNTAX_OTHER_MAILBOX
constant string Protocols.LDAP.SYNTAX_POSTAL_ADDR
constant string Protocols.LDAP.SYNTAX_PRESENTATION_ADDR
constant string Protocols.LDAP.SYNTAX_PRINTABLE_STR
constant string Protocols.LDAP.SYNTAX_PHONE_NUM
constant string Protocols.LDAP.SYNTAX_UTC_TIME
constant string Protocols.LDAP.SYNTAX_LDAP_SYNTAX_DESCR
constant string Protocols.LDAP.SYNTAX_DIT_STRUCTURE_RULE_DESCR
LDAP syntax: Standard syntaxes from RFC 2252.
constant Protocols.LDAP.SYNTAX_CASE_EXACT_STR
"caseExactString" is an alias used in e.g. RFC 2079.
constant string Protocols.LDAP.SYNTAX_DELIVERY_METHOD
constant string Protocols.LDAP.SYNTAX_ENHANCED_GUIDE
constant string Protocols.LDAP.SYNTAX_GUIDE
constant string Protocols.LDAP.SYNTAX_OCTET_STR
constant string Protocols.LDAP.SYNTAX_TELETEX_TERMINAL_ID
constant string Protocols.LDAP.SYNTAX_TELETEX_NUM
constant string Protocols.LDAP.SYNTAX_SUPPORTED_ALGORITHM
LDAP syntax: Standard syntaxes from RFC 2256.
string canonicalize_dn(string dn, void|int strict)
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.
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.
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.
string encode_dn_value(string str)
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.
object get_cached_filter(string filter, void|int ldap_version)
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.
If there's a parse error in the filter then a FilterError is
thrown as from make_filter.
object get_connection(string ldap_url, void|string binddn, void|string password, void|int version, void|SSL.Context ctx)
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.
ctx may be specified to control SSL/TLS parameters to use
with the "ldaps"-protocol. Note that changing this only
affects new connections.
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.
string get_constant_name(mixed val)
If val matches any non-integer constant in this module, its
name is returned.
string ldap_decode_string(string str)
Decodes all \xx escapes in str.
ldap_encode_string
string ldap_encode_string(string str)
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.
ldap_decode_string, Protocols.LDAP.client.search
constant Protocols.LDAP.ldap_error_strings
Mapping from LDAP_* result codes to descriptive strings.
object make_filter(string filter, void|int ldap_version)
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.
filterThe 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.
ldap_versionLDAP 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.
An ASN1 object tree representing the filter.
FilterError is thrown if there's a syntax error in the
filter.
int num_connections(string ldap_url)
Returns the number of currently stored connections for the given LDAP URL.
mapping(string:mixed) parse_ldap_url(string ldap_url)
Parses an LDAP URL and returns its fields in a mapping.
The returned mapping contains these fields:
| The URL scheme, either |
| Self-explanatory. |
| |
| |
| Array containing the attributes. Undefined if none was specified. |
| The scope as one of the |
| The search filter. Undefined if none was specified. |
| The extensions. Undefined if none was specified. The mapping
values are |
| The original unparsed URL. |
get_parsed_url
void return_connection(object conn)
Use this to return a connection to the connection pool after you've finished using it. The connection is assumed to be working.
Ensure that persistent connection settings such as the scope and the base DN are restored to the defaults
constant mapping(string:function(string:string)) Protocols.LDAP.syntax_decode_fns
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(string:function(string:string)) Protocols.LDAP.syntax_encode_fns
Mapping containing the reverse functions from syntax_decode_fns.
Error object thrown by make_filter for parse errors.
constant int Protocols.LDAP.FilterError.is_ldap_filter_error
Recognition constant.
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.
int add(string dn, mapping(string:array(string)) attrs)
The Add Operation allows a client to request the addition of an entry into the directory
dnThe Distinguished Name of the entry to be added.
attrsThe 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 1 on success, 0 otherwise.
The API change: the returning code was changed in Pike 7.3+ to follow his logic better.
int bind()
int bind(string dn, string password)
int bind(string dn, string password, int version)
Authenticates connection to the direcory.
First form uses default value previously entered in create.
Second form uses value from parameters:
dnThe distinguished name (DN) of an entry aginst which will be made authentication.
passwordPassword used for authentication.
Third form allows specify the version of LDAP protocol used by connection to the LDAP server.
versionThe desired protocol version (current 2 or 3).
Defaults to 3 if zero or left out.
Returns 1 on success, 0 otherwise.
Only simple authentication type is implemented. So be warned clear text passwords are sent to the directory server.
The API change: the returning code was changed in Pike 7.3+ to follow his logic better.
int compare(string dn, string attr, string value)
Compares an attribute value with one in the directory.
dnThe distinguished name of the entry.
attrThe type (aka name) of the attribute to compare.
valueThe value to compare with. It's UTF-8 encoded automatically if the attribute syntax specifies that.
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).
This function has changed arguments since version 7.6. From 7.3 to 7.6 it was effectively useless since it always returned true.
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.
Protocols.LDAP.client Protocols.LDAP.client()
Protocols.LDAP.client Protocols.LDAP.client(string|mapping(string:mixed) url)
Protocols.LDAP.client Protocols.LDAP.client(string|mapping(string:mixed) url, object context)
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.
urlLDAP 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.
contextTLS context of connection
LDAP.client.bind, LDAP.client.search
int delete(string dn)
Deletes entry from the LDAP server.
dnThe distinguished name of deleted entry.
Returns 1 on success, 0 otherwise.
The API change: the returning code was changed in Pike 7.3+ to follow his logic better.
mapping(string:mixed) get_attr_type_descr(string attr, void|int standard_attrs)
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.
attrThe name of the attribute. Might also be the object identifier on string form.
standard_attrsFlag that controls how the known standard attributes stored in
Protocols.LDAP are to be used:
| Check the known standard attributes first. If the attribute isn't found there, query the server. This is the default. |
| Don't check the known standard attributes, i.e. always use the schema from the server. |
| Only check the known standard attributes. The server is never contacted. |
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):
| 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). | |||||||
| Array with one or more names used for the attribute. | |||||||
| Description. | |||||||
| Flag. | |||||||
| 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. | |||||||
| The value is the name or oid of a matching rule. | |||||||
| The value is the name or oid of a matching rule. | |||||||
| The value is the name or oid of a matching rule. | |||||||
| The value is the oid of the syntax (RFC 2252, section 4.3.2).
(This is extracted from the | |||||||
| 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 | |||||||
| Flag. Default multi-valued. | |||||||
| Flag. Default not collective. | |||||||
| Flag. Default user modifiable. | |||||||
| The value is any of the following:
|
There might be more fields for server extensions.
Zero is returned if the server didn't provide any attribute type
description for attr.
It's the schema applicable at the base DN that is queried.
LDAPv3 is assumed.
string get_basedn()
Returns the current base DN for searches using search and
schema queries using get_attr_type_descr.
string get_bind_password_hash()
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.
string get_bound_dn()
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.
object get_cached_filter(string filter)
This is a wrapper for Protocols.LDAP.get_cached_filter which
passes the LDAP protocol version currently in use by this
connection.
If there's a parse error in the filter then a
Protocols.LDAP.FilterError is thrown as from
Protocols.LDAP.make_filter.
object get_default_filter()
Returns the ASN1 object parsed from the filter specified in the LDAP URL, or zero if the URL doesn't specify any filter.
If there's a parse error in the filter then a
Protocols.LDAP.FilterError is thrown as from
Protocols.LDAP.make_filter.
int get_option(int opttype)
option_typeLDAP_OPT_xxx
mapping(string:mixed) get_parsed_url()
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.
int get_protocol_version()
Return the LDAP protocol version in use.
array|int get_referrals()
Gets referrals.
Returns array of referrals or 0.
array(string) get_root_dse_attr(string attr)
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.
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.
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.
string get_scope()
Return the currently set scope as a string "base",
"one", or "sub".
multiset(string) get_supported_controls()
Returns a multiset containing the controls supported by the server. They are returned as object identifiers on string form. A working connection is assumed.
search
mapping Protocols.LDAP.client.info
Several information about code itself and about active connection too
inherit .protocol : protocol
object make_filter(string filter)
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.
If there's a parse error in the filter then a
Protocols.LDAP.FilterError is thrown as from
Protocols.LDAP.make_filter.
int modify(string dn, mapping(string:array(int(0..2)|string)) attropval)
The Modify Operation allows a client to request that a modification of an entry be performed on its behalf by a server.
dnThe distinguished name of modified entry.
attropvalThe mapping of attributes with requested operation and attribute's values.
attropval=([ attribute: ({operation, value1, value2, ...}) ])
Where operation is one of the following:
Add values listed to the given attribute, creating the attribute if necessary.
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.
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 1 on success, 0 otherwise.
The API change: the returning code was changed in Pike 7.3+ to follow his logic better.
int modifydn(string dn, string newrdn, int deleteoldrdn, string|void newsuperior)
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.
dnDN of source object
newrdnRDN of destination
deleteoldrdnThe parameter controls whether the old RDN attribute values are to be retained as attributes of the entry, or deleted from the entry.
newsuperiorIf present, this is the Distinguished Name of the entry which becomes the immediate superior of the existing entry.
Returns 1 on success, 0 otherwise.
The API change: the returning code was changed in Pike 7.3+ to follow his logic better.
mapping(string:mixed) parse_url(string ldapuri)
Compatibility alias for Protocols.LDAP.parse_ldap_url.
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)
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 a mapping of the requested attributes. It has the same
form as the response from result.fetch.
search
string|array(string) read_attr(string object_name, string attr, void|string filter, void|mapping(string:array(int|string)) controls)
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.
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.
read, get_root_dse_attr
void reset_options()
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.
result|int search(string|object|void filter, array(string)|void attrs, int|void attrsonly, void|mapping(string:array(int|string)) controls, void|int flags)
Search LDAP directory.
filterSearch 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.
attrsThe array of attribute names which will be returned by server for every entry.
attrsonlyThis 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.
controlsExtra 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.
| The index is the object identifier in string form for the
control type. There are constants in The mapping value is an array of two elements:
| ||||||
flagsBitfield with flags to control various behavior at the client
side of the search operation. See the
Protocol.LDAP.SEARCH_* constants for details.
Returns object LDAP.client.result on success, 0
otherwise.
The API change: the returning code was changed in Pike 7.3+ to follow his logic better.
result, result.fetch, read, get_supported_controls,
Protocols.LDAP.ldap_encode_string, Protocols.LDAP.make_filter
string set_basedn(string base_dn)
Sets the base DN for searches using search and schema queries
using get_attr_type_descr.
For compatibility, the old base DN is returned. However, if
LDAPv3 is used, the value is UTF-8 encoded. Use get_basedn
separately instead.
int set_option(int opttype, int value)
option_typeLDAP_OPT_xxx
valuenew value for option
int set_scope(int|string scope)
Sets value of scope for search operation.
scopeThe value can be one of the SCOPE_* constants or a
string "base", "one" or "sub".
Returns the SCOPE_* constant for the old scope.
int start_tls(void|SSL.Context context)
Requests that a SSL/TLS session be negotiated on the connection. If the connection is already secure, this call will fail.
contextan optional SSL.context object to provide to the SSL/TLS connection client.
Returns 1 on success, 0 otherwise.
int unbind()
Unbinds from the directory and close the connection.
Contains the result of a LDAP search.
LDAP.client.search, LDAP.client.result.fetch
int count_entries()
Returns the number of entries from the current cursor position to the end of the list.
LDAP.client.result.first, LDAP.client.result.next
Protocols.LDAP.client.result Protocols.LDAP.client.result(array(object) entries, int stuff, int flags)
You can't create instances of this object yourself. The only way to create it is via a search of a LDAP server.
int error_number()
Returns the error number in the search result.
error_string, server_error_string
string error_string()
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.
server_error_string, error_number
ResultEntry fetch(int|void idx)
Returns the current entry pointed to by the cursor.
indexThis optional argument can be used for direct access to an entry other than the one currently pointed to by the cursor.
The return value is a mapping describing the entry:
| An attribute in the entry. The value is an array containing
the returned attribute value(s) on string form, or a single
string if If |
| This special entry contains the object name of the entry as a distinguished name. This might also be a |
Zero is returned if the cursor is outside the valid range of entries.
Unless Protocols.LDAP.SEARCH_RETURN_DECODE_ERRORS was
given to search, a Charset.DecodeError is thrown if
there is an error decoding the DN or any attribute value.
It's undefined whether or not destructive operations on the
returned mapping will affect future fetch calls for the
same entry.
In Pike 7.6 and earlier, the special "dn" entry was
incorrectly returned in UTF-8 encoded form for LDAPv3
connections.
fetch_all
array(ResultEntry) fetch_all()
Convenience function to fetch all entries at once. The cursor isn't affected.
Returns an array where each element is the entry from the result. Don't be destructive on the returned value.
Unless Protocols.LDAP.SEARCH_RETURN_DECODE_ERRORS was
given to search, a Charset.DecodeError is thrown if
there is an error decoding the DN or any attribute value.
fetch
void first()
Initialized the result cursor to the first entry in the result list.
LDAP.client.result.next
string|Charset.DecodeError get_dn()
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.
In Pike 7.6 and earlier, this field was incorrectly returned in UTF-8 encoded form for LDAPv3 connections.
int next()
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.
LDAP.client.result.next
int num_entries()
Returns the number of entries.
LDAP.client.result.count_entries
string server_error_string()
Returns the error string from the server, or zero if the server didn't provide any.
error_string, error_number
int error_number()
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
.ldapfd->errno()
error_string, server_error_string
string error_string()
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.
server_error_string, error_number
int get_last_io_time()
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.
string server_error_string()
Returns the error string from the server, or zero if the server didn't provide any.
error_string, error_number
A LMTP server. It has been fairly well tested against Postfix client.
Actually this module is only an extention to the SMTP server.
Protocols.LMTP.Server Protocols.LMTP.Server(array(string) _domains, void|int port, void|string ip, function(:void) _cb_mailfrom, function(:void) _cb_rcptto, function(:void) _cb_data)
Create a receiving LMTP server. It implements RFC 2821, 2822, 2033 and 1854.
domainDomains 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.
portPort this server listen on
listenipIP on which server listen
cb_mailfromMailfrom 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.
cb_rcpttoSame as cb_mailfrom but called when a client sends a rcpt to.
cb_dataThis 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.
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; }
An implementation of the BSD lpd protocol (RFC 1179).
A client for communicating with printers and print spoolers that support the BSD lpd protocol (RFC 1179).
Protocols.LPD.client Protocols.LPD.client(string|void hostname, int|void portnum)
Create a new LPD client connection.
hostnameContains the hostname or ipaddress of the print host. if not provided, defaults to localhost.
portnumContains the port the print host is listening on. if not provided, defaults to port 515, the RFC 1179 standard.
int delete_job(string queue, int|void job)
Delete job job from printer queue.
Returns 1 on success, 0 otherwise.
string|int send_job(string queue, string job)
Send print job consisting of data job to printer queue.
Returns 1 if success, 0 otherwise.
int set_job_name(string name)
Sets the name of the print job to name.
int set_job_type(string type)
Set the type of job to be sent to the printer to type. Valid types are: text, postscript and raw.
int start_queue(string queue)
Start the queue queue if not already printing.
Returns 0 if unable to connect, 1 otherwise.
string|int status(string queue)
Check the status of queue queue.
Returns 0 on failure, otherwise returns the status response from the printer.
Nonblocking line-oriented I/O with support for reading literals.
void expect_literal(int length, function(string:void) callback)
Enter literal reading mode.
Sets literal_length and handle_literal().
literal_length, handle_literal()
void handle_command(string line)
Function called once for every received line.
function(string:void) Protocols.Line.imap_style.handle_line
This function will be called once for every line that is received.
This API is provided for backward compatibility; overload
handle_command() instead.
Protocols.Line.simple()->handle_command()
function(string:void) Protocols.Line.imap_style.handle_literal
If this variable has been set, literal_length bytes will be
accumulated, and this function will be called with the resulting data.
handle_literal() is one-shot, ie it will be cleared when it is called.
inherit simple : simple
int Protocols.Line.imap_style.literal_length
Length in bytes of the literal to read.
Simple nonblocking line-oriented I/O.
protected void close_callback()
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.
Protocols.Line.simple Protocols.Line.simple(Stdio.File con, int|void timeout)
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.
touch_time(), do_timeout()
void disconnect()
Disconnect the connection.
Pushes an end of file marker onto the send queue send_q.
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.
protected void do_timeout()
This function is called when a timeout occurrs.
Overload this function as appropriate.
The default action is to shut down the connection immediately.
create(), touch_time()
void handle_command(string line)
This function will be called once for every line that is received.
Overload this function as appropriate.
It will not be called if handle_data() has been set.
line will not contain the line separator.
handle_data()
function(string:void) Protocols.Line.simple.handle_data
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.
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.
handle_command()
protected constantstring Protocols.Line.simple.line_separator
The sequence separating lines from eachother. "\r\n" by default.
protected void read_callback(mixed ignored, string data)
Called when data has been received.
Overload as appropriate.
Calls the handle callbacks repeatedly until no more lines are available.
handle_data(), handle_command(), read_line()
protected string read_line()
Read a line from the input.
Returns 0 when more input is needed.
Returns the requested line otherwise.
The returned line will not contain the line separator.
handle_command(), line_separator
protected void send(string s)
Queue some data to send.
handle_command(), handle_data(), disconnect()
ADT.Queue Protocols.Line.simple.send_q
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.
send(), disconnect()
void touch_time()
Reset the timeout timer.
create(), do_timeout()
Nonblocking line-oriented I/O with support for sending SMTP-style codes.
mapping(int:string|array(string)) Protocols.Line.smtp_style.errorcodes
Mapping from return-code to error-message.
Overload this constant as apropriate.
inherit simple : simple
void send(int(100..999) code, array(string)|string|void lines)
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.
errorcodes
NNTP - The Network News Transfer Protocol.
Asynchronous NNTP protocol
void command(string cmd, function(:void)|void cb)
send a command to the server
the result code sent by the server
inherit protocolhelper : protocolhelper
inherit Stdio.File : sock
void readreturncode(function(:void) cb, mixed ... extra)
reads the server result code for last request used internally by command().
An NNTP client
string article(void|int|string x)
string body(void|int|string x)
Protocols.NNTP.client Protocols.NNTP.client(string|void server)
serverNNTP server to connect to.
Defaults to the server specified by
the environment variable NNTPSERVER.
Group Protocols.NNTP.client.current_group
The current news group.
Group go_to_group(string group)
Sets the current group to group.
string head(void|int|string x)
inherit protocol : protocol
array(Group) list_groups()
Returns a list of all active groups.
void set_group(Group o)
Sets the current news group to o.
Synchronous NNTP protocol
int command(string cmd)
send a command to the server
the result code sent by the server
string do_cmd_with_body(string cmd)
send a command that should return a message body.
the message body
int failsafe_command(string cmd)
send a command and require an ok response (200 series). throws an error if the command result was not success.
inherit protocolhelper : protocolhelper
inherit Stdio.FILE : sock
array(string) read_body_lines()
reads the message from the server as an array of lines
string readreturnbody()
reads the message from the server
int readreturncode()
reads the server result code for last request used internally by command().
void writebody(string s)
send the body of a message to the server.
helper class for protocol implementations.
protocol
string get_response_message()
gets the result message supplied by the server for the last response
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.
typedef mapping(HeaderIdentifier:string|int|array) Protocols.OBEX.Headers
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.
final constantint Protocols.OBEX.SETPATH_BACKUP
A flag for the REQ_SETPATH command indicating that the
parent directory should be selected
final constantint Protocols.OBEX.SETPATH_NOCREATE
A flag for the REQ_SETPATH command indicating that the
selected directory should not be created if it doesn't exist
Headers decode_headers(string h)
Deserialize a set of headers from wire format
string encode_headers(Headers h)
Serialize a set of headers to wire format
split_headers()
array(string) split_headers(string h, int chunklen)
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.
An identifier for a request or response header
constant Protocols.OBEX.HI_APPPARAM
Extended application request & response information
constant Protocols.OBEX.HI_AUTHCHALL
Authentication digest-challenge
constant Protocols.OBEX.HI_AUTHRESP
Authentication digest-response
constant Protocols.OBEX.HI_BODY
A chunk of the object body
constant Protocols.OBEX.HI_CONNID
An identifier used for OBEX connection multiplexing
constant Protocols.OBEX.HI_COUNT
Number of objects to transfer (used by REQ_CONNECT)
constant Protocols.OBEX.HI_CREATORID
Indicates the creator of an object
constant Protocols.OBEX.HI_DESCRIPTION
Text description of the object
constant Protocols.OBEX.HI_ENDOFBODY
The final chunk of the object body
constant Protocols.OBEX.HI_HTTP
Any HTTP 1.x header
constant Protocols.OBEX.HI_LENGTH
Length of the object transferred, in octets
constant Protocols.OBEX.HI_NAME
Name of the object (string)
constant Protocols.OBEX.HI_OBJCLASS
OBEX object class of object
constant Protocols.OBEX.HI_SESSPARAM
Parameters used in session commands/responses
constant Protocols.OBEX.HI_SESSSEQNR
Sequence number used in each OBEX packet for reliability
constant Protocols.OBEX.HI_TARGET
Name of service that operation is targeted to
constant Protocols.OBEX.HI_TIME
ISO 8601 timestamp (string)
constant Protocols.OBEX.HI_TYPE
Type of the object (IANA media type)
constant Protocols.OBEX.HI_WANUUID
Uniquely identifies the OBEX server
constant Protocols.OBEX.HI_WHO
Identifies the OBEX application (string)
A request opcode, for use with the client.do_request() function.
constant Protocols.OBEX.REQ_ABORT
Abort the request currently being processed
constant Protocols.OBEX.REQ_CONNECT
Establish a new OBEX connection
constant Protocols.OBEX.REQ_DISCONNECT
Terminate an OBEX connection
constant Protocols.OBEX.REQ_FINAL
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.
constant Protocols.OBEX.REQ_GET
Receive an object from the mobile devuce
constant Protocols.OBEX.REQ_PUT
Send an object to the mobile device
constant Protocols.OBEX.REQ_SESSION
Manage a session
constant Protocols.OBEX.REQ_SETPATH
Change the working directory
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 : Client
An OBEX client
ATclient
bool connect()
Establish a new connection using the REQ_CONNECT opcode to
negotiate transfer parameters
If the connection succeeds, 1 is returned. Otherwise, 0 is returned.
Protocols.OBEX.Client Protocols.OBEX.Client(Stdio.Stream _con)
Initialize the client by establishing a connection to the server at the other end of the provided transport stream
_conA stream for writing requests and reading back responses. Typically this is some kind of serial port.
bool disconnect()
Terminate a connection using the REQ_DISCONNECT opcode
If the disconnection succeeds, 1 is returned. Otherwise, 0 is returned.
array(int|Headers) do_abort(Headers|void headers)
Perform a REQ_ABORT request.
do_request()
array(int|Headers) do_get(Stdio.Stream data, Headers|void headers)
Perform a REQ_GET request.
dataA stream to write the body data to
headersHeaders for the request
See do_request(). The Headers do not contain any HI_BODY
headers, they are written to the data stream.
do_put(), do_request()
array(int|Headers) do_put(string|Stdio.Stream data, Headers|void extra_headers)
Perform a REQ_PUT request.
dataBody data to send, or a stream to read the data from
extra_headersAny additional headers to send (HI_LENGTH and HI_BODY
are generated by this function)
do_get(), do_request()
array(int|Headers) do_request(Request r, Headers|void headers, string|void extra_req)
Perform a request/response exchange with the server, including processing of headers and request splitting.
rRequest opcode
headersRequest headers
extra_reqAny request data that should appear before the headers, but after the opcode
An array with the response information
| Array | |
| An HTTP response code |
| Response headers |
low_do_request(), do_abort(), do_put(), do_get(),
do_setpath(), do_session()
array(int|Headers) do_session(Headers|void headers)
Perform a REQ_SESSION request.
do_request()
array(int|Headers) do_setpath(string path, int|void flags, Headers|void extra_headers)
Perform a REQ_SETPATH request.
pathThe directory to set as current working directory
| Go to the root directory |
| Go to the parent directory |
flagsLogical or of zero or more of SETPATH_BACKUP and SETPATH_NOCREATE
extra_headersAny additional request headers (the HI_NAME header is generated
by this function)
do_request()
array(int|string) low_do_request(Request r, string data)
Perform a request/response exchange with the server. No interpretation is preformed of either the request or response data, they are just passed literally.
rRequest opcode
dataRaw request data
An array with the response information
| Array | |
| An HTTP response code |
| Response data, if any |
do_request()
A list of named ports. This is similar to /etc/services.
Service|mixed `[](string name)
If name is not an indentifier in this module, return the first
matching protocol. This would be the first element in the array
returned by lookup
array(Service) lookup(string name)
Return all ports registered for the specified name This function also reads data from /etc/services if possible.
int port(string name)
Return the first port registered for the specified name (the lowest numbered tcp port, or if there is no tcp ports, the lowest numbered udp port)
constant Protocols.Ports.private_tcp
Contains all TCP ports assigned for private use as of RFC 1700
constant Protocols.Ports.private_udp
Contains all UDP ports assigned for private use as of RFC 1700
constant Protocols.Ports.tcp
Contains all non-private TCP port assignments as of RFC 1700 Extended with some non-official.
constant Protocols.Ports.udp
Contains all non-private UDP port assignments as of RFC 1700
A single service registration. Used as the return value for the
lookup method.
string Protocols.Ports.Service.name
int Protocols.Ports.Service.port
string Protocols.Ports.Service.protocol
string Protocols.Ports.Service.comment
Protocols.Ports.Service Protocols.Ports.Service(string name, int port, string protocol, string comment)
mapping(int:string) Protocols.SMTP.replycodes
A mapping(int:string) that maps SMTP return codes to english textual messages.
Asynchronous (nonblocking/event-oriented) email client class (this lets you send emails).
Protocols.SMTP.AsyncClient Protocols.SMTP.AsyncClient(void|string|object server, int|void port, function(:void)|void cb, mixed ... args)
Creates an SMTP mail client and connects it to the
the server provided. The server parameter may
either be a string with the hostname of the mail server,
or it may be a file object acting as a mail server.
If server is a string, then 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.
The callback will first be called when the connection is established
(cb(1, @args)) or fails to be established with an error. The
callback will also be called with an error if one occurs during the
delivery of mails.
In the error cases, the cb gets called the following ways:
cb(({ 1, errno(), error_string, int(0..1) direct }), @args);
cb(({ 0, smtp-errorcode, error_string, int(0..1) direct }), @args);
Where direct is 1 if establishment of the connection
failed.
inherit AsyncProtocol : AsyncProtocol
inherit ClientHelper : ClientHelper
void send_message(string from, array(string) to, string body, function(:void)|void cb, mixed ... args)
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.
When the message is successfully sent, the callback will be called
(cb(1, @args);).
When the message cannot be sent, cb will be called in one of the
following ways:
cb(({ 1, errno(), error_string, int(0..1) direct }), @args);
cb(({ 0, smtp-errorcode, error_string, int(0..1) direct }), @args);
where direct will be 1 if this particular message caused the
error and 0 otherwise.
simple_mail
void simple_mail(string to, string subject, string from, string msg, function(:void)|void cb, mixed ... args)
Sends an e-mail. Wrapper function that uses send_message.
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.
When the message is successfully sent, the callback will be called
(cb(1, @args);).
When the message cannot be sent, cb will be called in one of the
following ways:
cb(({ 1, errno(), error_string, int(0..1) direct }), @args);
cb(({ 0, smtp-errorcode, error_string, int(0..1) direct }), @args);
where direct will be 1 if this particular message caused the
error and 0 otherwise.
void verify(string addr, function(:void) cb, mixed ... args)
Verifies the mail address addr against the mail server.
The callback will be called with
cb(({ code, message }), @args);
where code and message are
| Array | |
| The numerical return code from the VRFY call. |
| The textual answer to the VRFY call. |
or
cb(({ 1, errno(), error_string, int(0..1) direct }), @args);
cb(({ 0, smtp-errorcode, error_string, int(0..1) direct }), @args);
with direct being 1 if this verify operation caused the
error when the message can't be verified
or when an error occurs.
Some mail servers does not answer truthfully to verification queries in order to prevent spammers and others to gain information about the mail addresses present on the mail server.
Synchronous (blocking) email class (this lets you send emails).
Protocols.SMTP.Client Protocols.SMTP.Client()
Protocols.SMTP.Client Protocols.SMTP.Client(Stdio.File server)
Protocols.SMTP.Client Protocols.SMTP.Client(string server, void|int port)
Creates an SMTP mail client and connects it to the
the server provided. The server parameter may
either be a string with the hostname of the mail server,
or it may be a file object acting as a mail server.
If server is a string, then 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 an exception if the client fails to connect to the mail server.
inherit ClientHelper : ClientHelper
inherit Protocol : Protocol
void send_message(string from, array(string) to, string body)
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.
simple_mail
If the mail server returns any other return code than 200-399 an exception will be thrown.
void simple_mail(string to, string subject, string from, string msg)
Sends an e-mail. Wrapper function that uses send_message.
Some important headers are set to:
"Content-Type: text/plain; charset=iso-8859-1" and
"Content-Transfer-Encoding: 8bit".
The "Date:" header is set to the current local time.
The "Message-Id" header is set to a Standards.UUID
followed by the hostname as returned by gethostname().
If gethostname() is not supported, it will be replaced
with the string "localhost".
If the mail server returns any other return code than 200-399 an exception will be thrown.
array(int|string) verify(string addr)
Verifies the mail address addr against the mail server.
| Array | |
| The numerical return code from the VRFY call. |
| The textual answer to the VRFY call. |
Some mail servers does not answer truthfully to verification queries in order to prevent spammers and others to gain information about the mail addresses present on the mail server.
If the mail server returns any other return code than 200-399 an exception will be thrown.
A helper class with functions useful when sending eMail.
protected string parse_addr(string addr)
Parses email addresses as the Protocols.SMTP client classes do.
Useful if emails should only be sent matching certain conditions etc..
string rfc2822date_time(int ts)
Return an RFC2822 date-time string suitable for the Date: header.
Class to store configuration variable for the SMTP server
int Protocols.SMTP.Configuration.checkdns
Verify sender domain for MX
int Protocols.SMTP.Configuration.checkemail
Lamme check email from validity
int Protocols.SMTP.Configuration.givedata
Give raw data and normal MIME data, if set to yes your cb_data function should take an extra string argument
int Protocols.SMTP.Configuration.maxrcpt
Maximum number of recipients (default 1000)
int Protocols.SMTP.Configuration.maxsize
Message max size
The low-level class for the SMTP server
function(string:mixed) Protocols.SMTP.Connection.logfunction
This function is called whenever the SMTP server logs something.
By default the log function is werror.
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
Protocols.SMTP.Server Protocols.SMTP.Server(array(string) _domains, void|int port, void|string ip, function(:void) _cb_mailfrom, function(:void) _cb_rcptto, function(:void) _cb_data)
Create a receiving SMTP server. It implements RFC 2821, 2822 and 1854.
domainDomains 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.
portPort this server listen on
listenipIP on which server listen
cb_mailfromMailfrom 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.
cb_rcpttoSame as cb_mailfrom but called when a client sends a rcpt to.
cb_dataThis 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.
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; }
SNMPv1 and v2c
constant Protocols.SNMP.ERROR_BADVALUE
Error badValue
constant Protocols.SNMP.ERROR_GENERROR
Error genError
constant Protocols.SNMP.ERROR_NOERROR
Error noError
constant Protocols.SNMP.ERROR_NOSUCHNAME
Error noSuchName
constant Protocols.SNMP.ERROR_READONLY
Error readOnly
constant Protocols.SNMP.ERROR_TOOBIG
Error tooBig
constant Protocols.SNMP.REQUEST_GET
PDU type Get
constant Protocols.SNMP.REQUEST_GETNEXT
PDU type GetNext
constant Protocols.SNMP.REQUEST_GET_RESPONSE
PDU type GetResponse
constant Protocols.SNMP.REQUEST_SET
PDU type Set
constant Protocols.SNMP.REQUEST_TRAP
PDU type Trap
A simple SNMP agent with support for SNMP Get requests
int clear_get_oid_callback(string oid)
clear the Get callback function for an Object Identifier
oidthe string object identifier, such as 1.3.6.1.4.1.132.2 or an asterisk (*) to indicate the default handler.
1 if the callback existed, 0 otherwise
int clear_set_oid_callback(string oid)
clear the Set callback function for an Object Identifier
oidthe string object identifier, such as 1.3.6.1.4.1.132.2 or an asterisk (*) to indicate the default handler.
1 if the callback existed, 0 otherwise
Protocols.SNMP.agent Protocols.SNMP.agent(int|void port, string|void addr)
create a new instance of the agent
portthe port number to listen for requests on
addrthe address to bind to for listening
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.
void|function(:void) get_get_oid_callback(string oid)
get the Get request callback function for an Object Identifier
oidthe string object identifier, such as 1.3.6.1.4.1.132.2 or an asterisk (*) to indicate the default handler
the function associated with oid, if any
void|function(:void) get_set_oid_callback(string oid)
get the Set request callback function for an Object Identifier
oidthe string object identifier, such as 1.3.6.1.4.1.132.2 or an asterisk (*) to indicate the default handler
the function associated with oid, if any
inherit "protocol" : "protocol"
void set_get_communities(array communities)
set the valid community strings for Get requests
communitiesan array of valid Get communities
send an empty array to disable Get requests
void set_get_oid_callback(string oid, function(:void) cb)
set the Get request callback function for an Object Identifier
oidthe 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.
cbthe 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 or 4 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.
If a fourth array element is returned, it should contain the OID
that the callback actually fetched (typically different from the
requested OID for REQUEST_GETNEXT requests). This is needed for
e.g. snmpwalk to work properly.
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.
void set_managers(array managers)
set the valid manager list for requests
managersan array of valid management hosts
send an empty array to disable all requests
void set_managers_only(int yesno)
enable manager access limits
yesno1 to allow only managers to submit requests 0 to allow any host to submit requests
default setting allows all requests from all hosts
void set_set_communities(array communities)
set the valid community strings for Set requests
communitiesan array of valid Set communities
send an empty array to disable Set requests
void set_set_oid_callback(string oid, function(:void) cb)
set the Set request callback function for an Object Identifier
oidthe 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.
cbthe 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.
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.
void set_threaded()
Run the agent event loop in a thread, if available.
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
Protocols.SNMP.protocol Protocols.SNMP.protocol(int|void rem_port, string|void rem_addr, int|void loc_port, string|void loc_addr)
create a new SNMP protocol object
rem_portrem_addrremote address and UDP port (optional)
loc_portloc_addrlocal address and UDP port (optional)
mapping decode_asn1_msg(mapping rawd)
decode ASN1 data, if garbaged ignore it
int get_nextrequest(array(string) varlist, string|void rem_addr, int|void rem_port)
GetNextRequest-PDU call
varlistan array of OIDs to GET
rem_addrrem_portremote address an UDP port to send request to (optional)
request ID
int get_request(array(string) varlist, string|void rem_addr, int|void rem_port)
GetRequest-PDU call
varlistan array of OIDs to GET
rem_addrrem_portremote address an UDP port to send request to (optional)
request ID
int get_response(mapping varlist, mapping origdata, int|void errcode, int|void erridx)
GetResponse-PDU call
varlista mapping containing data to return
|
| ||||||
|
| ||||||
|
| ||||||
origdataoriginal received decoded pdu that this response corresponds to
errcodeerror code
erridxerror index
request ID
inherit Stdio.UDP : snmp
mapping readmsg(int|float|void timeout)
return the whole SNMP message in raw format
private mapping readmsg_from_pool(int msgid)
read decoded message from pool
int set_request(mapping varlist, string|void rem_addr, int|void rem_port)
SetRequest-PDU call
varlista mapping of OIDs to SET
|
| ||||||
|
| ||||||
|
| ||||||
rem_addrrem_portremote address an UDP port to send request to (optional)
request ID
// 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");
string Protocols.SNMP.protocol.snmp_community
SNMP community string
should be set to the appropriate SNMP community before sending a request.
Set to "public" by default.
int Protocols.SNMP.protocol.snmp_version
SNMP version
currently version 1 and 2 are supported.
void to_pool(mapping rawd)
decode raw pdu message and place in message pool
int trap(mapping varlist, string oid, int type, int spectype, int ticks, string|void locip, string|void remaddr, int|void remport)
send an SNMP-v1 trap
varlista mapping of OIDs to include in trap
|
| ||||||
|
| ||||||
|
| ||||||
oidtypegeneric trap-type
spectypespecific trap-type
ticksuptime
lociporiginating ip address of the trap
remaddrremportaddress and UDP to send trap to
request id
Implements TELNET as described by RFC 764 and RFC 854
Also implements the Q method of TELNET option negotiation as specified by RFC 1143.
constant int Protocols.TELNET.AUTH_WHO_CLIENT
Client authenticating server
constant int Protocols.TELNET.AUTH_WHO_SERVER
Server authenticating client
constant int Protocols.TELNET.LFLOW_OFF
Disable remote flow control
constant int Protocols.TELNET.LFLOW_ON
Enable remote flow control
constant int Protocols.TELNET.LFLOW_RESTART_ANY
Restart output on any char
constant int Protocols.TELNET.LFLOW_RESTART_XON
Restart output only on XON
constant int Protocols.TELNET.TELQUAL_INFO
ENVIRON: informational version of IS
constant int Protocols.TELNET.TELQUAL_IS
option is...
constant int Protocols.TELNET.TELQUAL_NAME
AUTHENTICATION: client version of IS
constant int Protocols.TELNET.TELQUAL_REPLY
AUTHENTICATION: client version of IS
constant int Protocols.TELNET.TELQUAL_SEND
send option
inherit TelnetCodes : TelnetCodes
inherit Telopts : Telopts
Line-oriented TELNET protocol handler.
inherit protocol : protocol
Based on the generic TELNET protocol handler.
protected void setup()
Perform the initial TELNET handshaking for LINEMODE.
Line-oriented TELNET protocol handler with Stdio.Readline support.
Implements the Stdio.NonblockingStream API.
void close()
Close the connection.
Protocols.TELNET.Readline Protocols.TELNET.Readline(object f, function(mixed, string:void) r_cb, function(mixed|void:string) w_cb, function(mixed|void:void) c_cb, mapping callbacks, mixed|void new_id)
Creates a TELNET protocol handler, and sets its callbacks.
fFile to use for the connection.
r_cbFunction to call when data has arrived.
w_cbFunction to call when the send buffer is empty.
c_cbFunction to call when the connection is closed.
callbacksMapping with callbacks for the various TELNET commands.
new_idValue to send to the various callbacks.
inherit LineMode : LineMode
Based on the Line-oriented TELNET protocol handler.
void message(string s, void|int word_wrap)
Write a message.
function(mixed|void:void) query_close_callback()
function(mixed, string:void) query_read_callback()
function(mixed|void:string) query_write_callback()
Stdio.Readline Protocols.TELNET.Readline.readline
Stdio.Readline object handling the connection.
void set_blocking()
void set_close_callback(function(mixed|void:void) c_cb)
void set_nonblocking(function(mixed, string:void) r_cb, function(mixed|void:string) w_cb, function(mixed|void:void) c_cb)
Change the asynchronous I/O callbacks.
r_cbFunction to call when data has arrived.
w_cbFunction to call when the send buffer is empty.
c_cbFunction to call when the connection is closed.
create()
void set_prompt(string s)
Set the readline prompt.
void set_read_callback(function(mixed, string:void) r_cb)
void set_secret(int onoff)
Turn on/off echo mode.
void set_write_callback(function(mixed|void:string) w_cb)
mapping(string:int) tcgetattr()
Get current terminal attributes.
Currently only the following attributes are supported:
| Number of columns. |
| Number of rows. |
| Local character echo on ( |
| Canonical input on ( |
Using this function currently bypasses the Readline layer.
Stdio.File()->tcgetattr()
int tcsetattr(mapping(string:int) options, string|void when)
Set terminal attributes.
Currently only the following attributes are supported:
| Local character echo on ( |
| Canonical input on ( |
Using this function currently bypasses the Readline layer.
Stdio.File()->tcsetattr()
void write(string s)
Queues data to be sent to the other end of the connection.
sString to send.
Table of IAC-codes.
constant int Protocols.TELNET.TelnetCodes.ABORT
Abort process
constant int Protocols.TELNET.TelnetCodes.AO
abort output--but let prog finish
constant int Protocols.TELNET.TelnetCodes.AYT
are you there
constant int Protocols.TELNET.TelnetCodes.BREAK
break
constant int Protocols.TELNET.TelnetCodes.DM
data mark--for connect. cleaning
constant int Protocols.TELNET.TelnetCodes.DO
please, you use option
constant int Protocols.TELNET.TelnetCodes.DONT
you are not to use option
constant int Protocols.TELNET.TelnetCodes.EC
erase the current character
constant int Protocols.TELNET.TelnetCodes.EL
erase the current line
constant int Protocols.TELNET.TelnetCodes.EOR
end of record (transparent mode)
constant int Protocols.TELNET.TelnetCodes.GA
you may reverse the line
constant int Protocols.TELNET.TelnetCodes.IAC
interpret as command.
constant int Protocols.TELNET.TelnetCodes.IP
interrupt process--permanently
constant int Protocols.TELNET.TelnetCodes.NOP
nop
constant int Protocols.TELNET.TelnetCodes.SB
interpret as subnegotiation
constant int Protocols.TELNET.TelnetCodes.SE
end sub negotiation
constant int Protocols.TELNET.TelnetCodes.SUSP
Suspend process
constant int Protocols.TELNET.TelnetCodes.SYNCH
for telfunc calls
constant int Protocols.TELNET.TelnetCodes.WILL
I will use option
constant int Protocols.TELNET.TelnetCodes.WONT
I won't use option
constant int Protocols.TELNET.TelnetCodes.xEOF
End of file: EOF is already used...
Table of TELNET options.
constant int Protocols.TELNET.Telopts.TELOPT_3270REGIME
3270 regime
constant int Protocols.TELNET.Telopts.TELOPT_AUTHENTICATION
Authenticate
constant int Protocols.TELNET.Telopts.TELOPT_BINARY
8-bit data path
constant int Protocols.TELNET.Telopts.TELOPT_BM
byte macro
constant int Protocols.TELNET.Telopts.TELOPT_DET
data entry terminal
constant int Protocols.TELNET.Telopts.TELOPT_ECHO
echo
constant int Protocols.TELNET.Telopts.TELOPT_ENCRYPT
Encryption option
constant int Protocols.TELNET.Telopts.TELOPT_EOR
end or record
constant int Protocols.TELNET.Telopts.TELOPT_EXOPL
extended-options-list
constant int Protocols.TELNET.Telopts.TELOPT_LFLOW
remote flow control
constant int Protocols.TELNET.Telopts.TELOPT_LINEMODE
Linemode option
constant int Protocols.TELNET.Telopts.TELOPT_LOGOUT
force logout
constant int Protocols.TELNET.Telopts.TELOPT_NAMS
approximate message size
constant int Protocols.TELNET.Telopts.TELOPT_NAOCRD
negotiate about CR disposition
constant int Protocols.TELNET.Telopts.TELOPT_NAOFFD
negotiate about formfeed disposition
constant int Protocols.TELNET.Telopts.TELOPT_NAOHTD
negotiate about horizontal tab disposition
constant int Protocols.TELNET.Telopts.TELOPT_NAOHTS
negotiate about horizontal tabstops
constant int Protocols.TELNET.Telopts.TELOPT_NAOL
negotiate about output line width
constant int Protocols.TELNET.Telopts.TELOPT_NAOLFD
negotiate about output LF disposition
constant int Protocols.TELNET.Telopts.TELOPT_NAOP
negotiate about output page size
constant int Protocols.TELNET.Telopts.TELOPT_NAOVTD
negotiate about vertical tab disposition
constant int Protocols.TELNET.Telopts.TELOPT_NAOVTS
negotiate about vertical tab stops
constant int Protocols.TELNET.Telopts.TELOPT_NAWS
window size
constant int Protocols.TELNET.Telopts.TELOPT_NEW_ENVIRON
New - Environment variables
constant int Protocols.TELNET.Telopts.TELOPT_OLD_ENVIRON
Old - Environment variables
constant int Protocols.TELNET.Telopts.TELOPT_OUTMRK
output marking
constant int Protocols.TELNET.Telopts.TELOPT_RCP
prepare to reconnect
constant int Protocols.TELNET.Telopts.TELOPT_RCTE
remote controlled transmission and echo
constant int Protocols.TELNET.Telopts.TELOPT_SGA
suppress go ahead
constant int Protocols.TELNET.Telopts.TELOPT_SNDLOC
send location
constant int Protocols.TELNET.Telopts.TELOPT_STATUS
give status
constant int Protocols.TELNET.Telopts.TELOPT_SUPDUP
supdup protocol
constant int Protocols.TELNET.Telopts.TELOPT_SUPDUPOUTPUT
supdup output
constant int Protocols.TELNET.Telopts.TELOPT_TM
timing mark
constant int Protocols.TELNET.Telopts.TELOPT_TSPEED
terminal speed
constant int Protocols.TELNET.Telopts.TELOPT_TTYLOC
terminal location number
constant int Protocols.TELNET.Telopts.TELOPT_TTYPE
terminal type
constant int Protocols.TELNET.Telopts.TELOPT_TUID
TACACS user identification
constant int Protocols.TELNET.Telopts.TELOPT_X3PAD
X.3 PAD
constant int Protocols.TELNET.Telopts.TELOPT_XASCII
extended ascic character set
constant int Protocols.TELNET.Telopts.TELOPT_XDISPLOC
X Display Location
Implementation of the TELNET protocol.
protected void call_read_cb(string data)
Calls read_cb().
Specifically provided for overloading
protected mapping Protocols.TELNET.protocol.cb
Mapping containing extra callbacks.
void close()
Closes the connetion neatly
protected function(mixed|void:void) Protocols.TELNET.protocol.close_cb
Close callback.
Protocols.TELNET.protocol Protocols.TELNET.protocol(object f, function(mixed, string:void) r_cb, function(mixed|void:string) w_cb, function(mixed|void:void) c_cb, mapping callbacks, mixed|void new_id)
Creates a TELNET protocol handler, and sets its callbacks.
fFile to use for the connection.
r_cbFunction to call when data has arrived.
w_cbFunction to call when the send buffer is empty.
c_cbFunction to call when the connection is closed.
callbacksMapping with callbacks for the various TELNET commands.
new_idValue to send to the various callbacks.
protected void disable_write()
Turns off the write callback if apropriate.
protected int Protocols.TELNET.protocol.done
Indicates that connection should be closed
protected void enable_write()
Turns on the write callback if apropriate.
protected object Protocols.TELNET.protocol.fd
The connection.
protected void got_data(mixed ignored, string line)
Callback called when normal data has been received. This function also does most of the TELNET protocol parsing.
ignoredThe id from the connection.
sThe received data.
protected void got_oob(mixed ignored, string s)
Callback called when Out-Of-Band data has been received.
ignoredThe id from the connection.
sThe Out-Of-Band data received.
protected mixed Protocols.TELNET.protocol.id
Value to send to the callbacks.
protected array(int) Protocols.TELNET.protocol.remote_options
protected array(int) Protocols.TELNET.protocol.local_options
Negotiation states of all WILL/WON'T options. See RFC 1143 for a description of the states.
protected int Protocols.TELNET.protocol.nonblocking_write
Tells if we have set the nonblocking write callback or not.
function(mixed|void:void) query_close_callback()
function(mixed, string:void) query_read_callback()
function(mixed|void:string) query_write_callback()
protected function(mixed, string:void) Protocols.TELNET.protocol.read_cb
Read callback.
void send_DO(int option)
Starts negotiation to enable a TELNET option.
optionThe option to enable.
void send_DONT(int option)
Starts negotiation to disable a TELNET option.
optionThe option to disable.
protected void send_data()
Callback called when it is clear to send data over the connection. This function does the actual sending.
void send_synch()
Sends a TELNET synch command.
void set_close_callback(function(mixed|void:void) c_cb)
void set_nonblocking(function(mixed, string:void) r_cb, function(mixed|void:string) w_cb, function(mixed|void:void) c_cb)
Change the asynchronous I/O callbacks.
r_cbFunction to call when data has arrived.
w_cbFunction to call when the send buffer is empty.
c_cbFunction to call when the connection is closed.
create()
void set_read_callback(function(mixed, string:void) r_cb)
void set_write_callback(function(mixed|void:string) w_cb)
Sets the callback to be called when it is clear to send.
w_cbThe new write callback.
protected void setup()
Called when the initial setup is done.
Created specifically for overloading
protected int Protocols.TELNET.protocol.synch
Indicates whether we are in synch-mode or not.
protected string Protocols.TELNET.protocol.to_send
Data queued to be sent.
void write(string s)
Queues data to be sent to the other end of the connection.
sString to send.
protected function(mixed|void:string) Protocols.TELNET.protocol.write_cb
Write callback.
void write_raw(string s)
Queues raw data to be sent to the other end of the connection.
sString with raw telnet data to send.
This module implements the WebSocket protocol as described in RFC 6455.
WebSocket close status codes, as explained in the WebSocket protocol specification.
constant Protocols.WebSocket.CLOSE_BAD_DATA
constant Protocols.WebSocket.CLOSE_BAD_TYPE
constant Protocols.WebSocket.CLOSE_ERROR
constant Protocols.WebSocket.CLOSE_EXTENSION
constant Protocols.WebSocket.CLOSE_GONE_AWAY
constant Protocols.WebSocket.CLOSE_NONE
constant Protocols.WebSocket.CLOSE_NORMAL
constant Protocols.WebSocket.CLOSE_POLICY
constant Protocols.WebSocket.CLOSE_UNEXPECTED
WebSocket frame opcodes.
constant Protocols.WebSocket.FRAME_BINARY
constant Protocols.WebSocket.FRAME_CLOSE
constant Protocols.WebSocket.FRAME_CONTINUATION
constant Protocols.WebSocket.FRAME_PING
constant Protocols.WebSocket.FRAME_PONG
constant Protocols.WebSocket.FRAME_TEXT
Stdio.Buffer Protocols.WebSocket.Connection.buf
Output buffer
int Protocols.WebSocket.Connection.bufferedAmount
Number of bytes in the send buffer.
void close(void|CLOSE_STATUS reason)
Send a WebSocket connection close frame. The close callback will be called when the close handshake has been completed. No more frames can be sent after initiating the close handshake.
int connect(Standards.URI endpoint, void|mapping(string:string) extra_headers)
Connect to a remote WebSocket.
This method will send the actual HTTP request to switch
protocols to the server and once a HTTP 101 response is
returned, switch the connection to WebSockets and call the
onopen callback.
Protocols.WebSocket.Connection Protocols.WebSocket.Connection()
Create a WebSocket client
Protocols.WebSocket.Connection Protocols.WebSocket.Connection(Stdio.File|SSL.File f)
Create a WebSocket server out of the given Stdio.File-like object
Standards.URI Protocols.WebSocket.Connection.endpoint
Remote endpoint in client mode
protected Stdio.Buffer Protocols.WebSocket.Connection.http_buffer
Used in client mode to read server response.
protected void http_read(mixed id, string data)
Read callback for HTTP answer when we are in client mode and have requested an upgrade to WebSocket.
bool Protocols.WebSocket.Connection.masking
If true, all outgoing frames are masked.
function(CLOSE_STATUS, mixed:void) Protocols.WebSocket.Connection.onclose
This callback will be called once the WebSocket has been closed. No more frames can be sent or will be received after the close event has been triggered. This happens either when receiving a frame initiating the close handshake or after the TCP connection has been closed. Note that this is a deviation from the WebSocket API specification.
function(Frame, mixed:void) Protocols.WebSocket.Connection.onmessage
function(mixed:void) Protocols.WebSocket.Connection.onopen
Parser Protocols.WebSocket.Connection.parser
An instance of Parser used to parse incoming data.
void ping(void|string s)
Send a WebSocket ping frame.
protected void request_upgrade()
Write callback during the upgrade of a socket.
void send(Frame frame)
Send a WebSocket frame.
void send_binary(string(8bit) s)
Send a WebSocket binary frame.
void send_text(string s)
Send a WebSocket text frame.
void set_id(mixed id)
Set the id. It will be passed as last argument to all
callbacks.
STATE Protocols.WebSocket.Connection.state
Stdio.File|SSL.File Protocols.WebSocket.Connection.stream
The actual client connection.
constant Protocols.WebSocket.Connection.CLOSED
constant Protocols.WebSocket.Connection.CLOSING
constant Protocols.WebSocket.Connection.CONNECTING
constant Protocols.WebSocket.Connection.OPEN
Protocols.WebSocket.Frame Protocols.WebSocket.Frame(FRAME opcode, void|string|CLOSE_STATUS)
Protocols.WebSocket.Frame Protocols.WebSocket.Frame(FRAME_TEXT, string text)
Protocols.WebSocket.Frame Protocols.WebSocket.Frame(FRAME_BINARY, string(8bit) data)
Protocols.WebSocket.Frame Protocols.WebSocket.Frame(FRAME_CLOSE, CLOSE_STATUS reason)
Protocols.WebSocket.Frame Protocols.WebSocket.Frame(FRAME_PING, string(8bit) data)
Protocols.WebSocket.Frame Protocols.WebSocket.Frame(FRAME_PONG, string(8bit) data)
string Protocols.WebSocket.Frame.data
Data part of the frame. Valid for frames of type FRAME_BINARY,
FRAME_PING and FRAME_PONG.
void encode(Stdio.Buffer buf)
bool Protocols.WebSocket.Frame.fin
Set to 1 if this a final frame, i.e. the last frame of a
fragmented message or a non-fragmentation frame.
FRAME Protocols.WebSocket.Frame.opcode
CLOSE_STATUS Protocols.WebSocket.Frame.reason
Only exists for frames of type FRAME_CLOSE.
string Protocols.WebSocket.Frame.text
Only exists for frames of type FRAME_TEXT.
Parses WebSocket frames.
Stdio.Buffer Protocols.WebSocket.Parser.buf
Unparsed data.
void feed(string data)
Add more data to the internal parsing buffer.
Frame parse()
Parses and returns one WebSocket frame from the internal buffer. If
the buffer does not contain a full frame, 0 is returned.
Creates a simple HTTP Server. ws_cb will be called for all incoming
WebSocket connections. Its first argument are the list of protocols
requested by the client and the second argument the corresponding
Request object. The WebSocket connection handshake is completed
by calling Request.websocket_accept.
http_cb will be called for all other HTTP Requests or if ws_cb
is zero.
Protocols.HTTP.Server.Port
inherit Protocols.HTTP.Server.Port : Port
function(array(string), Request:void) Protocols.WebSocket.Request.cb
Protocols.WebSocket.Request Protocols.WebSocket.Request(function(array(string), Request:void) cb)
inherit Protocols.HTTP.Server.Request : Request
Connection websocket_accept(string protocol)
Calling websocket_accept completes the WebSocket connection
handshake. The protocol should be either 0 or a protocol
advertised by the client when initiating the WebSocket connection.
The returned connection object is in state Connection.OPEN.
Opens a simple HTTPS Server which supports WebSocket connections.
Port, Protocols.HTTP.Server.SSLPort
inherit Protocols.HTTP.Server.SSLPort : SSLPort
A Pike interface to the low-level X Window System.
This implements the on-wire protocol and some simple useful abstractions.
Keep track of X11 atoms
Keeps track of known atoms. Is inherited into Xlib.Display
object InternAtom(string name, function(:void)|void callback)
Looks up the atom in local cache. If it is not present, issue an asyncronous InternAtom request, and return 0
an abstract class used to provide features for implimenting X11 extensions. Provides no useful functionality on its own.
int init(object d)
initialize the extension.
dAn object of type Protocols.X.Xlib.Display
inherit Extension : Extension
void ShapeMask(object window, int xo, int yo, string kind, string operation, object|void source)
void ShapeOffset(object window, string kind, int xo, int yo)
void ShapeRectangles(object window, int xo, int yo, string kind, string operation, .Types.Rectangle|array(.Types.Rectangle) rectangles)
inherit Extension : Extension
Provides support for the X11 XTEST extension.
void XTestFakeInput(string event_type, int detail, int delay, object|void window, int|void xloc, int|void yloc)
Send a synthetic event to an X server.
event_typeType of event to send. Possible values: KeyPress: 2, KeyRelease: 3, ButtonPress: 4, ButtonRelease: 5, MotionNotify: 6
detailButton (for Button events) or Keycode (for Key events) to send
delayDelay before the X server simulates event. 0 indicates zero delay.
windowWindow object that a motion event occurrs in. If no window is provided, the root window will be used.
xlocFor motion events, this is the relative X distance or absolute X coordinates.
ylocFor motion events, this is the relative Y distance or absolute Y coordinates.
void XTestGrabControl(int impervious)
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.
imperviousA 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.
Protocols.X.Extensions.XTEST Protocols.X.Extensions.XTEST()
Create object.
inherit Extension : Extension
int init(object display)
Initialize the XTEST extension. Returns 1 if successful.
displayProtocols.X.Display object
int LookupCharacter(string str)
int LookupKeycode(int keysym, object display)
string LookupKeysym(int keysym, object display)
void ReleaseKey(int sym)
int _LookupCharacter(string str)
string _LookupKeysym(int keysym)
int Protocols.X.KeySyms.alt_gr
int Protocols.X.KeySyms.num_lock
int Protocols.X.KeySyms.shift
int Protocols.X.KeySyms.control
int Protocols.X.KeySyms.caps_lock
int Protocols.X.KeySyms.meta
int Protocols.X.KeySyms.alt
int Protocols.X.KeySyms.super
int Protocols.X.KeySyms.hyper
mapping Protocols.X.KeySyms.attributes
void makeKeysymtoKeycode(object display)
mapping Protocols.X.KeySyms.stringtokeysyms
Varios X11 on-wire requests
int Protocols.X.Requests.AllocColor.red
int Protocols.X.Requests.AllocColor.green
int Protocols.X.Requests.AllocColor.blue
int Protocols.X.Requests.AllocColor.colormap
inherit request : request
inherit request : request
int Protocols.X.Requests.Bell.percent
int Protocols.X.Requests.ChangeGC.gc
mapping Protocols.X.Requests.ChangeGC.attributes
inherit request : request
int Protocols.X.Requests.ChangeProperty.mode
int Protocols.X.Requests.ChangeProperty.window
int Protocols.X.Requests.ChangeProperty.property
int Protocols.X.Requests.ChangeProperty.type
int Protocols.X.Requests.ChangeProperty.format
string|array(int) Protocols.X.Requests.ChangeProperty.data
inherit request : request
int Protocols.X.Requests.ChangeWindowAttributes.window
mapping Protocols.X.Requests.ChangeWindowAttributes.attributes
inherit request : request
int Protocols.X.Requests.ClearArea.exposures
int Protocols.X.Requests.ClearArea.window
int Protocols.X.Requests.ClearArea.x
int Protocols.X.Requests.ClearArea.y
int Protocols.X.Requests.ClearArea.width
int Protocols.X.Requests.ClearArea.height
inherit request : request
inherit FreeRequest : FreeRequest
mapping Protocols.X.Requests.ConfigureWindow.attributes
inherit request : request
object Protocols.X.Requests.CopyArea.gc
object Protocols.X.Requests.CopyArea.area
object Protocols.X.Requests.CopyArea.src
object Protocols.X.Requests.CopyArea.dst
int Protocols.X.Requests.CopyArea.x
int Protocols.X.Requests.CopyArea.y
inherit request : request
inherit CopyArea : CopyArea
int Protocols.X.Requests.CopyPlane.plane
int Protocols.X.Requests.CreateColormap.cid
int Protocols.X.Requests.CreateColormap.alloc
inherit request : request
int Protocols.X.Requests.CreateColormap.window
int Protocols.X.Requests.CreateColormap.visual
int Protocols.X.Requests.CreateGC.gc
int Protocols.X.Requests.CreateGC.drawable
mapping Protocols.X.Requests.CreateGC.attributes
inherit request : request
int Protocols.X.Requests.CreateGlyphCursor.cid
int Protocols.X.Requests.CreateGlyphCursor.sourcefont
int Protocols.X.Requests.CreateGlyphCursor.maskfont
int Protocols.X.Requests.CreateGlyphCursor.sourcechar
int Protocols.X.Requests.CreateGlyphCursor.maskchar
int Protocols.X.Requests.CreateGlyphCursor.forered
int Protocols.X.Requests.CreateGlyphCursor.foregreen
int Protocols.X.Requests.CreateGlyphCursor.foreblue
int Protocols.X.Requests.CreateGlyphCursor.backred
int Protocols.X.Requests.CreateGlyphCursor.backgreen
int Protocols.X.Requests.CreateGlyphCursor.backblue
inherit request : request
int Protocols.X.Requests.CreatePixmap.depth
int Protocols.X.Requests.CreatePixmap.pid
int Protocols.X.Requests.CreatePixmap.drawable
int Protocols.X.Requests.CreatePixmap.width
int Protocols.X.Requests.CreatePixmap.height
inherit request : request
mapping Protocols.X.Requests.CreateWindow.attributes
int Protocols.X.Requests.CreateWindow.x
int Protocols.X.Requests.CreateWindow.y
int Protocols.X.Requests.CreateWindow.width
int Protocols.X.Requests.CreateWindow.height
int Protocols.X.Requests.CreateWindow.borderWidth
int Protocols.X.Requests.CreateWindow.c_class
int Protocols.X.Requests.CreateWindow.visual
int Protocols.X.Requests.CreateWindow.depth
inherit request : request
int Protocols.X.Requests.CreateWindow.wid
int Protocols.X.Requests.CreateWindow.parent
inherit request : request
int Protocols.X.Requests.DeleteProperty.window
int Protocols.X.Requests.DeleteProperty.property
Base class used by extensions
int Protocols.X.Requests.ExtensionRequest.type
int Protocols.X.Requests.ExtensionRequest.code
string Protocols.X.Requests.ExtensionRequest.data
function(:void) Protocols.X.Requests.ExtensionRequest.handle_reply
function(:void) Protocols.X.Requests.ExtensionRequest.handle_error
int Protocols.X.Requests.FillPoly.drawable
int Protocols.X.Requests.FillPoly.gc
int Protocols.X.Requests.FillPoly.shape
int Protocols.X.Requests.FillPoly.coordMode
inherit request : request
array Protocols.X.Requests.FillPoly.points
inherit FreeRequest : FreeRequest
array Protocols.X.Requests.FreeColors.colors
int Protocols.X.Requests.FreeColors.colormap
int Protocols.X.Requests.FreeColors.plane_mask
inherit request : request
inherit FreeRequest : FreeRequest
inherit FreeRequest : FreeRequest
inherit FreeRequest : FreeRequest
int Protocols.X.Requests.FreeRequest.id
inherit request : request
int Protocols.X.Requests.GetAtomName.atom
inherit request : request
int Protocols.X.Requests.GetKeyboardMapping.first
int Protocols.X.Requests.GetKeyboardMapping.num
inherit request : request
int Protocols.X.Requests.GetProperty.delete
int Protocols.X.Requests.GetProperty.window
int Protocols.X.Requests.GetProperty.property
int Protocols.X.Requests.GetProperty.type
int Protocols.X.Requests.GetProperty.longOffset
int Protocols.X.Requests.GetProperty.longLength
inherit request : request
int Protocols.X.Requests.GrabButton.ownerEvents
int Protocols.X.Requests.GrabButton.grabWindow
int Protocols.X.Requests.GrabButton.eventMask
int Protocols.X.Requests.GrabButton.pointerMode
int Protocols.X.Requests.GrabButton.keyboardMode
int Protocols.X.Requests.GrabButton.confineTo
int Protocols.X.Requests.GrabButton.cursor
int Protocols.X.Requests.GrabButton.button
int Protocols.X.Requests.GrabButton.modifiers
inherit request : request
int Protocols.X.Requests.ImageText16.drawable
int Protocols.X.Requests.ImageText16.gc
int Protocols.X.Requests.ImageText16.x
int Protocols.X.Requests.ImageText16.y
string Protocols.X.Requests.ImageText16.str
inherit request : request
int Protocols.X.Requests.ImageText8.drawable
int Protocols.X.Requests.ImageText8.gc
int Protocols.X.Requests.ImageText8.x
int Protocols.X.Requests.ImageText8.y
string Protocols.X.Requests.ImageText8.str
inherit request : request
inherit request : request
int Protocols.X.Requests.InternAtom.onlyIfExists
string Protocols.X.Requests.InternAtom.name
inherit request : request
int Protocols.X.Requests.ListProperties.window
inherit ResourceReq : ResourceReq
int Protocols.X.Requests.OpenFont.fid
string Protocols.X.Requests.OpenFont.name
inherit request : request
int Protocols.X.Requests.PolyFillRectangle.drawable
int Protocols.X.Requests.PolyFillRectangle.gc
inherit request : request
array Protocols.X.Requests.PolyFillRectangle.rectangles
inherit PolyPoint : PolyPoint
int Protocols.X.Requests.PolyPoint.coordMode
int Protocols.X.Requests.PolyPoint.drawable
int Protocols.X.Requests.PolyPoint.gc
array(object) Protocols.X.Requests.PolyPoint.points
inherit request : request
string Protocols.X.Requests.PutImage.data
int Protocols.X.Requests.PutImage.depth
int Protocols.X.Requests.PutImage.width
int Protocols.X.Requests.PutImage.height
int Protocols.X.Requests.PutImage.dst_x
int Protocols.X.Requests.PutImage.dst_y
int Protocols.X.Requests.PutImage.left_pad
int Protocols.X.Requests.PutImage.format
int Protocols.X.Requests.PutImage.drawable
int Protocols.X.Requests.PutImage.gc
inherit request : request
inherit request : request
string Protocols.X.Requests.QueryExtension.name
int Protocols.X.Requests.QueryTextExtents.font
string Protocols.X.Requests.QueryTextExtents.str
inherit request : request
inherit request : request
inherit ResourceReq : ResourceReq
int AllocColor(int r, int g, int b)
void FreeColor(int pixel)
object Protocols.X.Types.Colormap.visual
mapping Protocols.X.Types.Colormap.alloced
inherit XResource : XResource
inherit XResource : XResource
object CopyArea(object gc, object src, object area, int x, int y)
object CopyArea_req(object gc, object src, object area, int x, int y)
object CreateGC(mapping|void attributes)
object CreateGC_req()
object CreatePixmap(int width, int height, int depth)
object CreatePixmap_req(int width, int height, int depth)
void DrawLine(object gc, int coordMode, object ... points)
object DrawLine_req(int gc, int coordMode, array(object) points)
void FillPoly(object gc, int shape, int coordMode, array(object) points)
object FillPoly_req(int gc, int shape, int coordMode, array(object) p)
void FillRectangles(object gc, object ... r)
object FillRectangles_req(int gc, array(object) r)
void ImageText16(object gc, int x, int y, string str)
object ImageText16_req(int gc, int x, int y, string str)
void ImageText8(object gc, int x, int y, string str)
object ImageText8_req(int gc, int x, int y, string str)
void PutImage(object gc, int depth, int tx, int ty, int width, int height, string data, int|void format)
object PutImage_req(object gc, int depth, int tx, int ty, int width, int height, string data)
inherit XResource : XResource
object CreateGlyphCursor(int sourcechar, array(int)|void foreground, array(int)|void background)
mapping(string:int) QueryTextExtents(string str)
mapping(string:int) QueryTextExtents16(string str)
object QueryTextExtents_req(string str)
inherit XResource : XResource
void ChangeGC(mapping attributes)
object ChangeGC_req(mapping attributes)
mapping(string:mixed) GetGCValues()
inherit XResource : XResource
mapping(string:mixed) Protocols.X.Types.GC.values
inherit Drawable : Drawable
int Protocols.X.Types.Point.x
int Protocols.X.Types.Point.y
int Protocols.X.Types.Rectangle.width
int Protocols.X.Types.Rectangle.height
int Protocols.X.Types.Rectangle.x
int Protocols.X.Types.Rectangle.y
object Protocols.X.Types.RootWindow.defaultColorMap
int Protocols.X.Types.RootWindow.whitePixel
int Protocols.X.Types.RootWindow.blackPixel
int Protocols.X.Types.RootWindow.pixWidth
int Protocols.X.Types.RootWindow.pixHeight
int Protocols.X.Types.RootWindow.mmWidth
int Protocols.X.Types.RootWindow.mmHeight
int Protocols.X.Types.RootWindow.minInstalledMaps
int Protocols.X.Types.RootWindow.maxInstalledMaps
int Protocols.X.Types.RootWindow.backingStore
int Protocols.X.Types.RootWindow.saveUnders
int Protocols.X.Types.RootWindow.rootDepth
mapping Protocols.X.Types.RootWindow.depths
inherit Window : Window
int Protocols.X.Types.Visual.c_class
int Protocols.X.Types.Visual.bitsPerRGB
int Protocols.X.Types.Visual.colorMapEntries
int Protocols.X.Types.Visual.redMask
int Protocols.X.Types.Visual.greenMask
int Protocols.X.Types.Visual.blueMask
int Protocols.X.Types.Visual.depth
inherit XResource : XResource
void ChangeAttributes(mapping m)
object ChangeAttributes_req(mapping m)
void ChangeProperty(object property, object type, int format, array(int)|string data)
object ChangeProperty_req(object property, object type, int format, array(int)|string data)
void ClearArea(int x, int y, int width, int height, int|void exposures)
object ClearArea_req(int x, int y, int width, int height, int exposures)
void Configure(mapping m)
object Configure_req(mapping m)
object CreateColormap(object visual, int|void alloc)
object CreateSimpleWindow(int x, int y, int width, int height, int border_width, int border, int background)
object CreateWindow(int x, int y, int width, int height, int border_width, mapping|void attributes, object|void visual, int|void d, int|void c_class)
object CreateWindow_req(int x, int y, int width, int height, int border_width, int depth, object visual)
int DeselectInput(string ... types)
mapping GetProperty(object property, object|void type)
object GetProperty_req(object property, object|void type)
void GrabButton(int button, int modifiers, string ... types)
object GrabButton_req(int button, int modifiers, array(string) types)
array ListProperties()
object ListProperties_req()
void Lower()
void Map()
object Map_req()
void Raise()
int SelectInput(string ... types)
object SelectInput_req()
void ShapeMask(string kind, int xo, int yo, string operation, Pixmap mask)
void ShapeOffset(string kind, int xo, int yo)
void ShapeRectangles(string kind, int xo, int yo, string operation, array(Rectangle) rectangles)
void Unmap()
object Unmap_req()
int Protocols.X.Types.Window.currentInputMask
mapping(string:array(array)) Protocols.X.Types.Window.event_callbacks
inherit Drawable : Drawable
inherit .KeySyms : KeySyms
void set_event_callback(string type, function(:void) f, int|void priority)
A resorce in the X-server Most will automatically free the resource in the server when all references is gone in your application
void Free()
object Protocols.X.Types.XResource.display
int Protocols.X.Types.XResource.id
int Protocols.X.Types.XResource.autofree
Handles Image.Image to XImage conversions.
The XImage class behaves more or less exactly like an
Image.Image, but it keeps itself synchronized with the server if
so needed.
object MakeShapeMask(object in, object alpha)
Convert an alpha channel to a shaped-window extension mask
void ShapedWindowImage(object in, object color, object|void alpha, int|void contour)
Make the window in display the image, with a mask shaped
according to alpha, and optionally with a colored border aound the
mask.
Wrapper for Image.Image that keeps track of the modifications done.
A pixmap (much like XImage, but stored in the server)
inherit XImage : XImage
A version of XImage that redraws itself at need
inherit XImage : XImage
Image.Colortable allocate_colortable()
int Protocols.X.XImage.XImage.best
int Protocols.X.XImage.XImage.depth
int Protocols.X.XImage.XImage.bpp
function(:void) Protocols.X.XImage.XImage.converter
int Protocols.X.XImage.XImage.linepad
int Protocols.X.XImage.XImage.swapbytes
int Protocols.X.XImage.XImage.rmask
int Protocols.X.XImage.XImage.gmask
int Protocols.X.XImage.XImage.bmask
object Protocols.X.XImage.XImage.window
object Protocols.X.XImage.XImage.root
object Protocols.X.XImage.XImage.visual
object Protocols.X.XImage.XImage.colormap
Image.Colortable Protocols.X.XImage.XImage.ccol
object Protocols.X.XImage.XImage.dgc
inherit Image_wrapper : Image_wrapper
int Protocols.X.XImage.XImage.offset_x
int Protocols.X.XImage.XImage.offset_y
void redraw(int x, int y, int width, int height)
void set_drawable(object w)
void set_offset(int x, int y)
void set_window(object w)
Various tools that are higher level than raw X, but are lower level than widgets.
A simple button. Steals and processes mousebutton events Can be inherited and then expanded the button_pressed function
int Protocols.X.XTools.Button.pressed
int Protocols.X.XTools.Button.inside
int Protocols.X.XTools.Button.button
void button_exposed(mapping event)
mapping button_pressed(mapping event)
mapping button_released(mapping event)
Protocols.X.XTools.Button Protocols.X.XTools.Button(object w, int|void b)
mapping window_entered(mapping event)
mapping window_left(mapping event)
Implementations of various X11 calls.
The representation of a X display.
Keeps the connection to the X server and various other information needed to use X11.
void Bell(int volume)
object Bell_req(int volume)
object CreateGlyphCursor(object sourcefont, int sourcechar, object|void maskfont, int|void maskchar, array(int)|void foreground, array(int)|void background)
object CreateGlyphCursor_req(object sourcefont, object maskfont, int sourcechar, int maskchar, array(int) foreground, array(int) background)
object DefaultRootWindow()
object OpenFont(string name)
object OpenFont_req(string name)
int Protocols.X.Xlib.Display.imageByteOrder
int Protocols.X.Xlib.Display.bitmapBitOrder
int Protocols.X.Xlib.Display.bitmapScanlineUnit
int Protocols.X.Xlib.Display.bitmapScanlinePad
array blocking_request(.Requests.request req)
mapping(string:.Extensions.Extension) Protocols.X.Xlib.Display.extensions
All extensions supported by the server and this module
array Protocols.X.Xlib.Display.formats
inherit Stdio.File : File
inherit .Atom.atom_manager : atom_manager
inherit id_manager : id_manager
array Protocols.X.Xlib.Display.key_mapping
int Protocols.X.Xlib.Display.majorVersion
int Protocols.X.Xlib.Display.minorVersion
The protocol major and minor version reported by the server
int Protocols.X.Xlib.Display.minKeyCode
int Protocols.X.Xlib.Display.maxKeyCode
int Protocols.X.Xlib.Display.maxRequestSize
int Protocols.X.Xlib.Display.motionBufferSize
int open(string|void display)
Connect to the specified display. The default is to use the value of the environment variable DISPLAY
int Protocols.X.Xlib.Display.release
Server release number
array Protocols.X.Xlib.Display.roots
int Protocols.X.Xlib.Display.screen_number
void send_async_request(.Requests.request req, function(:void) callback)
string Protocols.X.Xlib.Display.vendor
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.
The XML-RPC <dateTime.iso8601> datatype does not assume any
time zone, but local time is always used in the conversion to
Calendar objects.
Call decode_call(string xml_input)
Decodes a XML-RPC representation of a function call and returns a
Call object.
Call
array|Fault decode_response(string xml_input, int|void boolean)
Decodes a XML-RPC representation of a response and returns an
array containing response values, or a Fault object.
Fault
string encode_call(string method_name, array params)
Encodes a function call with the name method_name and the arguments
params and returns the XML-RPC string representation.
string encode_response(array params)
Encodes a response containing the multiple values in params and
returns the XML-RPC string representation.
string encode_response_fault(int fault_code, string fault_string)
Encodes a response fault containing a fault_code and a
fault_string and returns the XML-RPC string representation.
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.
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;
Represents a function call made to a XML-RPC server.
decode_call()
Protocols.XMLRPC.Call Protocols.XMLRPC.Call(string method_name, array params)
int Protocols.XMLRPC.Call.method_name
Represents <methodName> in the XML-RPC standard.
string Protocols.XMLRPC.Call.method_name
array Protocols.XMLRPC.Call.params
array Protocols.XMLRPC.Call.params
Represents <params> in the XML-RPC standard where all datatypes have been converted to equivalent or similar datatypes in Pike.
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.
> 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"
})
})
string|Standards.URI Protocols.XMLRPC.Client.url
int|void Protocols.XMLRPC.Client.boolean
Protocols.XMLRPC.Client Protocols.XMLRPC.Client(string|Standards.URI url, int|void boolean)
Represents a fault response which can be one of the return values from a XML-RPC function call.
decode_response()
Protocols.XMLRPC.Fault Protocols.XMLRPC.Fault(int fault_code, string fault_string)
int Protocols.XMLRPC.Fault.fault_code
Represents faultCode in the XML-RPC standard.
int Protocols.XMLRPC.Fault.fault_code
string Protocols.XMLRPC.Fault.fault_string
int Protocols.XMLRPC.Fault.fault_string
Represents faultString in the XML-RPC standard.