13. Protocols |
Module Protocols.HTTP |
string Protocols.HTTP.filename_to_type(string filename)
string Protocols.HTTP.extension_to_type(string extension)
Looks up the file extension in a table to return a suitable MIME type.
string Protocols.HTTP.http_date(int time)
Makes a time notification suitable for the HTTP protocol. @param time The time in seconds since the 00:00:00 UTC, January 1, 1970 @returns The date in the HTTP standard date format. Example : Thu, 03 Aug 2000 05:40:39 GMT
int Protocols.HTTP.http_decode_date(string date)
Decode a HTTP date to seconds since 1970 (UTC) @returns zero (UNDEFINED) if the given string isn't a HTTP date
string Protocols.HTTP.http_decode_string(string what)
mapping(string:string|array(string)) Protocols.HTTP.http_decode_urlencoded_query(string query, void|mapping dest)
Decodes an URL-encoded query into a mapping.
.Query Protocols.HTTP.do_method(string method, string|Standards.URI url, void|mapping(string:int|string) query_variables, void|mapping(string:string|array(string)) request_headers, void|Protocols.HTTP.Query con, void|string data)
Low level HTTP call method.
The HTTP method to use, e.g. "GET"
.
The URL to perform method on. Should be a complete URL,
including protocol, e.g. "https://pike.ida.liu.se/"
.
Calls http_encode_query and appends the result to the URL.
The HTTP headers to be added to the request. By default the headers User-agent, Host and, if needed by the url, Authorization will be added, with generated contents. Providing these headers will override the default. Setting the value to 0 will remove that header from the request.
Old connection object.
Data payload to be transmitted in the request.
.Query Protocols.HTTP.get_url(string|Standards.URI url, void|mapping(string:int|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.
.Query Protocols.HTTP.put_url(string|Standards.URI url, void|string file, void|mapping(string:int|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.
.Query Protocols.HTTP.delete_url(string|Standards.URI url, void|mapping(string:int|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.
array(string) Protocols.HTTP.get_url_nice(string|Standards.URI url, void|mapping(string:int|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.
string Protocols.HTTP.get_url_data(string|Standards.URI url, void|mapping(string:int|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.
.Query Protocols.HTTP.post_url(string|Standards.URI url, mapping(string:int|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.
array(string) Protocols.HTTP.post_url_nice(string|Standards.URI url, mapping(string:int|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.
string Protocols.HTTP.post_url_data(string|Standards.URI url, mapping(string:int|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.
string Protocols.HTTP.unentity(string s)
Helper function for replacing HTML entities with the corresponding iso-8859-1 characters.
All characters aren't replaced, only those with corresponding iso-8859-1 characters.
string Protocols.HTTP.http_encode_query(mapping(string:int|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"
string Protocols.HTTP.http_encode_string(string in)
This protects all odd - see http_encode_query() - characters for transfer in HTTP.
Do not use this function to protect URLs, since
it will protect URL characters like '/'
and '?'
.
The string to encode
The HTTP encoded string
string Protocols.HTTP.http_encode_cookie(string f)
Encode the specified string in as to the HTTP cookie standard.
The string to encode.
The HTTP cookie encoded string.
CLASS Protocols.HTTP.HeaderParser |
Fast HTTP header parser.
CLASS Protocols.HTTP.Query |
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.ida.liu.se", 80, "HEAD / HTTP/1.0"); return -1; }
int errno
Errno copied from the connection.
int ok
Tells if the connection is successfull.
mapping headers
Headers as a mapping. All header names are in lower case, for convinience.
string protocol
Protocol string, ie "HTTP/1.0"
.
int status
string status_desc
Status number and description (eg 200
and "ok"
).
mapping hostname_cache
Set this to a global mapping if you want to use a cache, prior of calling *request().
Protocols.HTTP.Query set_callbacks(function request_ok, function request_fail, mixed ... extra)
Protocols.HTTP.Query async_request(string server, int port, string query)
Protocols.HTTP.Query async_request(string server, int port, string query, mapping headers, string|void data)
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
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.
int `()()
Wait for connection to complete.
Returns 1
on successfull connection, 0
on failure.
string data(int|void max_length)
Gives back the data as a string.
int downloaded_bytes()
Gives back the number of downloaded bytes.
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.
array cast("array")
|
mapping cast("mapping")
The header mapping ORed with the following mapping.
|
string cast("string")
Gives back the answer as a string.
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()
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()
void async_fetch(function callback, mixed ... extra)
Fetch all data in background.
CLASS Protocols.HTTP.Session |
int 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
mapping default_headers
Default HTTP headers.
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.
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.
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.
array(string) get_cookies(Standards.URI|SessionURL for_url, void|int(0..1) 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.
mapping hostname_cache
Cache of hostname to IP lookups. Given to and used by the Query objects.
int|float 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.
int maximum_connections_per_server
Maximum number of connections to the same server. Used only by async requests. Defaults to 10 connections.
int 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.
int maximum_connection_reuse
Maximum times a connection is reused. Defaults to 1000000. <2 means no reuse at all.
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.
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.
Request get_url(URL url, void|mapping query_variables)
Request post_url(URL url, mapping 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.
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 query_variables)
string post_url_data(URL url, mapping 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.
Request async_get_url(URL url, void|mapping query_variables, function callback_headers_ok, function callback_data_ok, function callback_fail, mixed ... callback_arguments)
Request async_put_url(URL url, void|string file, void|mapping query_variables, function callback_headers_ok, function callback_data_ok, function callback_fail, mixed ... callback_arguments)
Request async_delete_url(URL url, void|mapping query_variables, function callback_headers_ok, function callback_data_ok, function callback_fail, mixed ... callback_arguments)
Request async_post_url(URL url, mapping query_variables, function callback_headers_ok, function callback_data_ok, function callback_fail, mixed ... callback_arguments)
Sends a HTTP GET, POST, PUT or DELETE request to the server in the URL asynchroneously, and call the corresponding callbacks when result arrives (or not). The callbacks will receive the created Request object as first argument, then the given callback_arguments , if any.
callback_headers_ok is called when the HTTP request has received headers.
callback_data_ok is called when the HTTP request has been received completely, data and all.
callback_fail is called when the HTTP request has failed, on a TCP/IP or DNS level, or has received a forced timeout.
The created Request object is returned.
CLASS Protocols.HTTP.Session.Request |
Request
Query con
Raw connection object
Standards.URI url_requested
URL requested (set by prepare_method). This will update according to followed redirects.
int 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.
function(string:mixed) 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.
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).
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
Request wait()
Wait for the request thread to finish.
0 upon failure, or the called object upon success.
do_thread
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.
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
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.
CLASS Protocols.HTTP.Session.SessionURL |
Class to store URL+referer
inherit Standards.URI : URI
URL referer
the referer to this URL
void 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
Module Protocols.HTTP.Server |
CLASS Protocols.HTTP.Server.Port |
The simplest server possible. Binds a port and calls a callback with Server.Request objects.
void Protocols.HTTP.Server.Port(function(.Request:void) callback)
void Protocols.HTTP.Server.Port(function(.Request:void) callback, int portno, void|string interface)
void close()
Closes the HTTP port.
CLASS Protocols.HTTP.Server.Request |
string raw
raw unparsed full request (headers and body)
string body_raw
raw unparsed body of the request (raw minus request line and headers)
string request_raw
full request line (request_type + full_query + protocol )
string request_type
HTTP request method, eg. POST, GET, etc.
string full_query
full resource requested, including attached GET query
string not_query
resource requested minus any attached query
string query
query portion of requested resource, starting after the first "?"
string protocol
request protocol and version, eg. HTTP/1.0
mapping(string:string|array(string)) request_headers
all headers included as part of the HTTP request, ie content-type.
mapping(string:string|array(string)) variables
all variables included as part of a GET or POST request.
mapping(string:string) cookies
cookies set by client
mapping misc
external use only
int send_timeout_delay
send timeout (no activity for this period with data in send buffer) in seconds, default is 180
int connection_timeout_delay
connection timeout, delay until connection is closed while waiting for the correct headers:
void response_and_finish(mapping m, function|void _log_cb)
return a properly formatted response to the HTTP client
Contains elements for generating a response to the client.
|
CLASS Protocols.HTTP.Server.SSLPort |
The simplest SSL server possible. Binds a port and calls a callback with Request objects.
void Protocols.HTTP.Server.SSLPort(function(Request:void) _callback, void|int _portno, void|string _interface, void|string key, void|string|array certificate)
Create a HTTPS (HTTP over SSL) server.
The function run when a request is received. takes one argument of type Request .
The port number to bind to, defaults to 443.
The interface address to bind to.
An optional SSL secret key, provided in binary format, such as that created by Standards.PKCS.RSA.private_key() .
An optional SSL certificate or chain of certificates with the host certificate first, provided in binary format.
void close()
Closes the HTTP port.
void new_connection()
The port accept callback
CLASS Protocols.HTTP.Server.SSLPort.MySSLPort |
inherit SSL.sslport : sslport
void set_default_keycert()
void set_key(string skey)
void set_certificate(string|array certificate)
Module SSL |
CLASS SSL.alert |
Alert package.
inherit .packet : packet
void SSL.alert(int level, int description, int version, string|void message, mixed|void trace)
CLASS SSL.connection |
SSL packet layer. SSL.connection inherits SSL.handshake, and in addition to the state in the handshake super class, it contains the current read and write states, packet queues. This object is responsible for receiving and sending packets, processing handshake packets, and providing a clear text packages for some application.
inherit .handshake : handshake
inherit ADT.Queue : alert
inherit ADT.Queue : urgent
inherit ADT.Queue : application
void set_alert_callback(function(object: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.
object recv_packet(string data)
Low-level receive handler. Returns a packet, an alert, or zero if more data is needed to get a complete packet.
void send_packet(object 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.
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.
void send_close()
Initiate close.
int send_streaming_data(string 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.
string|int got_data(string|int s)
Main receive handler. Returns a string of received application data, or 1 if a close was received, or -1 if an error occured.
This function is intended to be called from an i/o read callback.
CLASS SSL.context |
Keeps the state that is shared by all SSL-connections for one server (or one port). It includes policy configuration, a server certificate, the server's private key(s), etc. It also includes the session cache.
Crypto.RSA rsa
The server's private key
int auth_level
Policy for client authentication. One of SSL.Constants.AUTHLEVEL_none , SSL.Constants.AUTHLEVEL_ask and SSL.Constants.AUTHLEVEL_require .
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 Tools.PEM.Msg first.
Note that it is presumed that the issuer will also be trusted by the server. See trusted_issuers for details on specifying trusted issuers.
If empty, the server will accept any client certificate whose issuer is trusted by the server.
int 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.
array(string) get_authorities()
Get the list of allowed authorities. See set_authorities .
void set_trusted_issuers(array(array(string)) i)
Sets the list of trusted certificate issuers.
An array of certificate chains whose root is self signed (ie a root issuer), and whose final certificate is an issuer that we trust. The root of the certificate should be first certificate in the chain. The string is a DER-encoded certificate, which typically must be decoded using MIME.decode_base64 or Tools.PEM.Msg first.
If this array is left empty, and the context is set to verify certificates, a certificate chain must have a root that is self signed.
array(array(string)) get_trusted_issuers()
Get the list of trusted issuers. See set_trusted_issuers .
int verify_certificates
Determines whether certificates presented by the peer are verified, or just accepted as being valid.
Crypto.RSA long_rsa
Crypto.RSA short_rsa
Temporary, non-certified, private keys, used with a server_key_exchange message. The rules are as follows:
If the negotiated cipher_suite has the "exportable" property, and short_rsa is not zero, send a server_key_exchange message with the (public part of) the short_rsa key.
If the negotiated cipher_suite does not have the exportable property, and long_rsa is not zero, send a server_key_exchange message with the (public part of) the long_rsa key.
Otherwise, dont send any server_key_exchange message.
Crypto.DSA dsa
Servers dsa key.
.Cipher.DHParameters dh_params
Parameters for dh keyexchange.
function(int:string) 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.
array(string) certificates
The server's certificate, or a chain of X509.v3 certificates, with the server's certificate first and root certificate last.
array(int) preferred_auth_methods
For client authentication. Used only if auth_level is AUTH_ask or AUTH_require.
array(int) preferred_suites
Cipher suites we want the server to support, best first.
void rsa_mode()
Set preferred_suites to RSA based methods.
void dhe_dss_mode()
Set preferred_suites to DSS based methods.
array(int) preferred_compressors
Always ({ COMPRESSION_null })
int use_cache
Non-zero to enable cahing of sessions
int 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.
.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.
.session new_session()
Create a new session.
void record_session(.session s)
Add a session to the cache (if caching is enabled).
void purge_session(object s)
Remove a session from the cache.
CLASS SSL.handshake |
SSL.handshake keeps the state relevant for SSL handshaking. This includes a pointer to a context object (which doesn't change), various buffers, a pointer to a session object (reuse or created as appropriate), and pending read and write states being negotiated.
Each connection will have two sets or read and write state: The current read and write states used for encryption, and pending read and write states to be taken into use when the current keyexchange handshake is finished.
string client_random
string server_random
Random cookies, sent and received with the hello-messages.
int(-1..1) handle_handshake(int type, string data, string 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 hadshake is in progress, 1 if handshake is finished, and -1 if a fatal error occured. It uses the send_packet() function to trasnmit packets.
CLASS SSL.https |
Dummy HTTPS server
inherit SSL.sslport : sslport
CLASS SSL.packet |
SSL Record Layer. Handle formatting and parsing of packets.
CLASS SSL.session |
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.
string identity
Identifies the session to the server
int compression_algorithm
Always COMPRESSION_null.
int cipher_suite
Constant defining a choice of keyexchange, encryption and mac algorithm.
.Cipher.CipherSpec cipher_spec
Information about the encryption method derived from the cipher_suite.
int ke_method
Key exchange method, also derived from the cipher_suite.
string master_secret
48 byte secret shared between the client and the server. Used for deriving the actual keys.
mapping cert_data
information about the certificate in use by the peer, such as issuing authority, and verification status.
array(string) peer_certificate_chain
void set_cipher_suite(int suite, int version)
Sets the proper authentication method and cipher specification for the given cipher suite and verison .
void set_compression_method(int compr)
Sets the compression method. Currently only COMPRESSION_null is supported.
array(string) generate_keys(string client_random, string server_random, array(int) version)
Generates keys appropriate for the SSL version given in version , based on the client_random and server_random .
|
array(.state) new_server_states(string client_random, string server_random, array(int) version)
Computes a new set of encryption states, derived from the client_random, server_random and master_secret strings.
|
array(.state) new_client_states(string client_random, string server_random, array(int) version)
Computes a new set of encryption states, derived from the client_random, server_random and master_secret strings.
|
CLASS SSL.sslfile |
Interface similar to Stdio.File .
Handles blocking and nonblocking mode.
Handles callback mode in an arbitrary backend (also in blocking mode).
Read and write operations might each do both reading and writing. In callback mode that means that installing either a read or a write callback might install both internally. It also means that reading in one thread while writing in another doesn't work.
Callback changing operations like set_blocking and set_nonblocking aren't atomic.
Apart from the above, thread safety/atomicity characteristics are retained.
Blocking characterstics are retained for all functions.
Connection init (create ) and close (close ) can do both reading and writing.
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.
void SSL.sslfile(Stdio.File stream, SSL.context ctx, int|void is_client, int|void is_blocking)
Create a connection over stream , which should be an open socket or pipe. ctx is the SSL context. If is_client is set then a client-side connection is started, server-side otherwise. If is_blocking is set then the stream is initially set in blocking mode, nonblocking mode otherwise.
The backend used by stream is taken over and restored after the connection is closed (see close ). The callbacks and id in stream are overwritten.
mapping get_peer_certificate_info()
returns peer certificate information, if any.
array get_peer_certificates()
returns the peer certificate chain, if any.
int close(void|string how, void|int clean_close)
Close the connection. Both the read and write ends are always
closed - the argument how is only for Stdio.File
compatibility and must be either "rw"
or 0
.
If clean_close is set then close messages are exchanged to shut down the SSL connection but not the underlying stream. It may then continue to be used for other communication afterwards. The default is to send a close message and then close the stream without waiting for a response.
Returns zero and sets the errno to System.EBADF if the connection already is closed. Other I/O errors are thrown.
In nonblocking mode the stream isn't closed right away and the backend will be used for a while afterwards. If there's an I/O problem it won't be signalled immediately.
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.
Stdio.File shutdown()
Shut down the SSL connection without sending any more packets. The underlying stream is returned if the connection isn't shut down already and if a nonclean close hasn't been requested.
string read(void|int length, void|int(0..1) 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.
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.
I/O errors from both reading and writing might occur in blocking mode.
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.
void set_nonblocking(void|function(mixed:void) read, void|function(void|mixed:void) write, void|function(void|mixed:void) close, void|function(void|mixed:void) read_oob, void|function(void|mixed:void) write_oob, void|function(void|mixed:void) 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.
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.
int errno()
void set_alert_callback(function(object:void) alert)
Install a function that will be called when an alert packet is received. It doesn't affect the callback mode - it's called both from backends and from within normal function calls like read and write .
function(object:void) query_alert_callback()
void set_accept_callback(function(object: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 sslfile 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.
function(object:int) query_accept_callback()
void set_read_callback(function(mixed:int) read)
Install a function to be called when data is available.
function(mixed:int) query_read_callback()
void set_write_callback(function(void|mixed:int) write)
Install a function to be called when data can be written.
function(void|mixed:int) query_write_callback()
void set_close_callback(function(void|mixed:int) close)
Install a function to be called when the connection is closed.
It will only be called if the connection is closed cleanly with the proper messages. Any other way of closing the it is considered an error to avoid truncation attacks.
function(void|mixed:int) query_close_callback()
void set_id(mixed id)
mixed query_id()
void set_backend(Pike.Backend backend)
Set the backend used for the file callbacks.
Pike.Backend query_backend()
Return the backend used for the file callbacks.
string query_address(int|void arg)
Stdio.File query_stream()
Return the underlying stream.
Avoid any temptation to do
destruct(sslfile_obj->query_stream())
. That almost
certainly creates more problems than it solves.
SSL.connection query_connection()
Return the SSL connection object.
SSL.context query_context()
Return the SSL context object.
CLASS SSL.sslport |
Interface similar to Stdio.Port.
inherit Stdio.Port : socket
inherit .context : context
inherit ADT.Queue : accept_queue
CLASS SSL.state |
A connection switches from one set of state objects to another, one or more times during its lifetime. Each state object handles a one-way stream of packets, and operates in either decryption or encryption mode.
object session
Information about the used algorithms.
.Cipher.MACAlgorithm mac
Message Authentication Code
.Cipher.CipherAlgorithm crypt
Encryption or decryption object.
Gmp.mpz seq_num
64-bit sequence number.
Alert|.packet decrypt_packet(.packet packet, int version)
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, int version)
Encrypts a packet (including deflating and MAC-generation).
Module SSL.Cipher |
Encryption and MAC algorithms used in SSL.
string SSL.Cipher.prf(string secret, string label, string seed, int len)
ADT.struct SSL.Cipher.rsa_sign(object context, string cookie, ADT.struct struct)
int(0..1) SSL.Cipher.rsa_verify(object context, string cookie, ADT.struct struct, Gmp.mpz signature)
ADT.struct SSL.Cipher.dsa_sign(object context, string cookie, ADT.struct struct)
ADT.struct SSL.Cipher.anon_sign(object context, string cookie, ADT.struct struct)
CLASS SSL.Cipher.CipherAlgorithm |
Cipher algorithm interface.
this_program set_encrypt_key(string)
this_program set_decrypt_key(string)
Set the key used for encryption/decryption, and enter encryption mode.
int(0..) block_size()
Return the block size for this crypto.
CLASS SSL.Cipher.MACAlgorithm |
Message Authentication Code interface.
CLASS SSL.Cipher.CipherSpec |
Cipher specification.
CLASS SSL.Cipher.MACsha |
MAC using SHA.
string hash_raw(string data)
string hash(object packet, Gmp.mpz seq_num)
string hash_master(string data, string|void s)
void SSL.Cipher.MACsha(string|void s)
CLASS SSL.Cipher.MACmd5 |
MAC using MD5.
inherit MACsha : MACsha
CLASS SSL.Cipher.MAChmac_sha |
string hash(object packet, Gmp.mpz seq_num)
void SSL.Cipher.MAChmac_sha(string|void s)
CLASS SSL.Cipher.MAChmac_md5 |
inherit MAChmac_sha : MAChmac_sha
void SSL.Cipher.MAChmac_md5(string|void s)
CLASS SSL.Cipher.DES |
inherit Crypto.CBC : CBC
CLASS SSL.Cipher.DES3 |
inherit Crypto.CBC : CBC
CLASS SSL.Cipher.DHParameters |
Diffie-Hellman parameters.
Gmp.mpz p
Gmp.mpz g
Gmp.mpz order
Module SSL.Constants |
Protocol constants
ENUM SSL.Constants.KeyExchangeType |
Key exchange methods.
constant SSL.Constants.KE_rsa
Rivest-Shamir-Adelman
constant SSL.Constants.KE_dh
Diffie-Hellman
ENUM SSL.Constants.CompressionType |
Compression methods.
constant SSL.Constants.COMPRESSION_null
No compression.
Module Protocols.LysKOM |
CLASS Protocols.LysKOM.Connection |
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 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.
int protocol_level
string session_software
string software_version
Description of the connected server.
void Protocols.LysKOM.Connection(string server)
void Protocols.LysKOM.Connection(string server, mapping options)
The options argument is a mapping with the following members:
|
CLASS Protocols.LysKOM.Session |
object user
This variable contains the Protocols.LysKOM.Session.Person that is logged in.
void Protocols.LysKOM.Session(string server)
void Protocols.LysKOM.Session(string server, mapping options)
Initializes the session object, and opens a connection to that server.
options is a mapping of options:
|
Connection
Text text(int no)
Returns the text no .
Person person(int no)
Returns the person no .
Conference conference(int no)
Returns conference number 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 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.
object create_person(string name, string password)
Create a person, which will be logged in. returns the new person object
this_program logout()
Logouts from the server. returns the called object
object create_text(string subject, string body, mapping options)
object create_text(string subject, string body, mapping options, function 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:
|
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|void send_message(string textstring, mapping options)
Sends a message.
options is a mapping that may contain:
|
void register_async_message_callback(function(int:void) cb)
CLASS Protocols.LysKOM.Session.AuxItemInput |
Undocumented
inherit ProtocolTypes.AuxItemInput : AuxItemInput
CLASS Protocols.LysKOM.Session.AuxItems |
Undocumented
CLASS Protocols.LysKOM.Session.Text |
All variables in this class is read only.
Undocumented
int no
The text number, as spicified to create .
object err
Undocumented
void Protocols.LysKOM.Session.Text(string textnumber)
Initializes a Text object.
void mark_as_read()
Undocumented.
mixed prefetch_text
mixed prefetch_stat
mixed lines
mixed characters
mixed clear_stat
mixed aux_items
Undocumented
string text
The actual text (or body if you wish).
string subject
The message subject.
string author
The author of the text.
mixed misc
Misc info, including what conferences the message is posted to.
Needs a more complete description.
int marks
The number of marks on this text.
mixed creation_time
The time the text was created on the server.
CLASS Protocols.LysKOM.Session.Membership |
All variables in this class is read only.
object last_time_read
int(0..255) priority
int last_text_read
array(int) read_texts
object added_at
multiset(string) type
int position
object conf
int number_unread()
void query_read_texts()
array(object) unread_texts()
CLASS Protocols.LysKOM.Session.Person |
int no
void Protocols.LysKOM.Session.Person(int no)
mixed prefetch_stat
mixed prefetch_conf
mixed prefetch_membership
Undocumented
object error
Text user_area
mixed username
mixed privileges
mixed flags
mixed last_login
mixed total_time_present
mixed sessions
mixed created_lines
mixed created_bytes
mixed read_texts
mixed no_of_text_fetches
mixed created_persons
mixed created_confs
mixed first_created_local_no
mixed no_of_created_texts
mixed no_of_marks
mixed no_of_confs
mixed unread
int(0..0) clear_membership
mixed membership
Undocumented
CLASS Protocols.LysKOM.Session.Conference |
void Protocols.LysKOM.Session.Conference(int no)
Module Protocols.LysKOM.ProtocolTypes |
Data types as defined by the LysKOM protocol specification.
Module Protocols.LysKOM.Request |
This module contains nice abstraction for calls into the server. They are named "call", "async_call" or "async_cb_call", depending on how you want the call to be done.
CLASS Protocols.LysKOM.Request._Request |
This is the main request class. All lyskom request classes inherit this class.
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.
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 `()()
Wait for the call to finish.
int(0..1) ok
Tells if the call has executed ok
object error
How the call failed.
The call has completed if (ok||error)
.
Module Protocols.DNS |
Domain Name System RFC 1035
void Protocols.DNS.async_ip_to_host(string ip, function cb, mixed ... cba)
void Protocols.DNS.async_host_to_ip(string host, function cb, mixed ... cba)
void Protocols.DNS.async_get_mx_all(string host, function cb, mixed ... cba)
void Protocols.DNS.async_get_mx(string host, function cb, mixed ... cba)
array Protocols.DNS.gethostbyname(string host)
array Protocols.DNS.gethostbyaddr(string host)
string Protocols.DNS.get_mx(string host)
string Protocols.DNS.get_primary_mx(string host)
ENUM Protocols.DNS.ResourceClass |
Resource classes
constant Protocols.DNS.C_IN
Class Internet
constant Protocols.DNS.C_CS
Class CSNET (Obsolete)
constant Protocols.DNS.C_CH
Class CHAOS
constant Protocols.DNS.C_HS
Class Hesiod
constant Protocols.DNS.C_ANY
Class ANY
ENUM Protocols.DNS.EntryType |
Entry types
constant Protocols.DNS.T_A
Type - host address
constant Protocols.DNS.T_NS
Type - authoritative name server
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_CNAME
Type - canonical name for an alias
constant Protocols.DNS.T_SOA
Type - start of a zone of authority
constant Protocols.DNS.T_MB
Type - mailbox domain name (EXPERIMENTAL)
constant Protocols.DNS.T_MG
Type - mail group member (EXPERIMENTAL)
constant Protocols.DNS.T_MR
Type - mail rename domain name (EXPERIMENTAL)
constant Protocols.DNS.T_NULL
Type - null RR (EXPERIMENTAL)
constant Protocols.DNS.T_WKS
Type - well known service description
constant Protocols.DNS.T_PTR
Type - domain name pointer
constant Protocols.DNS.T_HINFO
Type - host information
constant Protocols.DNS.T_MINFO
Type - mailbox or mail list information
constant Protocols.DNS.T_MX
Type - mail exchange
constant Protocols.DNS.T_TXT
Type - text strings
constant Protocols.DNS.T_AAAA
Type - IPv6 address record (RFC 1886, deprecated)
constant Protocols.DNS.T_LOC
Type - Location Record (RFC 1876)
constant Protocols.DNS.T_SRV
Type - Service location record (RFC 2782)
constant Protocols.DNS.T_A6
Type - IPv6 address record (RFC 2874, incomplete support)
CLASS Protocols.DNS.protocol |
Low level DNS protocol
string mkquery(string|mapping dnameorquery, int|void cl, int|void type)
create a DNS query PDU
record class such as Protocols.DNS.C_IN
query 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.ida.liu.se string q=Protocols.DNS.protocol()->mkquery("pike.ida.liu.se", Protocols.DNS.C_IN, Protocols.DNS.T_A);
CLASS Protocols.DNS.server |
Implements a Domain Name Service (DNS) server.
inherit protocol : protocol
inherit Stdio.UDP : udp
mapping reply_query(mapping query, mapping udp_data)
Reply to a query (stub).
Parsed query.
Raw UDP data.
Overload this function to implement the proper lookup.
Returns 0
(zero) on failure, or a result mapping on success:
|
CLASS Protocols.DNS.client |
Synchronous DNS client.
inherit protocol : protocol
void Protocols.DNS.client()
void Protocols.DNS.client(void|string|array server, void|int|array domain)
mapping do_sync_query(string s)
perform a syncronous query
result 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.ida.liu.se", C_IN, T_A));
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 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 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.
|
string get_primary_mx(string hostname)
Queries the primary mx for the host.
Returns the hostname of the primary mail exchanger.
Module Protocols |
Module Protocols.IRC |
CLASS Protocols.IRC.Client |
void Protocols.IRC.Client(string server, void|mapping(string:mixed) options)
The IRC server to connect to.
An optional mapping with additional IRC client options.
|
void close()
Closes the connection to the server.
CLASS Protocols.IRC.Person |
Abstract class for a person.
string nick
User nickname, e.g. "Mirar"
.
string user
User name, e.g. "mirar"
.
string ip
User domain, e.g. "mistel.idonex.se"
.
int last_action
Time of last action, represented as posix time.
CLASS Protocols.IRC.Channel |
Abstract class for a IRC channel.
string name
The name of the channel.
Module Protocols.LDAP |
CLASS Protocols.LDAP.client |
Contains the client implementation of the LDAP protocol. All of the version 2 protocol features are implemented but only the base parts of the version 3.
inherit .protocol : protocol
mapping info
Several information about code itself and about active connection too
void Protocols.LDAP.client()
void Protocols.LDAP.client(string url)
void Protocols.LDAP.client(string 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.
LDAP server URL in form
"ldap://hostname/basedn?attrlist?scope?ext"
TLS context of connection
LDAP.client.bind , LDAP.client.search
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:
The distinguished name (DN) of an entry aginst which will be made authentication.
Password used for authentication.
Third form allows specify the version of LDAP protocol used by connection to the LDAP server.
Only 2
or 3
can be entered.
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 unbind()
Unbinds from the directory and close the connection.
int delete(string dn)
Deletes entry from the LDAP server.
The 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.
int compare(string dn, array(string) aval)
Compares given attribute value with one in the directory.
The distinguished name of compared entry.
The mapping of compared attributes and theirs values.
Returns 1
on success, 0
otherwise.
The API change: the returning code was changed in Pike 7.3+ to follow his logic better.
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
The Distinguished Name of the entry to be added.
The mapping of attributes and their values that make up the content of the entry being added.
Returns 1
on success, 0
otherwise.
The API change: the returning code was changed in Pike 7.3+ to follow his logic better.
object|int search(string|void filter, array(string)|void attrs, int|void attrsonly)
Search LDAP directory.
Search filter used when searching directory objects.
The array of attribute names which will be returned by server. for every entry.
The flag causes server return only attribute name but not the attribute values.
Returns object LDAP.client.result on success, 0
otherwise.
For syntax of search filter see at RFC 1960 (http://community.roxen.com/developers/idocs/rfc/rfc1960.html).
The API change: the returning code was changed in Pike 7.3+ to follow his logic better.
LDAP.client.result , LDAP.client.result.fetch
string set_basedn(string base_dn)
base DN for search
int set_scope(int|string scope)
Sets value of scope for search operation.
Value can be integer or its corresponding string value. 0: base, 1: one, 2: sub
int set_option(int opttype, int value)
LDAP_OPT_xxx
new value for option
int get_option(int opttype)
LDAP_OPT_xxx
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.
DN of source object
RDN of destination
The parameter controls whether the old RDN attribute values are to be retained as attributes of the entry, or deleted from the entry.
If 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.
int modify(string dn, mapping(string:array(mixed)) attropval)
The Modify Operation allows a client to request that a modification of an entry be performed on its behalf by a server.
The distinguished name of modified entry.
The mapping of attributes with requested operation and attribute's values.
attropval=([ attribute: ({operation, value1, value2, ...}) ])
where operation is one of the following: 0 (LDAP_OPERATION_ADD) - add values listed to the given attribute, creating the attribute if necessary 1 (LDAP_OPERATION_DELETE) - delete values listed from the given attribute, removing the entire attribute if no values are listed, or if all current values of the attribute are listed for deletion 2 (LDAP_OPERATION_REPLACE) - replace all existing values of the given attribute with the new values listed, creating the attribute if it did not already exist. A replace with no value will delete the entire attribute if it exists, and is ignored if the attribute does not exist
Returns 1
on uccess, 0
otherwise.
The API change: the returning code was changed in Pike 7.3+ to follow his logic better.
array|int get_referrals()
Gets referrals.
Returns array of referrals or 0
.
mapping|int parse_url(string ldapuri)
LDAP URL
CLASS Protocols.LDAP.client.result |
Contains the result of a LDAP search.
LDAP.client.search , LDAP.client.result.fetch
object|int Protocols.LDAP.client.result(array rawres, int|void stuff)
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 error number of search result.
LDAP.client.result.error_string
string error_string()
Returns error description of search result.
LDAP.client.result.error_number
int num_entries()
Returns the number of entries.
LDAP.client.result.count_entries
int count_entries()
Returns the number of entries from current cursor possition till end of the list.
LDAP.client.result.first , LDAP.client.result.next
int|mapping(string:array(string)) fetch(int|void idx)
Returns a mapping with an entry for each attribute. Each entry is an array of values of the attribute.
Optional argument can be used for direct access to the entry other then currently pointed by cursor.
string get_dn()
Returns distinguished name (DN) of the current entry in the result list. Notice that this is the same as fetch()->dn[0].
void first()
Initialized the result cursor to the first entry in the result list.
LDAP.client.result.next
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
CLASS Protocols.LDAP.protocol |
inherit Stdio.File : ldap
int error_number()
Returns error number of last transaction.
LDAP.protocol.error_string
string error_string()
Returns error description of search result.
LDAP.protocol.error_number
Module Protocols.SMTP |
mapping(int:string) Protocols.SMTP.replycodes
A mapping(int:string) that maps SMTP return codes to english textual messages.
CLASS Protocols.SMTP.Client |
inherit Protocol : Protocol
void Protocols.SMTP.Client()
void Protocols.SMTP.Client(Stdio.File server)
void 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 witht the hostnam of the mail server, or it may be a file object acting as a mail server. If server is a string, than an optional port parameter may be provided. If no port parameter is provided, port 25 is assumed. If no parameters at all is provided the client will look up the mail host by searching for the DNS MX record.
Throws an exception if the client fails to connect to the mail server.
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"
. "Date:"
header isn't used at all.
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.
|
Some mail servers does not answer truthfully to verfification queries in order to prevent spammers and others to gain information about the mail addresses present on the mail server.
If the mail server returns any other return code than 200-399 an exception will be thrown.
CLASS Protocols.SMTP.Configuration |
Class to store configuration variable for the SMTP server
int maxsize
Message max size
int maxrcpt
Maximum number of recipients (default 1000)
int checkdns
Verify sender domain for MX
int checkemail
Lamme check email from validity
int givedata
Give raw data and normal MIME data, if set to yes your cb_data function should take an extra string argument
CLASS Protocols.SMTP.Connection |
The low-level class for the SMTP server
function(string:mixed) logfunction
This function is called whenever the SMTP server logs something. By default the log function is werror .
CLASS Protocols.SMTP.Server |
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
void Protocols.SMTP.Server(array(string) _domains, void|int port, void|string ip, function _cb_mailfrom, function _cb_rcptto, function _cb_data)
Create a receiving SMTP server. It implements RFC 2821, 2822 and 1854.
Domains name this server relay, you need to provide at least one domain (the first one will be used for MAILER-DAEMON address). if you want to relay everything you can put a '*' after this first domain.
Port this server listen on
IP on which server listen
Mailfrom callback function, this function will be called when a client send a mail from command. This function must take a string as argument (corresponding to the sender's email) and return int corresponding to the SMTP code to output to the client. If you return an array the first element is the SMTP code and the second is the error string to display.
Same as cb_mailfrom but called when a client sends a rcpt to.
This function is called each time a client send a data content. It must have the following synopsis: int cb_data(object mime, string sender, array(string) recipients, void|string rawdata) object mime : the mime data object string sender : sender of the mail (from the mailfrom command) array(string) recipients : one or more recipients given by the rcpt to command return : SMTP code to output to the client. If you return an array the first element is the SMTP code and the second is the error string to display.
Here is an example of silly program that does nothing except outputing informations to stdout. int cb_mailfrom(string mail) { return 250; }
int cb_rcptto(string email) { // check the user's mailbox here return 250; }
int cb_data(object mime, string sender, array(string) recipients) { write(sprintf("smtpd: mailfrom=%s, to=%s, headers=%O\ndata=%s\n", sender, recipients * ", ", mime->headers, mime->getdata())); // check the data and deliver the mail here if(mime->body_parts) { foreach(mime->body_parts, object mpart) write("smtpd: mpart data = %O\n", mpart->getdata()); } return 250; }
int main(int argc, array(string) argv) { Protocols.SMTP.Server(({ "ece.fr" }), 2500, "127.0.0.1", cb_mailfrom, cb_rcptto, cb_data); return -1; }
Module Protocols.SNMP |
SNMPv1 and v2c
constant Protocols.SNMP.ERROR_TOOBIG
Error tooBig
constant Protocols.SNMP.ERROR_NOERROR
Error noError
constant Protocols.SNMP.ERROR_NOSUCHNAME
Error noSuchName
constant Protocols.SNMP.ERROR_BADVALUE
Error badValue
constant Protocols.SNMP.ERROR_READONLY
Error readOnly
constant Protocols.SNMP.ERROR_GENERROR
Error genError
constant Protocols.SNMP.REQUEST_GET
PDU type Get
constant Protocols.SNMP.REQUEST_GETNEXT
PDU type GetNext
constant Protocols.SNMP.REQUEST_SET
PDU type Set
constant Protocols.SNMP.REQUEST_GET_RESPONSE
PDU type GetResponse
constant Protocols.SNMP.REQUEST_TRAP
PDU type Trap
CLASS Protocols.SNMP.agent |
A simple SNMP agent with support for SNMP Get requests
inherit "protocol"
void Protocols.SNMP.agent(int|void port, string|void addr)
create a new instance of the agent
the port number to listen for requests on
the 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 set_threaded()
Run the agent event loop in a thread, if available.
void set_managers_only(int yesno)
enable manager access limits
1 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_get_communities(array communities)
set the valid community strings for Get requests
an array of valid Get communities
send an empty array to disable Get requests
void set_set_communities(array communities)
set the valid community strings for Set requests
an array of valid Set communities
send an empty array to disable Set requests
void set_managers(array managers)
set the valid manager list for requests
an array of valid management hosts
send an empty array to disable all requests
void set_set_oid_callback(string oid, function cb)
set the Set request callback function for an Object Identifier
the string object identifier, such as 1.3.6.1.4.1.132.2 or an asterisk (*) to serve as the handler for all requests for which a handler is specified.
the function to call when oid is requested by a manager the function should take 3 arguments: a string containing the requested oid, the desired value, and the body of the request as a mapping. The function should return an array containing 3 elements: The first is a boolean indicating success or failure. If success, the next 2 elements should be the SNMP data type of the result followed by the result itself. If failure, the next 2 elements should be the error-status such as Protocols.SNMP.ERROR_TOOBIG and the second is the error-index, if any.
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.
int clear_set_oid_callback(string oid)
clear the Set callback function for an Object Identifier
the 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
void|function get_set_oid_callback(string oid)
get the Set request callback function for an Object Identifier
the 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 set_get_oid_callback(string oid, function cb)
set the Get request callback function for an Object Identifier
the string object identifier, such as 1.3.6.1.4.1.132.2 or an asterisk (*) to serve as the handler for all requests for which a handler is specified.
the function to call when oid is requested by a manager the function should take 2 arguments: a string containing the requested oid and the body of the request as a mapping. The function should return an array containing 3 elements: The first is a boolean indicating success or failure. If success, the next 2 elements should be the SNMP data type of the result followed by the result itself. If failure, the next 2 elements should be the error-status such as Protocols.SNMP.ERROR_TOOBIG and the second is the error-index, if any.
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.
int clear_get_oid_callback(string oid)
clear the Get callback function for an Object Identifier
the 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
void|function get_get_oid_callback(string oid)
get the Get request callback function for an Object Identifier
the 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
CLASS Protocols.SNMP.protocol |
SNMP protocol implementation for Pike
RFCs:
implemented (yet): 1155-7 : v1
1901-4 : v2/community (Bulk ops aren't implemented!)
planned: 2742 : agentX
2570 : v3 description
inherit Stdio.UDP : snmp
int snmp_version
SNMP version
currently version 1 and 2 are supported.
string snmp_community
SNMP community string
should be set to the appropriate SNMP community before sending a request.
Set to "public" by default.
void 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
remote address and UDP port (optional)
local address and UDP port (optional)
mapping readmsg()
return the whole SNMP message in raw format
mapping decode_asn1_msg(mapping rawd)
decode ASN1 data, if garbaged ignore it
void to_pool(mapping rawd)
decode raw pdu message and place in message pool
mapping readmsg_from_pool(int msgid)
read decoded message from pool
int get_request(array(string) varlist, string|void rem_addr, int|void rem_port)
GetRequest-PDU call
an array of OIDs to GET
remote 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
a mapping containing data to return
|
original received decoded pdu that this response corresponds to
error code
error index
request ID
int get_nextrequest(array(string) varlist, string|void rem_addr, int|void rem_port)
GetNextRequest-PDU call
an array of OIDs to GET
remote address an UDP port to send request to (optional)
request ID
int set_request(mapping varlist, string|void rem_addr, int|void rem_port)
SetRequest-PDU call
a mapping of OIDs to SET
|
remote 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");
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
a mapping of OIDs to include in trap
|
generic trap-type
specific trap-type
uptime
originating ip address of the trap
address and UDP to send trap to
request id
Module Protocols.X |
Module Protocols.X.Extensions |
CLASS Protocols.X.Extensions.extension |
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.
An object of type Protocols.X.Xlib.Display
CLASS Protocols.X.Extensions.XTEST |
Provides support for the X11 XTEST extension.
inherit extension : extension
void Protocols.X.Extensions.XTEST()
Create object.
int init(object display)
Initialize the XTEST extension. Returns 1 if successful.
Protocols.X.Display object
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.
Type of event to send. Possible values: KeyPress: 2, KeyRelease: 3, ButtonPress: 4, ButtonRelease: 5, MotionNotify: 6
Button (for Button events) or Keycode (for Key events) to send
Delay before the X server simulates event. 0 indicates zero delay.
Window object that a motion event occurrs in. If no window is provided, the root window will be used.
For motion events, this is the relative X distance or absolute X coordinates.
For 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.
A true (non zero) value causes the client to perform as described above. If false (zero), server returns to the normal state of being susceptible to server grabs.
Module Protocols.XMLRPC |
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>.
Translation rules for conversions from XML-RPC datatypes to Pike datatypes:
XML-RPC <i4>, <int> and <boolean> are
translated to Pike int
.
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 is currently only partially implemented. It is decoded but cannot be encoded. Also, the code here does not assume any particular timezone (which is correct according to the specification). The Calendar module, however, seems to assume localtime.
Call Protocols.XMLRPC.decode_call(string xml_input)
Decodes a XML-RPC representation of a function call and returns a Call object.
Call
array|Fault Protocols.XMLRPC.decode_response(string xml_input)
Decodes a XML-RPC representation of a response and returns an array containing response values, or a Fault object.
Fault
string Protocols.XMLRPC.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 Protocols.XMLRPC.encode_response(array params)
Encodes a response containing the multiple values in params and returns the XML-RPC string representation.
string Protocols.XMLRPC.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.
CLASS Protocols.XMLRPC.Call |
Represents a function call made to a XML-RPC server.
decode_call()
string method_name
array paramsvoid Protocols.XMLRPC.Call(string method_name, array params)
int method_name
Represents <methodName> in the XML-RPC standard.
array params
Represents <params> in the XML-RPC standard where all datatypes have been converted to equivalent or similar datatypes in Pike.
CLASS Protocols.XMLRPC.Fault |
Represents a fault response which can be one of the return values from a XML-RPC function call.
decode_response()
int fault_code
string fault_stringvoid Protocols.XMLRPC.Fault(int fault_code, string fault_string)
int fault_code
Represents faultCode in the XML-RPC standard.
int fault_string
Represents faultString in the XML-RPC standard.
CLASS Protocols.XMLRPC.Client |
This class implements an XML-RPC client that uses HTTP transport.
> 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 urlvoid Protocols.XMLRPC.Client(string|Standards.URI url)
Module Protocols.Bittorrent |
CLASS Protocols.Bittorrent.Peer |
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_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_available()
Returns true if this peer is available, as in we can use it to download stuff.
int is_activated()
Returns true if this peer is activated, as in we're downloading from it.
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.
int is_choked()
Returns true if this peer is choking, as in doesn't send more data to us.
multiset(int) downloading_pieces()
Returns as multiset what this peer is downloading.
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.
void send_have(int n)
Send a have message to tell I now have piece n. Ignored if not online.
void request(int piece, int offset, int bytes, function(int:void|mixed) callback)
Called to request a chunk from this peer.
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.
CLASS Protocols.Bittorrent.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->my_port=6881; t->open_port();
// Ok, start calling tracker to get peers, // and tell about us: t->start_update_tracker();
// Finally, start the download: t->start_download();
return -1; }
function(.Peer:int(0..1)) 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 pieces_update_status
If set, called when we got another piece downloaded (no args).
function downloads_update_status
If set, called when we start to download another piece (no args).
function peer_update_status
If set, called when peer status changes.
function download_completed_callback
If set, called when download is completed.
function(string:void|mixed) warning
Called if there is a protocol error.
void load_metainfo(string filename)
Loads the metainfo from a file.
int fix_targets(void|int(-1..2) allocate, void|string base_filename, void|function(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.
Determines allocation procedure if the file doesn't exist:
|
A new base filename to substitute the metainfo base target filename with.
|
void verify_targets(void|function(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) ]
void open_port()
Open the port we're listening on.
int bytes_done()
Calculate the bytes successfully downloaded (full pieces).
int bytes_left()
Calculate the bytes left to download.
void update_tracker(void|string event, void|int contact)
Contact and update the tracker with current status will fill the peer list.
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 contact_peers(void|int n)
Contact all or n peers.
string file_got_bitfield()
Returns the file got field as a string bitfield (cached).
void start_download()
Initiate the downloading scheme.
CLASS Protocols.Bittorrent.Torrent.Target |
Each bittorrent has one or more target files. This represents one of those.
string base
int length
int offset
void|array pathvoid Protocols.Bittorrent.Torrent.Target(string base, int length, int offset, void|array path)
CLASS Protocols.Bittorrent.Generator |
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..sizeof(am)-2];;string f) g->add(f);
string dest=am[-1]; if (-1==search(dest,"torrent")) dest+=".torrent";
Stdio.write_file(dest,g->digest()); return 0; }
inherit .Torrent : Torrent
void Protocols.Bittorrent.Generator(void|string base, void|int piece_size)
Create a generator.
The base filename/path in the torrent.
The size of the pieces that the SHA hashes are calculated on. Default 262144 and this value should probably be 2^n.
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_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.
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(string path, void|string base)
Add a file, or a directory tree to the torrent. This will call add_directory_tree or add_file.
void build_sha1s(void|function(int:void) progress_callback)
Build the SHA hashes from the files.
string digest(void|function(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 .
CLASS Protocols.Bittorrent.Port |
void Protocols.Bittorrent.Port(.Torrent _parent)
Bind a port for this Torrent.
Module Protocols.Bittorrent.Bencoding |
array(string|int|array|mapping) Protocols.Bittorrent.Bencoding._decode(string what)
Decodes a Bittorrent bencoded data chunk.
|
string|int|array|mapping Protocols.Bittorrent.Bencoding.decode(string what)
Decodes a Bittorrent bencoded data chunk and ignores the remaining string. Returns UNDEFINED if the data is incomplete.
string Protocols.Bittorrent.Bencoding.encode(string|int|array|mapping data)
Encodes a Bittorrent bencoded data chunk.
string Protocols.Bittorrent.Bencoding.bits2string(array(int(0..1)) v)
Convert an array of int(0..1)
to a Bittorrent style
bitstring. Input will be padded to even bytes.
array(int(0..1)) Protocols.Bittorrent.Bencoding.string2bits(string s)
Convert a Bittorrent style bitstring to an array of
int(0..1)
.
array(int) Protocols.Bittorrent.Bencoding.string2arr(string s)
Convert a Bittorrent style bitstring to an array of indices.
Module Protocols.Ident |
An implementation of the IDENT protocol, specified in RFC 931.
array(string) Protocols.Ident.lookup(object fd)
Throws exception upon any error.
CLASS Protocols.Ident.AsyncLookup |
void Protocols.Ident.AsyncLookup(object fd, function(array(string):void) cb, mixed ... args)
Module Protocols.LMTP |
CLASS Protocols.LMTP.Server |
A LMTP server. It has been fairly well tested against Postfix client. Actually this module is only an extention to the SMTP server.
void Protocols.LMTP.Server(array(string) _domains, void|int port, void|string ip, function _cb_mailfrom, function _cb_rcptto, function _cb_data)
Create a receiving LMTP server. It implements RFC 2821, 2822, 2033 and 1854.
Domains name this server relay, you need to provide at least one domain (the first one will be used for MAILER-DAEMON address). if you want to relay everything you can put a '*' after this first domain.
Port this server listen on
IP on which server listen
Mailfrom callback function, this function will be called when a client send a mail from command. This function must take a string as argument (corresponding to the sender's email) and return int corresponding to the SMTP code to output to the client. If you return an array the first element is the SMTP code and the second is the error string to display.
Same as cb_mailfrom but called when a client sends a rcpt to.
This function is called for each recipient in the "rcpt to" command after the client sends the "data" command It must have the following synopsis: int|array cb_data(object mime, string sender, array(string) recipients, 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, 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(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; }
Module Protocols.LPD |
CLASS Protocols.LPD.client |
A client for communicating with printers and print spoolers that support the BSD lpd protocol (RFC 1179).
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 set_job_name(string name)
Sets the name of the print job to name.
int start_queue(string queue)
Start the queue queue if not already printing.
Returns 0 if unable to connect, 1 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 delete_job(string queue, int|void job)
Delete job job from printer queue.
Returns 1 on success, 0 otherwise.
string|int status(string queue)
Check the status of queue queue.
Returns 0 on failure, otherwise returns the status response from the printer.
void Protocols.LPD.client(string|void hostname, int|void portnum)
Create a new LPD client connection.
Contains the hostname or ipaddress of the print host. if not provided, defaults to localhost.
Contains the port the print host is listening on. if not provided, defaults to port 515, the RFC 1179 standard.
Module Protocols.Line |
CLASS Protocols.Line.simple |
Simple nonblocking line-oriented I/O.
constant line_separator
The sequence separating lines from eachother. "\r\n" by default.
function(string:void) 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()
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()
void send(string s)
Queue some data to send.
handle_command() , handle_data() , disconnect()
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 touch_time()
Reset the timeout timer.
create() , do_timeout()
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
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()
ADT.Queue 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 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.
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.
void 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()
CLASS Protocols.Line.smtp_style |
Nonblocking line-oriented I/O with support for sending SMTP-style codes.
inherit simple : simple
mapping(int:string|array(string)) errorcodes
Mapping from return-code to error-message.
Overload this constant as apropriate.
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
CLASS Protocols.Line.imap_style |
Nonblocking line-oriented I/O with support for reading literals.
inherit simple : simple
int literal_length
Length in bytes of the literal to read.
function(string:void) 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.
function(string:void) 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()
void handle_command(string line)
Function called once for every received line.
void expect_literal(int length, function(string:void) callback)
Enter literal reading mode.
Sets literal_length and handle_literal() .
literal_length , handle_literal()
Module Protocols.NNTP |
CLASS Protocols.NNTP.protocol |
NNTP protocol
inherit Stdio.FILE : sock
int readreturncode()
reads the server result code for last request used internally by command().
array(string) read_body_lines()
reads the message from the server as an array of lines
string readreturnbody()
reads the message from the server
void writebody(string s)
send the body of a message to the server.
int command(string cmd)
send a command to the server
the result code sent by the server
string get_response_message()
gets the result message supplied by the server for the last response
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.
string do_cmd_with_body(string cmd)
send a command that should return a message body.
the message body
CLASS Protocols.NNTP.client |
An NNTP client
inherit protocol : protocol
array(Group) list_groups()
Returns a list of all active groups.
Group current_group
The current news group.
void set_group(Group o)
Sets the current news group to o .
Group go_to_group(string group)
Sets the current group to group .
string head(void|int|string x)
string body(void|int|string x)
string article(void|int|string x)
void Protocols.NNTP.client(string|void server)
Module Protocols.TELNET |
Implements TELNET as described by RFC 764 and RFC 854
Also implements the Q method of TELNET option negotiation as specified by RFC 1143.
inherit TelnetCodes : TelnetCodes
inherit Telopts : Telopts
constant Protocols.TELNET.TELQUAL_IS
option is...
constant Protocols.TELNET.TELQUAL_SEND
send option
constant Protocols.TELNET.TELQUAL_INFO
ENVIRON: informational version of IS
constant Protocols.TELNET.TELQUAL_REPLY
AUTHENTICATION: client version of IS
constant Protocols.TELNET.TELQUAL_NAME
AUTHENTICATION: client version of IS
constant Protocols.TELNET.LFLOW_OFF
Disable remote flow control
constant Protocols.TELNET.LFLOW_ON
Enable remote flow control
constant Protocols.TELNET.LFLOW_RESTART_ANY
Restart output on any char
constant Protocols.TELNET.LFLOW_RESTART_XON
Restart output only on XON
constant Protocols.TELNET.AUTH_WHO_CLIENT
Client authenticating server
constant Protocols.TELNET.AUTH_WHO_SERVER
Server authenticating client
CLASS Protocols.TELNET.TelnetCodes |
Table of IAC-codes.
constant IAC
interpret as command.
constant DONT
you are not to use option
constant DO
please, you use option
constant WONT
I won't use option
constant WILL
I will use option
constant SB
interpret as subnegotiation
constant GA
you may reverse the line
constant EL
erase the current line
constant EC
erase the current character
constant AYT
are you there
constant AO
abort output--but let prog finish
constant IP
interrupt process--permanently
constant BREAK
break
constant DM
data mark--for connect. cleaning
constant NOP
nop
constant SE
end sub negotiation
constant EOR
end of record (transparent mode)
constant ABORT
Abort process
constant SUSP
Suspend process
constant xEOF
End of file: EOF is already used...
constant SYNCH
for telfunc calls
CLASS Protocols.TELNET.Telopts |
Table of TELNET options.
constant TELOPT_BINARY
8-bit data path
constant TELOPT_ECHO
echo
constant TELOPT_RCP
prepare to reconnect
constant TELOPT_SGA
suppress go ahead
constant TELOPT_NAMS
approximate message size
constant TELOPT_STATUS
give status
constant TELOPT_TM
timing mark
constant TELOPT_RCTE
remote controlled transmission and echo
constant TELOPT_NAOL
negotiate about output line width
constant TELOPT_NAOP
negotiate about output page size
constant TELOPT_NAOCRD
negotiate about CR disposition
constant TELOPT_NAOHTS
negotiate about horizontal tabstops
constant TELOPT_NAOHTD
negotiate about horizontal tab disposition
constant TELOPT_NAOFFD
negotiate about formfeed disposition
constant TELOPT_NAOVTS
negotiate about vertical tab stops
constant TELOPT_NAOVTD
negotiate about vertical tab disposition
constant TELOPT_NAOLFD
negotiate about output LF disposition
constant TELOPT_XASCII
extended ascic character set
constant TELOPT_LOGOUT
force logout
constant TELOPT_BM
byte macro
constant TELOPT_DET
data entry terminal
constant TELOPT_SUPDUP
supdup protocol
constant TELOPT_SUPDUPOUTPUT
supdup output
constant TELOPT_SNDLOC
send location
constant TELOPT_TTYPE
terminal type
constant TELOPT_EOR
end or record
constant TELOPT_TUID
TACACS user identification
constant TELOPT_OUTMRK
output marking
constant TELOPT_TTYLOC
terminal location number
constant TELOPT_3270REGIME
3270 regime
constant TELOPT_X3PAD
X.3 PAD
constant TELOPT_NAWS
window size
constant TELOPT_TSPEED
terminal speed
constant TELOPT_LFLOW
remote flow control
constant TELOPT_LINEMODE
Linemode option
constant TELOPT_XDISPLOC
X Display Location
constant TELOPT_OLD_ENVIRON
Old - Environment variables
constant TELOPT_AUTHENTICATION
Authenticate
constant TELOPT_ENCRYPT
Encryption option
constant TELOPT_NEW_ENVIRON
New - Environment variables
constant TELOPT_EXOPL
extended-options-list
CLASS Protocols.TELNET.protocol |
Implementation of the TELNET protocol.
static object fd
The connection.
static mapping cb
Mapping containing extra callbacks.
static mixed id
Value to send to the callbacks.
static function(mixed|void:string) write_cb
Write callback.
static function(mixed:void) read_cb
Read callback.
static function(mixed|void:void) close_cb
Close callback.
static array(int) remote_options
static array(int) local_options
Negotiation states of all WILL/WON'T options. See RFC 1143 for a description of the states.
static string to_send
Data queued to be sent.
static int done
Indicates that connection should be closed
static int nonblocking_write
Tells if we have set the nonblocking write callback or not.
void enable_write()
Turns on the write callback if apropriate.
void disable_write()
Turns off the write callback if apropriate.
void write(string s)
Queues data to be sent to the other end of the connection.
String to send.
void write_raw(string s)
Queues raw data to be sent to the other end of the connection.
String with raw telnet data to send.
void close()
Closes the connetion neatly
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 send_DO(int option)
Starts negotiation to enable a TELNET option.
The option to enable.
void send_DONT(int option)
Starts negotiation to disable a TELNET option.
The option to disable.
static int synch
Indicates whether we are in synch-mode or not.
void got_oob(mixed ignored, string s)
Callback called when Out-Of-Band data has been received.
The id from the connection.
The Out-Of-Band data received.
void call_read_cb(string data)
Calls read_cb() .
Specifically provided for overloading
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.
The id from the connection.
The received data.
void set_write_callback(function(mixed|void:string) w_cb)
Sets the callback to be called when it is clear to send.
The new write callback.
void setup()
Called when the initial setup is done.
Created specifically for overloading
void Protocols.TELNET.protocol(object f, function(mixed:void) r_cb, function(mixed|void:string) w_cb, function(mixed|void:void) c_cb, mapping callbacks, mixed|void new_id)
Creates a TELNET protocol handler, and sets its callbacks.
File to use for the connection.
Function to call when data has arrived.
Function to call when data can be sent.
Function to call when the connection is closed.
Mapping with callbacks for the various TELNET commands.
Value to send to the various callbacks.
CLASS Protocols.TELNET.LineMode |
Line-oriented TELNET protocol handler.
inherit protocol : protocol
CLASS Protocols.TELNET.Readline |
Line-oriented TELNET protocol handler with Stdio.Readline support.
inherit LineMode : LineMode
Module Protocols.OBEX |
The IrDAŽ Object Exchange Protocol. OBEX is a protocol for sending and receiving binary objects to mobile devices using transports such as IR and Bluetooth.
constant Protocols.OBEX.SETPATH_BACKUP
A flag for the REQ_SETPATH command indicating that the parent directory should be selected
constant 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
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.
string Protocols.OBEX.encode_headers(Headers h)
Serialize a set of headers to wire format
split_headers()
Headers Protocols.OBEX.decode_headers(string h)
Deserialize a set of headers from wire format
array(string) Protocols.OBEX.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.
ENUM Protocols.OBEX.Request |
A request opcode, for use with the client.do_request() function.
constant Protocols.OBEX.REQ_CONNECT
Establish a new OBEX connection
constant Protocols.OBEX.REQ_DISCONNECT
Terminate an OBEX connection
constant Protocols.OBEX.REQ_PUT
Send an object to the mobile device
constant Protocols.OBEX.REQ_GET
Receive an object from the mobile devuce
constant Protocols.OBEX.REQ_SETPATH
Change the working directory
constant Protocols.OBEX.REQ_SESSION
Manage a session
constant Protocols.OBEX.REQ_ABORT
Abort the request currently being processed
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.
ENUM Protocols.OBEX.HeaderIdentifier |
An identifier for a request or response header
constant Protocols.OBEX.HI_COUNT
Number of objects to transfer (used by REQ_CONNECT )
constant Protocols.OBEX.HI_NAME
Name of the object (string)
constant Protocols.OBEX.HI_TYPE
Type of the object (IANA media type)
constant Protocols.OBEX.HI_LENGTH
Length of the object transferred, in octets
constant Protocols.OBEX.HI_TIME
ISO 8601 timestamp (string)
constant Protocols.OBEX.HI_DESCRIPTION
Text description of the object
constant Protocols.OBEX.HI_TARGET
Name of service that operation is targeted to
constant Protocols.OBEX.HI_HTTP
Any HTTP 1.x header
constant Protocols.OBEX.HI_BODY
A chunk of the object body
constant Protocols.OBEX.HI_ENDOFBODY
The final chunk of the object body
constant Protocols.OBEX.HI_WHO
Identifies the OBEX application (string)
constant Protocols.OBEX.HI_CONNID
An identifier used for OBEX connection multiplexing
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_CREATORID
Indicates the creator of an object
constant Protocols.OBEX.HI_WANUUID
Uniquely identifies the OBEX server
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
CLASS Protocols.OBEX.Client |
An OBEX client
ATclient
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.
Request opcode
Raw request data
An array with the response information
|
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.
Request opcode
Request headers
Any request data that should appear before the headers, but after the opcode
An array with the response information
|
low_do_request() , do_abort() , do_put() , do_get() , do_setpath() , do_session()
array(int|Headers) do_abort(Headers|void headers)
Perform a REQ_ABORT request.
do_request()
array(int|Headers) do_put(string|Stdio.Stream data, Headers|void extra_headers)
Perform a REQ_PUT request.
Body data to send, or a stream to read the data from
Any additional headers to send (HI_LENGTH and HI_BODY are generated by this function)
do_get() , do_request()
array(int|Headers) do_get(Stdio.Stream data, Headers|void headers)
Perform a REQ_GET request.
A stream to write the body data to
Headers 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_setpath(string path, int|void flags, Headers|void extra_headers)
Perform a REQ_SETPATH request.
The directory to set as current working directory
|
Logical or of zero or more of SETPATH_BACKUP and SETPATH_NOCREATE
Any additional request headers (the HI_NAME header is generated by this function)
do_request()
array(int|Headers) do_session(Headers|void headers)
Perform a REQ_SESSION request.
do_request()
int(0..1) 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.
int(0..1) disconnect()
Terminate a connection using the REQ_DISCONNECT opcode
If the disconnection succeeds, 1 is returned. Otherwise, 0 is returned.
void 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
A stream for writing requests and reading back responses. Typically this is some kind of serial port.
CLASS Protocols.OBEX.ATClient |
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