NaviServer Programmable Web Server

ns_conn(n)

NaviServer Built-in Commands – 5.0.0a


[ Main Table Of Contents | Table Of Contents | Keyword Index ]

Name

ns_conn - Query or modify state information about the current HTTP connection

Table Of Contents

Synopsis

Description

This command provides various subcommands that allow you to query and modify properties of the current HTTP connection.

COMMANDS

The subcommands of ns_conn (listed here in alphabetical order) include:

ns_conn acceptedcompression

Returns the compression formats accepted by the client, as indicated by the Accept-Encoding header.

ns_conn auth

Returns the content of the Authorization header as an ns_set. For Basic authentication, the ns_set includes reserved keys such as "Username" and "Password" (the values returned by ns_conn authuser and ns_conn authpassword). For Digest authentication, all header fields are included in the ns_set. For Bearer authentication, the ns_set contains the base64-encoded token. The returned ns_set can also be updated.

For other authorization schemes, the Authorization header is treated like any other request header. For example:

 set auth_header [ns_set get -nocase [ns_conn header] Authorization ""]
ns_conn authpassword

Returns the decoded user password extracted from the authorization data.

ns_conn authuser

Returns the decoded username extracted from the authorization data.

ns_conn channel

Returns the Tcl channel name for the current connection.

ns_conn clientdata ?value?

Queries or sets the client data associated with the current connection. This application-defined data may be shared across threads to help maintain context of running requests (e.g. to determine which user initiated a request).

ns_conn close

Closes the connection so that the script or ADP can perform time-consuming processing without delaying the client. When using ns_conn close in an ADP, ensure that streaming is enabled (e.g., via <SCRIPT RUNAT=SERVER STREAM=ON>) so that output is sent before the connection is terminated in this case.

ns_conn compress ?level?

Queries or sets the compression level for the current connection. Specifying a level of 0 disables compression.

ns_conn content ?-binary? ?offset? ?length?

Returns the body of the HTTP request. Optionally, you can specify an offset and length to extract a substring. If the -binary option is used, raw binary content is returned; otherwise, the content is converted to the connection’s encoding. Note that the response content may be delivered either as a string (via ns_conn content) or as a file (see ns_conn contentfile), depending on configration options.

ns_conn contentfile

Returns the name of the temporary file that holds the request content. Whether the received contemt is spooled to a file depends on the configuration settings.

ns_conn contentlength

Returns the length (in bytes) of the HTTP request body.

ns_conn contentsentlength ?bytes?

Queries or sets the number of bytes of content that have been sent.

ns_conn copy offset length channelId

Copies a specified number of bytes from the connection’s buffered data to a Tcl channel. The offset and length parameters define the starting position and the number of bytes to copy.

This command is intended for specialized use cases where the raw, unsent content is needed (available only if the data is not spooled to a file). For most applications, consider using ns_getcontent instead.

ns_conn currentaddr

Returns the local IP address (IPv4 or IPv6) of the current connection (i.e. the destination address of the socket).

ns_conn currentport

Returns the local port (i.e. the destination port of the socket) for the current connection.

ns_conn details

Returns a dict containing driver-specific details for the current connection. This dict typically includes the local IP address, its type (IPv4/IPv6), whether it is public or trusted, and whether the connection is proxied. For HTTPS connections, additional fields such as sslversion, cipher, and servername (as provided via SNI) are included.

ns_conn driver

Returns the name of the module (e.g., nssock or nsssl) acting as the communications driver for this connection.

ns_conn encoding ?encoding?

Queries or sets the encoding for the current connection. If an encoding is provided, it sets the encoding; otherwise, it returns the current encoding.

ns_conn fileheaders file

Returns an ns_set containing header information for the uploaded file specified by file (as returned by ns_conn files). If the file was uploaded using the HTML5 multiple attribute, a list of ns_sets is returned.

ns_conn filelength file

Returns the length (in bytes) of the uploaded file specified by file. For files uploaded using the HTML5 multiple attribute, a list of file lengths is returned.

ns_conn fileoffset file

Returns the byte offset of the uploaded file specified by file. For files uploaded using the HTML5 multiple attribute, a list of offsets is returned.

ns_conn files

Returns a list of files uploaded with the current form.

ns_conn flags

Returns the internal connection flags. Use with caution as these flags may change in future releases.

ns_conn form ?-fallbackcharset value?

Returns any submitted form data as an ns_set. The form data may be submitted via POST or included in the URL of a GET request.

The option `-fallbackcharset` specifies an alternative character set for decoding the form data if the default decoding results in invalid UTF-8. (This fallback charset can also be set globally via the formfallbackcharset configuration parameter.) For multipart form data file uploads, use ns_getform instead.

ns_conn fragment

Returns the fragment identifier of the request URL (the portion following the # character).

ns_conn headerlength

Returns the length of the HTTP request header. Combined with ns_conn contentlength, this can be used to determine the total uncompressed size of the request (excluding any chunked encoding overhead).

ns_conn headers

Returns all HTTP request header fields as an ns_set, where each key is a header field name. The case of the header names depends on the HeaderCase configuration parameter (default is Preserve).

ns_conn host ?default?

Returns the host part of the URL in the HTTP request line. This field is set only when NaviServer is used as a (forward) proxy server.

ns_conn id

Returns a unique identifier for the current connection.

ns_conn isconnected

Returns 1 if the current code is executing in a connection thread and the connection is open (allowing ns_conn calls), or 0 otherwise (e.g., when running in a schedule procedure).

ns_conn keepalive ?value?

Queries or sets the keepalive value for the current connection.

ns_conn location

Returns the location string for the virtual server handling the request in the format (":port" ist optional): protocol://hostname:port

The location is determined by:

  1. If ns_locationproc is configured, its result is returned.

  2. If virtual hosting is enabled and a valid "Host:" header is provided, its value is used.

  3. Otherwise, the virtual hosts mapping table (as defined in the ns/module/nssock/servers or ns/module/nsssl/servers section) is consulted.

  4. If no match is found and a connection is open, the current socket address is used.

  5. If all else fails, the location is derived from the driver's configuration.

ns_conn method

Returns the HTTP method (e.g., GET, POST).

ns_conn outputheaders

Returns an ns_set containing the HTTP response header fields that will be sent to the client. This ns_set can be modified to extend, update, or clear the response headers. For example:

 ns_set put [ns_conn outputheaders ] "Content-Disposition" "attachment;filename=export.xotcl"
ns_conn peeraddr ?-source configured|direct|forwarded?

Returns the client's IP address (the remote endpoint of the connection). For IPv4, the address is returned in dotted decimal notation; for IPv6, in colon-separated format. In reverse proxy mode, the IP is derived from the x-forwarded-for header. The optional -source parameter can force the return of the configured, direct, or forwarded IP address.

ns_conn peerport

Returns the connection pool associated with the current server.

ns_conn pool

Returns the currently associated connection pool of this request.

ns_conn port

Returns the port specified in the host header or the protocol's default port. In proxy mode, it returns the port specified in the HTTP request URL, or 0 for backwards compatibility.

ns_conn protocol

Returns the protocol used by the current connection. In (forward) proxy mode, this reflects the URL present in the request line.

ns_conn query

Returns the query parameters of the HTTP request (the portion after the ? and before the # in the URL).

ns_conn partialtimes

Returns detailed timing information for the current request as a dict. Keys include:

  • accepttime: Time between socket acceptance and queueing.

  • queuetime: Time spent in the queue.

  • filtertime: Time spent executing filters.

  • runtime: Total time elapsed during request processing.

ns_conn ratelimit ?limit?

Queries or sets the rate limit for the current connection in kilobytes per second (KB/s). A value of 0 indicates no limit. Default limits can be set at the connection pool level (parameter ratelimit) or at the driver level (writerratelimit). Rate limiting is enforced only on connections using writer threads.

ns_conn request

Returns the HTTP request line as received from the client (e.g., "GET / HTTP/1.1").

ns_conn server

Returns the name of the server handling the request.

ns_conn sock

Returns the socket identifier (integer file descriptor) for the current connection.

ns_conn start

Returns the time when the connection request started in "sec:usec" (ns_time) format.

ns_conn status ?status-code?

Queries or sets the HTTP status code for the current connection.

ns_conn target

Returns the URI target from the start line of the HTTP request (this may include query variables).

ns_conn timeout

Returns an absolute time value beyond which the connection will not wait for resources (e.g., condition variables).

ns_conn url

Returns the URL of the HTTP request. This is the portion of the URL following the hostname (e.g., "/index.adp").

 if { [string match /page/* [ns_conn url]] } {
  ns_returnnotfound
 }
ns_conn urlc

Returns the number of elements in the URL, as determined by splitting on the / character.

ns_conn urldict

Returns the current request URL as a Tcl dictionary. The dictionary separates the URL into its constituent components (such as protocol, host, port, path, query, fragment, etc.).

This structured representation allows you to modify specific parts of the URL programmatically (for example, removing the query or adding a fragment) and then rebuild the complete URL using ns_joinurl. This is especially useful for dynamic web applications that require URL manipulation based on request context or custom routing logic.

 # Original URL: /foo/bar?x=1
 set urldict [ns_conn urldict]
 # Example result: {path foo tail bar query x=1}
 
 dict unset urldict query
 dict set urldict fragment sect2
 set url [ns_joinurl $urldict]
 # Resulting URL: /foo/bar#sect2
ns_conn urlencoding ?encoding?

Queries or sets the URL encoding for the current connection. If an encoding value is provided, it sets the URL encoding; otherwise, it returns the current encoding.

ns_conn urlv ?idx?

Returns a list of the URL components (delimited by `/'). If idx is provided, returns the nth element of the URL vector.

ns_conn version

Returns the HTTP version of the current request (typically 1.0 or 1.1).

ns_conn zipaccepted

Returns 0 or 1 depending on whether the client accepts a zip-encoded response.

See Also

ns_adp, ns_getcontent, ns_getform, ns_locationproc, ns_queryget, ns_set, ns_time

Keywords

IPv4, IPv6, SNI, connection, gzip, reverse proxy, server built-in, virtual host