lws_client_reset - retarget a connected wsi to start over with a new connection (ie, redirect) this only works if still in HTTP, ie, not upgraded yet

struct lws * lws_client_reset (struct lws * wsi, int ssl, const char * address, int port, const char * path, const char * host)

Arguments

wsi

connection to reset

address

network address of the new server

port

port to connect to

path

uri path to connect to on the new server

host

host header to send to the new server

lws_client_connect_via_info - Connect to another websocket server

struct lws * lws_client_connect_via_info (struct lws_client_connect_info * i)

Arguments

i
pointer to lws_client_connect_info struct

Description

This function creates a connection to a remote server

lws_client_connect_extended - Connect to another websocket server DEPRECATED use lws_client_connect_via_info

struct lws * lws_client_connect_extended (struct lws_context * context, const char * address, int port, int ssl_connection, const char * path, const char * host, const char * origin, const char * protocol, int ietf_version_or_minus_one, void * userdata)

Arguments

context
Websocket context
address
Remote server address, eg, "myserver.com"
port
Port to connect to on the remote server, eg, 80
ssl_connection
0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self signed certs
path
Websocket path on server
host
Hostname on server
origin
Socket origin name
protocol
Comma-separated list of protocols being asked for from the server, or just one. The server will pick the one it likes best.
ietf_version_or_minus_one
-1 to ask to connect using the default, latest protocol supported, or the specific protocol ordinal
userdata
Pre-allocated user data

Description

This function creates a connection to a remote server

lws_client_connect - Connect to another websocket server DEPRECATED use lws_client_connect_via_info

struct lws * lws_client_connect (struct lws_context * context, const char * address, int port, int ssl_connection, const char * path, const char * host, const char * origin, const char * protocol, int ietf_version_or_minus_one)

Arguments

context
Websocket context
address
Remote server address, eg, "myserver.com"
port
Port to connect to on the remote server, eg, 80
ssl_connection
0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self signed certs
path
Websocket path on server
host
Hostname on server
origin
Socket origin name
protocol
Comma-separated list of protocols being asked for from the server, or just one. The server will pick the one it likes best. If you don't want to specify a protocol, which is legal, use NULL here.
ietf_version_or_minus_one
-1 to ask to connect using the default, latest protocol supported, or the specific protocol ordinal

Description

This function creates a connection to a remote server

lws_get_library_version -

const char * lws_get_library_version ( void)

Arguments

void
no arguments

Description

returns a const char * to a string like "1.1 178d78c" representing the library version followed by the git head hash it was built from


lws_create_context - Create the websocket handler

struct lws_context * lws_create_context (struct lws_context_creation_info * info)

Arguments

info
pointer to struct with parameters

Description

This function creates the listening socket (if serving) and takes care of all initialization in one step.

After initialization, it returns a struct lws_context * that represents this server. After calling, user code needs to take care of calling lws_service with the context pointer to get the server's sockets serviced. This must be done in the same process context as the initialization call.

The protocol callback functions are called for a handful of events including http requests coming in, websocket connections becoming established, and data arriving; it's also called periodically to allow async transmission.

HTTP requests are sent always to the FIRST protocol in protocol, since at that time websocket protocol has not been negotiated. Other protocols after the first one never see any HTTP callack activity.

The server created is a simple http server by default; part of the websocket standard is upgrading this http connection to a websocket one.

This allows the same server to provide files like scripts and favicon / images or whatever over http and dynamic data over websockets all in one place; they're all handled in the user callback.


lws_context_destroy - Destroy the websocket context

void lws_context_destroy (struct lws_context * context)

Arguments

context
Websocket context

Description

This function closes any active connections and then frees the context. After calling this, any further use of the context is undefined.

lws_return_http_status - Return simple http status

int lws_return_http_status (struct lws * wsi, unsigned int code, const char * html_body)

Arguments

wsi
Websocket instance (available from user callback)
code
Status index, eg, 404
html_body
User-readable HTML description < 1KB, or NULL

Description

Helper to report HTTP errors back to the client cleanly and consistently

lws_set_timeout - marks the wsi as subject to a timeout

void lws_set_timeout (struct lws * wsi, enum pending_timeout reason, int secs)

Arguments

wsi
Websocket connection instance
reason
timeout reason
secs
how many seconds

Description

You will not need this unless you are doing something special


lws_get_peer_addresses - Get client address information

void lws_get_peer_addresses (struct lws * wsi, lws_sockfd_type fd, char * name, int name_len, char * rip, int rip_len)

Arguments

wsi
Local struct lws associated with
fd
Connection socket descriptor
name
Buffer to take client address name
name_len
Length of client address name buffer
rip
Buffer to take client address IP dotted quad
rip_len
Length of client address IP buffer

Description

This function fills in name and rip with the name and IP of the client connected with socket descriptor fd. Names may be truncated if there is not enough room. If either cannot be determined, they will be returned as valid zero-length strings.

lws_context_user - get the user data associated with the context

LWS_EXTERN void * lws_context_user (struct lws_context * context)

Arguments

context
Websocket context

Description

This returns the optional user allocation that can be attached to the context the sockets live in at context_create time. It's a way to let all sockets serviced in the same context share data without using globals statics in the user code.

lws_callback_all_protocol - Callback all connections using the given protocol with the given reason

int lws_callback_all_protocol (struct lws_context * context, const struct lws_protocols * protocol, int reason)

Arguments

protocol
Protocol whose connections will get callbacks
reason
Callback reason index

lws_get_socket_fd - returns the socket file descriptor

int lws_get_socket_fd (struct lws * wsi)

Arguments

wsi
Websocket connection instance

Description

You will not need this unless you are doing something special


lws_rx_flow_control - Enable and disable socket servicing for received packets.

int lws_rx_flow_control (struct lws * wsi, int enable)

Arguments

wsi
Websocket connection instance to get callback for
enable
0 = disable read servicing for this connection, 1 = enable

Description

If the output side of a server process becomes choked, this allows flow control for the input side.


lws_rx_flow_allow_all_protocol - Allow all connections with this protocol to receive

void lws_rx_flow_allow_all_protocol (const struct lws_context * context, const struct lws_protocols * protocol)

Arguments

protocol
all connections using this protocol will be allowed to receive

Description

When the user server code realizes it can accept more input, it can call this to have the RX flow restriction removed from all connections using the given protocol.


lws_canonical_hostname - returns this host's hostname

const char * lws_canonical_hostname (struct lws_context * context)

Arguments

context
Websocket context

Description

This is typically used by client code to fill in the host parameter when making a client connection. You can only call it after the context has been created.


lws_set_proxy - Setups proxy to lws_context.

int lws_set_proxy (struct lws_context * context, const char * proxy)

Arguments

context
pointer to struct lws_context you want set proxy to
proxy
pointer to c string containing proxy in format address:port

Description

Returns 0 if proxy string was parsed and proxy was setup. Returns -1 if proxy is NULL or has incorrect format.

This is only required if your OS does not provide the http_proxy environment variable (eg, OSX)

IMPORTANT! You should call this function right after creation of the lws_context and before call to connect. If you call this function after connect behavior is undefined. This function will override proxy settings made on lws_context creation with genenv call.


lws_get_protocol - Returns a protocol pointer from a websocket connection.

const struct lws_protocols * lws_get_protocol (struct lws * wsi)

Arguments

wsi
pointer to struct websocket you want to know the protocol of

Description

Some apis can act on all live connections of a given protocol, this is how you can get a pointer to the active protocol if needed.


lws_set_log_level - Set the logging bitfield

void lws_set_log_level (int level, void (*func) (int level, const char *line))

Arguments

level
OR together the LLL_ debug contexts you want output from

Description

log level defaults to "err", "warn" and "notice" contexts enabled and emission on stderr.

lws_is_ssl - Find out if connection is using SSL

int lws_is_ssl (struct lws * wsi)

Arguments

wsi
websocket connection to check

Description

Returns 0 if the connection is not using SSL, 1 if using SSL and using verified cert, and 2 if using SSL but the cert was not checked (appears for client wsi told to skip check on connection)

lws_partial_buffered - find out if lws buffered the last write

int lws_partial_buffered (struct lws * wsi)

Arguments

wsi
websocket connection to check

Description

Returns 1 if you cannot use lws_write because the last write on this connection is still buffered, and can't be cleared without returning to the service loop and waiting for the connection to be writeable again.

If you will try to do >1 lws_write call inside a single WRITEABLE callback, you must check this after every write and bail if set, ask for a new writeable callback and continue writing from there.

This is never set at the start of a writeable callback, but any write may set it.


lws_parse_uri -

LWS_EXTERN int lws_parse_uri (char * p, const char ** prot, const char ** ads, int * port, const char ** path)

Arguments

p
incoming uri string.. will get written to
prot
result pointer for protocol part (https://)
ads
result pointer for address part
port
result pointer for port part
path
result pointer for path part

Description

Notice it does so by dropping '\0' into input string

lws_cancel_service - Cancel servicing of pending websocket activity

void lws_cancel_service (struct lws_context * context)

Arguments

context
Websocket context

Description

This function let a call to lws_service waiting for a timeout immediately return.

There is no poll in MBED3, he will fire callbacks when he feels like it.


lws_cancel_service_pt - Cancel servicing of pending socket activity on one thread

void lws_cancel_service_pt (struct lws * wsi)

Arguments

wsi
Cancel service on the thread this wsi is serviced by

Description

This function let a call to lws_service waiting for a timeout immediately return.

lws_cancel_service - Cancel ALL servicing of pending socket activity

void lws_cancel_service (struct lws_context * context)

Arguments

context
Websocket context

Description

This function let a call to lws_service waiting for a timeout immediately return.

lws_cancel_service - Cancel servicing of pending websocket activity

void lws_cancel_service (struct lws_context * context)

Arguments

context
Websocket context

Description

This function let a call to lws_service waiting for a timeout immediately return.

lws_write - Apply protocol then write data to client

int lws_write (struct lws * wsi, unsigned char * buf, size_t len, enum lws_write_protocol wp)

Arguments

wsi
Websocket instance (available from user callback)
buf
The data to send. For data being sent on a websocket connection (ie, not default http), this buffer MUST have LWS_PRE bytes valid BEFORE the pointer. This is so the protocol header data can be added in-situ.
len
Count of the data bytes in the payload starting from buf

Description

This function provides the way to issue data back to the client for both http and websocket protocols.

In the case of sending using websocket protocol, be sure to allocate valid storage before and after buf as explained above. This scheme allows maximum efficiency of sending data and protocol in a single packet while not burdening the user code with any protocol knowledge.

Return may be -1 for a fatal error needing connection close, or a positive number reflecting the amount of bytes actually sent. This can be less than the requested number of bytes due to OS memory pressure at any given time.


lws_hdr_fragment_length -

int lws_hdr_fragment_length (struct lws * wsi, enum lws_token_indexes h, int frag_idx)

Arguments

wsi
websocket connection
h
which header index we are interested in
frag_idx
which fragment of h we want to get the length of

Description

The returned length does not include the space for a terminating '\0'

lws_hdr_total_length -

int lws_hdr_total_length (struct lws * wsi, enum lws_token_indexes h)

Arguments

wsi
websocket connection
h
which header index we are interested in

Description

The returned length does not include the space for a terminating '\0'

lws_hdr_copy_fragment -

int lws_hdr_copy_fragment (struct lws * wsi, char * dst, int len, enum lws_token_indexes h, int frag_idx)

Arguments

wsi
websocket connection
dst
destination buffer
len
length of destination buffer
h
which header index we are interested in

Description

The buffer length len must include space for an additional terminating '\0', or it will fail returning -1. If the requested fragment index is not present, it fails returning -1.

lws_hdr_copy -

int lws_hdr_copy (struct lws * wsi, char * dst, int len, enum lws_token_indexes h)

Arguments

wsi
websocket connection
dst
destination buffer
len
length of destination buffer
h
which header index we are interested in

Description

The buffer length len must include space for an additional terminating '\0', or it will fail returning -1.

lws_frame_is_binary -

int lws_frame_is_binary (struct lws * wsi)

Arguments

wsi
the connection we are inquiring about

Description

This is intended to be called from the LWS_CALLBACK_RECEIVE callback if it's interested to see if the frame it's dealing with was sent in binary mode.

lws_remaining_packet_payload - Bytes to come before "overall" rx packet is complete

size_t lws_remaining_packet_payload (struct lws * wsi)

Arguments

wsi
Websocket instance (available from user callback)

Description

This function is intended to be called from the callback if the user code is interested in "complete packets" from the client. libwebsockets just passes through payload as it comes and issues a buffer additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE callback handler can use this API to find out if the buffer it has just been given is the last piece of a "complete packet" from the client -- when that is the case lws_remaining_packet_payload will return 0.

Many protocols won't care becuse their packets are always small.


lws_callback_on_writable - Request a callback when this socket becomes able to be written to without blocking

int lws_callback_on_writable (struct lws * wsi)

Arguments

wsi
Websocket connection instance to get callback for

lws_callback_on_writable_all_protocol - Request a callback for all connections using the given protocol when it becomes possible to write to each socket without blocking in turn.

int lws_callback_on_writable_all_protocol (const struct lws_context * context, const struct lws_protocols * protocol)

Arguments

context
lws_context
protocol
Protocol whose connections will get callbacks

lws_http_transaction_completed - wait for new http transaction or close

int LWS_WARN_UNUSED_RESULT lws_http_transaction_completed (struct lws * wsi)

Arguments

wsi
websocket connection

Description

Returns 1 if the HTTP connection must close now Returns 0 and resets connection to wait for new HTTP header / transaction if possible

lws_adopt_socket - adopt foreign socket as if listen socket accepted it

struct lws * lws_adopt_socket (struct lws_context * context, lws_sockfd_type accept_fd)

Arguments

context
lws context
accept_fd
fd of already-accepted socket to adopt

Description

Either returns new wsi bound to accept_fd, or closes accept_fd and returns NULL, having cleaned up any new wsi pieces.

LWS adopts the socket in http serving mode, it's ready to accept an upgrade to ws or just serve http.


lws_serve_http_file - Send a file back to the client using http

int lws_serve_http_file (struct lws * wsi, const char * file, const char * content_type, const char * other_headers, int other_headers_len)

Arguments

wsi
Websocket instance (available from user callback)
file
The file to issue over http
content_type
The http content type, eg, text/html
other_headers
NULL or pointer to header string
other_headers_len
length of the other headers if non-NULL

Description

This function is intended to be called from the callback in response to http requests from the client. It allows the callback to issue local files down the http link in a single step.

Returning <0 indicates error and the wsi should be closed. Returning >0 indicates the file was completely sent and lws_http_transaction_completed called on the wsi (and close if != 0) ==0 indicates the file transfer is started and needs more service later, the wsi should be left alone.


lws_service_fd_tsi - Service polled socket with something waiting

int lws_service_fd_tsi (struct lws_context * context, struct lws_pollfd * pollfd, int tsi)

Arguments

context
Websocket context
pollfd
The pollfd entry describing the socket fd and which events happened.

Description

This function takes a pollfd that has POLLIN or POLLOUT activity and services it according to the state of the associated struct lws.

The one call deals with all "service" that might happen on a socket including listen accepts, http files as well as websocket protocol.

If a pollfd says it has something, you can just pass it to lws_service_fd whether it is a socket handled by lws or not. If it sees it is a lws socket, the traffic will be handled and pollfd->revents will be zeroed now.

If the socket is foreign to lws, it leaves revents alone. So you can see if you should service yourself by checking the pollfd revents after letting lws try to service it.


lws_service - Service any pending websocket activity

int lws_service (struct lws_context * context, int timeout_ms)

Arguments

context
Websocket context
timeout_ms
Timeout for poll; 0 means return immediately if nothing needed service otherwise block and service immediately, returning after the timeout if nothing needed service.

Description

This function deals with any pending websocket traffic, for three kinds of event. It handles these events on both server and client types of connection the same.

1) Accept new connections to our context's server

2) Call the receive callback for incoming frame data received by server or client connections.

You need to call this service function periodically to all the above functions to happen; if your application is single-threaded you can just call it in your main event loop.

Alternatively you can fork a new process that asynchronously handles calling this service in a loop. In that case you are happy if this call blocks your thread until it needs to take care of something and would call it with a large nonzero timeout. Your loop then takes no CPU while there is nothing happening.

If you are calling it in a single-threaded app, you don't want it to wait around blocking other things in your loop from happening, so you would call it with a timeout_ms of 0, so it returns immediately if nothing is pending, or as soon as it services whatever was pending.


struct lws_plat_file_ops - Platform-specific file operations

struct lws_plat_file_ops {
    lws_filefd_type (*open) (struct lws *wsi, const char *filename,unsigned long *filelen, int flags);
    int (*close) (struct lws *wsi, lws_filefd_type fd);
    unsigned long (*seek_cur) (struct lws *wsi, lws_filefd_type fd,long offset_from_cur_pos);
    int (*read) (struct lws *wsi, lws_filefd_type fd, unsigned long *amount,unsigned char *buf, unsigned long len);
    int (*write) (struct lws *wsi, lws_filefd_type fd, unsigned long *amount,unsigned char *buf, unsigned long len);
};

Members

open
Open file (always binary access if plat supports it) filelen is filled on exit to be the length of the file flags should be set to O_RDONLY or O_RDWR
close
Close file
seek_cur
Seek from current position
read
Read fron file *amount is set on exit to amount read
write
Write to file *amount is set on exit as amount written

Description

These provide platform-agnostic ways to deal with filesystem access in the library and in the user code.


lws_callback_function - User server actions

typedef int lws_callback_function (struct lws * wsi, enum lws_callback_reasons reason, void * user, void * in, size_t len)

Arguments

wsi
Opaque websocket instance pointer
reason
The reason for the call
user
Pointer to per-session user data allocated by library
in
Pointer used for some callback reasons
len
Length set for some callback reasons

Description

This callback is the way the user controls what is served. All the protocol detail is hidden and handled by the library.

For each connection / session there is user data allocated that is pointed to by "user". You set the size of this user data area when the library is initialized with lws_create_server.

You get an opportunity to initialize user data when called back with LWS_CALLBACK_ESTABLISHED reason.

LWS_CALLBACK_ESTABLISHED

after the server completes a handshake with an incoming client. If you built the library with ssl support, in is a pointer to the ssl struct associated with the connection or NULL.

LWS_CALLBACK_CLIENT_CONNECTION_ERROR

the request client connection has been unable to complete a handshake with the remote server. If in is non-NULL, you can find an error string of length len where it points to.

LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH

this is the last chance for the client user code to examine the http headers and decide to reject the connection. If the content in the headers is interesting to the client (url, etc) it needs to copy it out at this point since it will be destroyed before the CLIENT_ESTABLISHED call

LWS_CALLBACK_CLIENT_ESTABLISHED

after your client connection completed a handshake with the remote server

LWS_CALLBACK_CLOSED

when the websocket session ends

LWS_CALLBACK_CLOSED_HTTP

when a HTTP (non-websocket) session ends

LWS_CALLBACK_RECEIVE

data has appeared for this server endpoint from a remote client, it can be found at *in and is len bytes long

LWS_CALLBACK_CLIENT_RECEIVE_PONG

if you elected to see PONG packets, they appear with this callback reason. PONG packets only exist in 04+ protocol

LWS_CALLBACK_CLIENT_RECEIVE

data has appeared from the server for the client connection, it can be found at *in and is len bytes long

LWS_CALLBACK_HTTP

an http request has come from a client that is not asking to upgrade the connection to a websocket one. This is a chance to serve http content, for example, to send a script to the client which will then open the websockets connection. in points to the URI path requested and lws_serve_http_file makes it very simple to send back a file to the client. Normally after sending the file you are done with the http connection, since the rest of the activity will come by websockets from the script that was delivered by http, so you will want to return 1; to close and free up the connection. That's important because it uses a slot in the total number of client connections allowed set by MAX_CLIENTS.

LWS_CALLBACK_HTTP_BODY

the next len bytes data from the http request body HTTP connection is now available in in.

LWS_CALLBACK_HTTP_BODY_COMPLETION

the expected amount of http request body has been delivered

LWS_CALLBACK_HTTP_WRITEABLE

you can write more down the http protocol link now.

LWS_CALLBACK_HTTP_FILE_COMPLETION

a file requested to be send down http link has completed.

LWS_CALLBACK_SERVER_WRITEABLE

If you call lws_callback_on_writable on a connection, you will get one of these callbacks coming when the connection socket is able to accept another write packet without blocking. If it already was able to take another packet without blocking, you'll get this callback at the next call to the service loop function. Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE and servers get LWS_CALLBACK_SERVER_WRITEABLE.

LWS_CALLBACK_FILTER_NETWORK_CONNECTION

called when a client connects to the server at network level; the connection is accepted but then passed to this callback to decide whether to hang up immediately or not, based on the client IP. in contains the connection socket's descriptor. Since the client connection information is not available yet, wsi still pointing to the main server socket. Return non-zero to terminate the connection before sending or receiving anything. Because this happens immediately after the network connection from the client, there's no websocket protocol selected yet so this callback is issued only to protocol 0.

LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED

A new client just had been connected, accepted, and instantiated into the pool. This callback allows setting any relevant property to it. Because this happens immediately after the instantiation of a new client, there's no websocket protocol selected yet so this callback is issued only to protocol 0. Only wsi is defined, pointing to the new client, and the return value is ignored.

LWS_CALLBACK_FILTER_HTTP_CONNECTION

called when the request has been received and parsed from the client, but the response is not sent yet. Return non-zero to disallow the connection. user is a pointer to the connection user space allocation, in is the URI, eg, "/" In your handler you can use the public APIs lws_hdr_total_length / lws_hdr_copy to access all of the headers using the header enums lws_token_indexes from libwebsockets.h to check for and read the supported header presence and content before deciding to allow the http connection to proceed or to kill the connection.

LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION

called when the handshake has been received and parsed from the client, but the response is not sent yet. Return non-zero to disallow the connection. user is a pointer to the connection user space allocation, in is the requested protocol name In your handler you can use the public APIs lws_hdr_total_length / lws_hdr_copy to access all of the headers using the header enums lws_token_indexes from libwebsockets.h to check for and read the supported header presence and content before deciding to allow the handshake to proceed or to kill the connection.

LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS

if configured for including OpenSSL support, this callback allows your user code to perform extra SSL_CTX_load_verify_locations or similar calls to direct OpenSSL where to find certificates the client can use to confirm the remote server identity. user is the OpenSSL SSL_CTX*

LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS

if configured for including OpenSSL support, this callback allows your user code to load extra certifcates into the server which allow it to verify the validity of certificates returned by clients. user is the server's OpenSSL SSL_CTX*

LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY

if configured for including OpenSSL support but no private key file has been specified (ssl_private_key_filepath is NULL), this is called to allow the user to set the private key directly via libopenssl and perform further operations if required; this might be useful in situations where the private key is not directly accessible by the OS, for example if it is stored on a smartcard user is the server's OpenSSL SSL_CTX*

LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION

if the libwebsockets context was created with the option LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this callback is generated during OpenSSL verification of the cert sent from the client. It is sent to protocol[0] callback as no protocol has been negotiated on the connection yet. Notice that the libwebsockets context and wsi are both NULL during this callback. See

http

//www.openssl.org/docs/ssl/SSL_CTX_set_verify.html to understand more detail about the OpenSSL callback that generates this libwebsockets callback and the meanings of the arguments passed. In this callback, user is the x509_ctx, in is the ssl pointer and len is preverify_ok Notice that this callback maintains libwebsocket return conventions, return 0 to mean the cert is OK or 1 to fail it. This also means that if you don't handle this callback then the default callback action of returning 0 allows the client certificates.

LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER

this callback happens when a client handshake is being compiled. user is NULL, in is a char **, it's pointing to a char * which holds the next location in the header buffer where you can add headers, and len is the remaining space in the header buffer, which is typically some hundreds of bytes. So, to add a canned cookie, your handler code might look similar to:

char **p = (char **)in;

if (len < 100) return 1;

*p += sprintf(*p, "Cookie: a=b\x0d\x0a");

return 0;

Notice if you add anything, you just have to take care about the CRLF on the line you added. Obviously this callback is optional, if you don't handle it everything is fine.

Notice the callback is coming to protocols[0] all the time, because there is no specific protocol handshook yet.

LWS_CALLBACK_CONFIRM_EXTENSION_OKAY

When the server handshake code sees that it does support a requested extension, before accepting the extension by additing to the list sent back to the client it gives this callback just to check that it's okay to use that extension. It calls back to the requested protocol and with in being the extension name, len is 0 and user is valid. Note though at this time the ESTABLISHED callback hasn't happened yet so if you initialize user content there, user content during this callback might not be useful for anything. Notice this callback comes to protocols[0].

LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED

When a client connection is being prepared to start a handshake to a server, each supported extension is checked with protocols[0] callback with this reason, giving the user code a chance to suppress the claim to support that extension by returning non-zero. If unhandled, by default 0 will be returned and the extension support included in the header to the server. Notice this callback comes to protocols[0].

LWS_CALLBACK_PROTOCOL_INIT

One-time call per protocol so it can do initial setup / allocations etc

LWS_CALLBACK_PROTOCOL_DESTROY

One-time call per protocol indicating this protocol won't get used at all after this callback, the context is getting destroyed. Take the opportunity to deallocate everything that was allocated by the protocol.

LWS_CALLBACK_WSI_CREATE

outermost (earliest) wsi create notification

LWS_CALLBACK_WSI_DESTROY

outermost (latest) wsi destroy notification

The next five reasons are optional and only need taking care of if you will be integrating libwebsockets sockets into an external polling array.

For these calls, in points to a struct lws_pollargs that contains fd, events and prev_events members

LWS_CALLBACK_ADD_POLL_FD

libwebsocket deals with its poll loop internally, but in the case you are integrating with another server you will need to have libwebsocket sockets share a polling array with the other server. This and the other POLL_FD related callbacks let you put your specialized poll array interface code in the callback for protocol 0, the first protocol you support, usually the HTTP protocol in the serving case. This callback happens when a socket needs to be

added to the polling loop

in points to a struct lws_pollargs; the fd member of the struct is the file descriptor, and events contains the active events.

If you are using the internal polling loop (the "service" callback), you can just ignore these callbacks.

LWS_CALLBACK_DEL_POLL_FD

This callback happens when a socket descriptor needs to be removed from an external polling array. in is again the struct lws_pollargs containing the fd member to be removed. If you are using the internal polling loop, you can just ignore it.

LWS_CALLBACK_CHANGE_MODE_POLL_FD

This callback happens when libwebsockets wants to modify the events for a connectiion. in is the struct lws_pollargs with the fd to change. The new event mask is in events member and the old mask is in the prev_events member. If you are using the internal polling loop, you can just ignore it.

LWS_CALLBACK_UNLOCK_POLL

These allow the external poll changes driven by libwebsockets to participate in an external thread locking scheme around the changes, so the whole thing is threadsafe. These are called around three activities in the library, - inserting a new wsi in the wsi / fd table (len=1) - deleting a wsi from the wsi / fd table (len=1) - changing a wsi's POLLIN/OUT state (len=0) Locking and unlocking external synchronization objects when len == 1 allows external threads to be synchronized against wsi lifecycle changes if it acquires the same lock for the duration of wsi dereference from the other thread context.

LWS_CALLBACK_WS_PEER_INITIATED_CLOSE

The peer has sent an unsolicited Close WS packet. in and len are the optional close code (first 2 bytes, network order) and the optional additional information which is not defined in the standard, and may be a string or non-human- readble data. If you return 0 lws will echo the close and then close the connection. If you return nonzero lws will just close the connection.

lws_extension_callback_function - Hooks to allow extensions to operate

typedef int lws_extension_callback_function (struct lws_context * context, const struct lws_extension * ext, struct lws * wsi, enum lws_extension_callback_reasons reason, void * user, void * in, size_t len)

Arguments

context
Websockets context
ext
This extension
wsi
Opaque websocket instance pointer
reason
The reason for the call
user
Pointer to ptr to per-session user data allocated by library
in
Pointer used for some callback reasons
len
Length set for some callback reasons

Description

Each extension that is active on a particular connection receives callbacks during the connection lifetime to allow the extension to operate on websocket data and manage itself.

Libwebsockets takes care of allocating and freeing "user" memory for each active extension on each connection. That is what is pointed to by the user parameter.

LWS_EXT_CB_CONSTRUCT

called when the server has decided to select this extension from the list provided by the client, just before the server will send back the handshake accepting the connection with this extension active. This gives the extension a chance to initialize its connection context found in user.

LWS_EXT_CB_CLIENT_CONSTRUCT

same as LWS_EXT_CB_CONSTRUCT but called when client is instantiating this extension. Some extensions will work the same on client and server side and then you can just merge handlers for both CONSTRUCTS.

LWS_EXT_CB_DESTROY

called when the connection the extension was being used on is about to be closed and deallocated. It's the last chance for the extension to deallocate anything it has allocated in the user data (pointed to by user) before the user data is deleted. This same callback is used whether you are in client or server instantiation context.

LWS_EXT_CB_PACKET_RX_PREPARSE

when this extension was active on a connection, and a packet of data arrived at the connection, it is passed to this callback to give the extension a chance to change the data, eg, decompress it. user is pointing to the extension's private connection context data, in is pointing to an lws_tokens struct, it consists of a char * pointer called token, and an int called token_len. At entry, these are set to point to the received buffer and set to the content length. If the extension will grow the content, it should use a new buffer allocated in its private user context data and set the pointed-to lws_tokens members to point to its buffer.

LWS_EXT_CB_PACKET_TX_PRESEND

this works the same way as LWS_EXT_CB_PACKET_RX_PREPARSE above, except it gives the extension a chance to change websocket data just before it will be sent out. Using the same lws_token pointer scheme in in, the extension can change the buffer and the length to be transmitted how it likes. Again if it wants to grow the buffer safely, it should copy the data into its own buffer and set the lws_tokens token pointer to it.

struct lws_protocols - List of protocols and handlers server supports.

struct lws_protocols {
    const char * name;
    lws_callback_function * callback;
    size_t per_session_data_size;
    size_t rx_buffer_size;
    unsigned int id;
    void * user;
};

Members

name
Protocol name that must match the one given in the client Javascript new WebSocket(url, 'protocol') name.
callback
The service callback used for this protocol. It allows the service action for an entire protocol to be encapsulated in the protocol-specific callback
per_session_data_size
Each new connection using this protocol gets this much memory allocated on connection establishment and freed on connection takedown. A pointer to this per-connection allocation is passed into the callback in the 'user' parameter
rx_buffer_size
if you want atomic frames delivered to the callback, you should set this to the size of the biggest legal frame that you support. If the frame size is exceeded, there is no error, but the buffer will spill to the user callback when full, which you can detect by using lws_remaining_packet_payload. Notice that you just talk about frame size here, the LWS_PRE and post-padding are automatically also allocated on top.
id
ignored by lws, but useful to contain user information bound to the selected protocol. For example if this protocol was called "myprotocol-v2", you might set id to 2, and the user code that acts differently according to the version can do so by switch (wsi->protocol->id), user code might use some bits as capability flags based on selected protocol version, etc.
user
User provided context data at the protocol level. Accessible via lws_get_protocol(wsi)->user This should not be confused with wsi->user, it is not the same. The library completely ignores any value in here.

Description

This structure represents one protocol supported by the server. An array of these structures is passed to lws_create_server allows as many protocols as you like to be handled by one server.

The first protocol given has its callback used for user callbacks when there is no agreed protocol name, that's true during HTTP part of the

connection and true if the client did not send a Protocol

header.

struct lws_ext_options - Option arguments to the extension. These are used in the negotiation at ws upgrade time. The helper function lws_ext_parse_options() uses these to generate callbacks

struct lws_ext_options {
    const char * name;
    enum lws_ext_options_types type;
};

Members

name
Option name, eg, "server_no_context_takeover"
type
What kind of args the option can take

struct lws_extension - An extension we know how to cope with

struct lws_extension {
    const char * name;
    lws_extension_callback_function * callback;
    const char * client_offer;
};

Members

name
Formal extension name, eg, "permessage-deflate"
callback
Service callback
client_offer
String containing exts and options client offers

struct lws_context_creation_info - parameters to create context with

struct lws_context_creation_info {
    int port;
    const char * iface;
    const struct lws_protocols * protocols;
    const struct lws_extension * extensions;
    const struct lws_token_limits * token_limits;
    const char * ssl_cert_filepath;
    const char * ssl_private_key_filepath;
    const char * ssl_ca_filepath;
    const char * ssl_cipher_list;
    const char * http_proxy_address;
    unsigned int http_proxy_port;
    int gid;
    int uid;
    unsigned int options;
    void * user;
    int ka_time;
    int ka_probes;
    int ka_interval;
#ifdef LWS_OPENSSL_SUPPORT
    void * provided_client_ssl_ctx;
#else
    void * provided_client_ssl_ctx;
#endif
    short max_http_header_data;
    short max_http_header_pool;
    unsigned int count_threads;
    unsigned int fd_limit_per_thread;
};

Members

port
Port to listen on... you can use CONTEXT_PORT_NO_LISTEN to suppress listening on any port, that's what you want if you are not running a websocket server at all but just using it as a client
iface
NULL to bind the listen socket to all interfaces, or the interface name, eg, "eth2"
protocols
Array of structures listing supported protocols and a protocol- specific callback for each one. The list is ended with an entry that has a NULL callback pointer. It's not const because we write the owning_server member
extensions
NULL or array of lws_extension structs listing the extensions this context supports. If you configured with --without-extensions, you should give NULL here.
token_limits
NULL or struct lws_token_limits pointer which is initialized with a token length limit for each possible WSI_TOKEN_***
ssl_cert_filepath
If libwebsockets was compiled to use ssl, and you want to listen using SSL, set to the filepath to fetch the server cert from, otherwise NULL for unencrypted
ssl_private_key_filepath
filepath to private key if wanting SSL mode; if this is set to NULL but sll_cert_filepath is set, the OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called to allow setting of the private key directly via openSSL library calls
ssl_ca_filepath
CA certificate filepath or NULL
ssl_cipher_list
List of valid ciphers to use (eg, "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL" or you can leave it as NULL to get "DEFAULT"
http_proxy_address
If non-NULL, attempts to proxy via the given address. If proxy auth is required, use format "username:passwordserver:port"
http_proxy_port
If http_proxy_address was non-NULL, uses this port at the address
gid
group id to change to after setting listen socket, or -1.
uid
user id to change to after setting listen socket, or -1.
options
0, or LWS_SERVER_OPTION_... bitfields
user
optional user pointer that can be recovered via the context pointer using lws_context_user
ka_time
0 for no keepalive, otherwise apply this keepalive timeout to all libwebsocket sockets, client or server
ka_probes
if ka_time was nonzero, after the timeout expires how many times to try to get a response from the peer before giving up and killing the connection
ka_interval
if ka_time was nonzero, how long to wait before each ka_probes attempt
provided_client_ssl_ctx
If non-null, swap out libwebsockets ssl implementation for the one provided by provided_ssl_ctx. Libwebsockets no longer is responsible for freeing the context if this option is selected.
provided_client_ssl_ctx
If non-null, swap out libwebsockets ssl implementation for the one provided by provided_ssl_ctx. Libwebsockets no longer is responsible for freeing the context if this option is selected.
max_http_header_data
The max amount of header payload that can be handled in an http request (unrecognized header payload is dropped)
max_http_header_pool
The max number of connections with http headers that can be processed simultaneously (the corresponding memory is allocated for the lifetime of the context). If the pool is busy new incoming connections must wait for accept until one becomes free.
count_threads
how many contexts to create in an array, 0 = 1
fd_limit_per_thread
nonzero means restrict each service thread to this many fds, 0 means the default which is divide the process fd limit by the number of threads.

struct lws_client_connect_info - parameters to connect with when using lws_client_connect_via_info()

struct lws_client_connect_info {
    struct lws_context * context;
    const char * address;
    int port;
    int ssl_connection;
    const char * path;
    const char * host;
    const char * origin;
    const char * protocol;
    int ietf_version_or_minus_one;
    void * userdata;
    const struct lws_extension * client_exts;
};

Members

context
lws context to create connection in
address
remote address to connect to
port
remote port to connect to
ssl_connection
nonzero for ssl
path
uri path
host
content of host header
origin
content of origin header
protocol
list of ws protocols
ietf_version_or_minus_one
currently leave at 0 or -1
userdata
if non-NULL, use this as wsi user_data instead of malloc it
client_exts
array of extensions that may be used on connection

lws_close_reason - Set reason and aux data to send with Close packet If you are going to return nonzero from the callback requesting the connection to close, you can optionally call this to set the reason the peer will be told if possible.

LWS_EXTERN void lws_close_reason (struct lws * wsi, enum lws_close_status status, unsigned char * buf, size_t len)

Arguments

wsi
The websocket connection to set the close reason on
status
A valid close status from websocket standard
buf
NULL or buffer containing up to 124 bytes of auxiliary data
len
Length of data in buf to send