eXept Software AG Logo

Smalltalk/X Webserver

Documentation of class 'HTTPServer':

Home

Documentation
www.exept.de
Everywhere
for:
[back]

Class: HTTPServer


Inheritance:

   Object
   |
   +--HTTPServer
      |
      +--FCGIServer

Package:
stx:goodies/webServer
Category:
Net-Communication-HTTP-Server
Version:
rev: 1.702 date: 2024/03/26 13:06:31
user: cg
file: HTTPServer.st directory: goodies/webServer
module: stx stc-classLibrary: webServer

Description:


Communicate with me via your favourite webBrowser ...
... see examples, howToStart and howToConfigure for setup information.

This class combines the functionalities of our own HTTPServer
(which itself was a merge of the WebServer and our existing file-access
 HTTPServer), and the new PWS (pluggable web server).

By setting up the ActionTable, FileRoot and HomeURL as required,
all of the above Web services (i.e. plugged, dynamic objects and file access)
are implemented here in a backward compatible fashion.

  Features:
HTTPServer does file caching - you may want to configure the number of
cached documents and the maxSize for caching by changing the maxCacheSize
and maxCacheDocumentSize variables.
The server also cares for open connections, timeouts, authentication etc.
Can also operate as slave under a master-apache via FCGI

  Operation Overview:
For each incoming request, a HTTPConnection is created (or reused) and
this is asked to handle the request (see #serve).
HTTPConnection creates a HTTPRequest object, which is asked to generate a reply (#generateReply).
For reply, the requests asks me (the httpServer) back, to translate the requests URL
into an instance of HTTPService and a relative path (see #serviceAndLinkNameFromPath:into:).
The mapping of relative path to services is done via the linkResolver dictionary, into which
services can be registered/unregistered either programmatically or via the settings dialog
(#resolveServiceForPath: and #serviceForLink:ifAbsent:).

Finally, the service gets the request (#process:) and has to fill out the HTTPResponse object
which is passed along with the request (either directly or indirectly).
Eventually, when all intermediate methods return to the #generateReply of the HTTPRequest,
any collected html code is sent back to the original socket.

[History:]
    our own HTTPServer              - did file access only.
                                    - supports caching, keep-Alive, connections.
    merged WebServer                - added LinkedObjects
    improvements                    - added temporary links
    merged PWS                      - added an actionTable

[InstanceVariables:]
    port                            the port, on which this server is listening
    serverSocket                    the socket, on which this server is listening
    serverStatusHolder              a valueHolder holding this servers status (for monitoring)
    serverProcess                   process serving the connections
    serviceList                     list of registered services
    servicesSema                    accessLock
    linkResolver                    maps URLS
    linkHooks                       mappings for individual URLS
    temporaryLinks                  maps objects to temporary names
                                    These links are removed after being
                                    used - i.e. they are one-shot links
    temporaryObjectNames            maps temporary names to objects
                                    These links are removed after being
                                    used - i.e. they are one-shot links
    temporaryObjectNamesSema        accessLock
    temporaryLinksSema              accessLock
    temporaryLinkExpirationTime     the default expiration time for a temporary image
                                    sending with the response so the client can cache this links
                                    server removes that temporary links after that time
    homeURL                         the default URL (default is /Home)
    notFoundURL                     the url invoked if the service for the requested url is not found (default is nil)
    maintenanceMode                 boolean; if true, only local requests or requests includes the authorization for
                                    the ServerMaintenanceService are served
    backupJobs                      blocks to evaluate hourly
    maxNumberOfConnections          the max. number of simultaneous open connections.
    maxNumberOfKeepAliveConnections the max. number of kept connections.
                                    If more, the longest unused connection is closed.
                                    If 0, no connections are kept alive.
                                    (read about the WAIT_FIN TCP problem on
                                     why you may want to do this)
    keptConnectionsSema             accessLock
    keptConnections                 kept, still alive connections
    defaultFile                     obsolete
    verbose                         enables some debug messages (e.g. write header information to the Transcript) (default false)
    verboseData                     enables debug dump of incoming/outgoing data (default false)
    verboseErrors                   enables debug messages for error handling (default false)
    verboseTimeConsumtion           enables request time consumtion printouts to Transcript (default false)
    debugErrors                     enables debugging; if false, errors are caught and no debugger
                                    is opened (instead, the error is reported to the HTTP-requestor).
                                    If true, a regular debugger is opened.(default false)
    logFile                         a log file (will be in apache format soon)
    logToFile                       enables logging ti file
    logStream                       log stream to logFile
    loggingSema                     accessLock for logFile
    soapEnabled                     soap hook
    soapActionHandler
    realmUsersMap                   stores the user:password codes for all the authorization methods for each realm
    allowedAuthMethods              by now DIGEST and BASIC are supported
    settingsFilename                default filename were the server settings can be written to
    allowedHosts                    if non-nil, only those hosts are allowed (list of friends)
    forbiddenHosts                  if non-nil, those hosts are forbidden from connecting (list of intruders)

[ClassVariables:]
    CrLfCrLf
    RunningServers  OrderedCollection
                                    list of all running http server instances

copyright

COPYRIGHT (c) 2003 by eXept Software AG All Rights Reserved This software is furnished under a license and may be used only in accordance with the terms of that license and with the inclusion of the above copyright notice. This software may not be provided or otherwise made available to, or used by, any other person. No title to or ownership of the software is hereby transferred.

benchmarking

Please validate these numbers on your machine - the numbers below might be outdated by the time you read this ... Throughput testing - see how many URL-not found requests are handled per second ... try port 80 (default apache1.3 server) vs. port 8080 (a Zope HTTPServer). vs. port 8081 (ST/X HTTPServer). [exBegin] |startTime deltaTime n host port| port := Dialog request:'port' initialAnswer:'80'. port size==0 ifTrue:[^ self]. port := Integer readFrom:port. host := Dialog request:'host' initialAnswer:(OperatingSystem getHostName). host size==0 ifTrue:[^ self]. 5 timesRepeat:[ startTime := Timestamp now. n := 0. [(deltaTime := Timestamp now - startTime) < 10] whileTrue:[ HTTPInterface get:'/foo' fromHost:host port:port. n := n + 1 ]. Transcript showCR:((n / deltaTime) asFixedPoint:1) printString , ' requests per second'. ] [exEnd] On our linux box: Operating system: [ SuSE Linux 7.1 (i386) ] Host: [ Kernel: 2.2.18 (i686) ] Apache/1.3.14 166..170 Zope 50.. 59 ST/X HTTPServer 57.. 62 throughput testing - see how many real requests (a small html-file) are handled per second ... (here, the apache default index.html was used) try port 80 (default apache1.3 server) vs. port 8080 (our ST/X HTTPServer). [exBegin] |startTime deltaTime n host port| port := Dialog request:'port' initialAnswer:'80'. port size==0 ifTrue:[^ self]. port := Integer readFrom:port. host := Dialog request:'host' initialAnswer:(OperatingSystem getHostName). host size==0 ifTrue:[^ self]. 5 timesRepeat:[ startTime := Timestamp now. n := 0. [(deltaTime := Timestamp now - startTime) < 10] whileTrue:[ HTTPInterface get:'/' fromHost:host port:port. n := n + 1 ]. Transcript showCR:((n / deltaTime) asFixedPoint:1) printString , ' requests per second'. ] [exEnd] On our linux box: Apache 1.3 85..107 / 87..131 (keepAlive) ST/X HTTPServer 71.. 80 / 104..112 (keepAlive) throughput testing - see how many generated page requests are handled per second ... this can only be done with the ST/X server. [exBegin] |startTime deltaTime n host port| port := Dialog request:'port' initialAnswer:'8080'. port size==0 ifTrue:[^ self]. port := Integer readFrom:port. host := Dialog request:'host' initialAnswer:(OperatingSystem getHostName). host size==0 ifTrue:[^ self]. 5 timesRepeat:[ startTime := Timestamp now. n := 0. [(deltaTime := Timestamp now - startTime) < 10] whileTrue:[ HTTPInterface get:'/' fromHost:host port:port. n := n + 1 ]. Transcript showCR:((n / deltaTime) asFixedPoint:1) printString , ' requests per second'. ] [exEnd] On our linux box: ST/X HTTPServer 69 / 115 (keepAlive)

howToConfigure

Open the new Settings Dialog from Launcher System Settings and switch to the communication/HTTPServer section. If you want to have a standalone webServer application, type 'make' in the 'projects/webServer' directory. This compiles a sandalone executable containing this class and requried support stuff (actuall, it is the server which also runs our 'www.exept.de' homepage. After the build, type 'webServer --help' to see the options for startup. The best way is to setup the server(s) in the 'Settings Dialog' from a running smalltalk, and save the settings to a file (which is XML). Then give this file's name to the standAlone server app (using the '--useFile' argument option). In 'projects/webServer', you'll also find a sample startup script (shell-script) named 'stxWebServer'. You may want to copy this script-file to your '/usr/sbin' or '/usr/local/bin' directory of your linux distribution, change the parameters as required. This script can also be placed into /etc/rc.d. You cn then easily start/stop the httpServer via 'start'/'stop' command line arguments. Passwords: services may be (individually) protected by realms (userName/password pairs). If no password is given, the service is free for everyone; except for the maintenance service, which requires a password for connections from remote machines. allowedHosts / forbiddenHosts: server-instance specific; these allow fine-grain control over which hosts may access the server. If allowedHosts is non-nil, only hosts listed there may connect (for example, for local services on a separate port). If forbiddenHosts is non-nil, hosts listed there may never connect (for example, to lock out known intruders) temporarilyForbiddenHosts lists all hosts, which have sent a bad request recently; these are given another chance after a while (attackers will end up there).

howToStart

Unix users: Notice, although the standard http port is 80, this is a system port and requires that ST/X is running either as privileged user or setuid. Since we cannot guarantee against any security holes, we do NOT recommend doing this; instead, use some non-privileged port (say 8080) and add a link from your regular homePage to 'http://yourHost:8080/...'. Another alternative is to run the ST/X webserver as FCGI slave of an apache or other master server. This also allows for simple file servives to be served by the possibly faster master. Finally, this is also the way to go if you need load sharing etc.

todo

TODO: - change Demos::WebHomePageForSTX homePage: from <TABLE> to <DIV> - allow and disallow peerNames per service - support sessions, using cookies, unique urls and parameters. - separate users from realms to allow the assignment of same user to multiple realms - if service url not found take the servers not found url use own redirection dictionary IDEAS: - provide a global contents-cache (in Server); services should be able to specify that their generated contents should be cached there (in reply-send-code); for incoming requests, contentsCache is checked first; needs per-content-URL expiration time.

Class protocol:

accessing
o  defaultForbiddenPeers
well known fraud sites - blocked from our house.

o  defaultForbiddenUserAgents
well known fraud sites - blocked from our house.

o  forbiddenPeers
return the default list of peers from known fraud sites.
cuge is here by default - they generate random ratings...

o  forbiddenPeers: aSequenceableCollection
set the default list of peers from known fraud sites.
These are blocked from the server

o  forbiddenUserAgents
return the default list of agents from known fraud sites.
cuge is here by default - they generate random ratings...

o  forbiddenUserAgents: aSequenceableCollection
set the default list of agents from known fraud sites.
These are blocked from access

o  terminationRequest

class initialization
o  installInLauncher
self installInLauncher

o  loadRequiredClasses

o  removeFromLauncher
remove myself from the launcher's settings dialog

Usage example(s):

     self removeFromLauncher

configuring - setup
o  addToBackupJob: aJob
add a job (block) to be evaluated hourly by any server

constants
o  crlf

o  crlfcrlf

o  httpVersion

defaults
o  availableAuthenticationClasses

o  availableAuthenticationMethods

o  defaultAccessLogger
^ FullAccessLogger new.

o  defaultAllowRobots
this is a default setting for new servers

o  defaultAllowRobots: aBoolean
this is a default setting for new servers

o  defaultAllowedAuthenticationMethods
answer the alloed authenication methods.
We exclude Basic here, because it is insecure

o  defaultFile

o  defaultInactiveConnectionTimeout
seconds

o  defaultLogEnabled

o  defaultLogEnabled: aBoolean

o  defaultMaxNumberOfConnections
windows is not really useful as a server system

o  defaultMaxNumberOfKeepAliveConnections
windows is not really useful as a server system

o  defaultPort
return my default port number.
Use some high number here, since low ones (i.e. 80) are
reserved to super users. To use one below 1024, run ST/X as
setuid root.

o  defaultServerReplyPresenterClass

o  defaultServiceList
self defaultServiceList

o  homeURL
return the defaultHomeURL - that's the URL used when an empty URL is entered
in the browser.

o  inactiveConnectionTimeout

** This is an obsolete interface - do not use it (it may vanish in future versions) **

o  logFile
default log file name server instance add '_portNumber' before suffix point

o  notFoundURL
return the default notFoundURL - that's the URL used when no service for the request is available.

o  port
for protocol compatibility with instances (to allow for common settings dialog)

o  realmUsersMap

o  settingsFilename

o  temporaryLockoutTime
seconds

defaults-caching
o  maxCacheSize
files to cache

defaults-debugging
o  debugErrors

o  verbose
the default for every new server instance

o  verboseData
the default for every new server instance

o  verboseErrors
the default for every new server instance

defaults-soap
o  defaultSoapEnabled

o  loadSoapPackage
self loadSoapPackage

o  soapEnabled

** This is an obsolete interface - do not use it (it may vanish in future versions) **

html composition
o  withSpecialHTMLCharactersEscaped: aStringOrCharacter
replace ampersand, less and greater by html-character escapes

Usage example(s):

     self withSpecialHTMLCharactersEscaped:'<>#&'
     self withSpecialHTMLCharactersEscaped:$<
     self withSpecialHTMLCharactersEscaped:$#

instance creation
o  new
(comment from inherited method)
return an instance of myself without indexed variables

o  newServerOnPort: aPortNr
Creates a server on aPortNr and return the server instance.
This does NOT serve requests (i.e. it is not started)

o  newServerWithDefaultServiceListOn: port

o  newServerWithServiceList: aServiceList onPort: port

o  runningServerOnPort: aPort
return the server which is serving aPort or nil, if there is none.
Use this, if you want to avoid startup of new servers (i.e. to query if there is a server).
To really start servers, use #serverOnPort:

Usage example(s):

     HTTPServer runningServerOnPort:8080
     HTTPServer runningServerOnPort:8081

o  runningServers
return a collection of running servers

o  serverOnPort: aPortNr
if already running, return an existing server which serves aPortNr.
If not, start one and return it.
Use runningServerOnPort:aPortNr, if you want to avoid startup of new servers
(i.e. to query if there is a server)

Usage example(s):

     self serverOnPort:8081
     self serverOnPort:8080
     self serverOnPort:9000
     self serverOnPort:9090

o  soapEnabledServerOnPort: portNr
get an HTTPServer with SOAP enabled;
However, its serviceHandler does not yet have any services defined
(see Example services for more).

o  startServer
Start a server on the default port (8080) and return the server instance.
This starts a new process, which executes autonomously

Usage example(s):

     self startServer

o  startServerOnPort: aPortNr
Start a server on aPortNr and return the server instance.
This starts a new process, which executes autonomously.
See also #serverOnPort:aPortNr, which first looks, if there is already a server
running for that port.

Usage example(s):

     self startServerOnPort:8081
     self startServerOnPort:8080
     self startServerOnPort:9000
     self startServerOnPort:9090

obsolete
o  checkSwikiVersion
This is Squeak-Swiki 2.2.
Make sure that the Server:swiki folder is the version for 2.2.

Usage example(s):

     self checkSwikiVersion

o  disableMySwiki

o  rollForwardFrom: fileName
Roll the image forward using the given file.

o  setupMySwiki

private
o  addServer: aServer

o  removeServer: aServer

queries
o  defaultServer

o  isRunning
return true, if a server is running on defaultPort

o  isRunningOnPort: aPort
return true, if a server is running on aPort

queries-service
o  makeValidLinkName: eachLinkName
self makeValidLinkName:'//'
self makeValidLinkName:'//foo'
self makeValidLinkName:'/foo/'
self makeValidLinkName:'foo/'

read/write settings
o  instanceSettingsList
answer a list of instance variables to be saved as server settings

o  serverFromSettingsFile: aFilename
create a new HTTP server from the setting stored in aFilename

o  serverFromSettingsStream: aStream
create a new HTTP server from the setting stored in aStream

serving
o  stopAllServers
Stop all running http servers.
This is done kind of softly, allowing the current request to be finished.

Usage example(s):

     HTTPServer stopAllServers

o  stopServer
Stop the default server.
This is done kind of softly, allowing the current request to be finished.

Usage example(s):

     HTTPServer stopServer

o  stopServerOnPort: aPort
Stop the server for aPort.
This is done kind of softly, allowing the current request to be finished.

Usage example(s):

     HTTPServer stopServerOnPort:(self defaultPort)

o  terminateAllServers
Stop all running http servers.
This is done kind of softly, allowing the current request to be finished.

Usage example(s):

     HTTPServer terminateAllServers

serving-helpers
o  gifImageDataForImage: img
given an image, generate GIF-data (should now no longer be used - use png)

o  imageDataForImage: img type: type
given an image, generate image-data as determined by type (image/gif, image/png, etc.)

o  pngImageDataForImage: img
given an image, generate PNG-data

signal access
o  abortRequestProcessing


Instance protocol:

accessing
o  accessLogger

o  accessLogger: something

o  addListeningAddress: aSocketAddress
add aSocketAddress to the list of addresses, that this server is listening.
You have to restart the server, if it is already running.

Usage example(s):

      self new addListeningAddress:(IPSocketAddress anyHost port:6666).

o  allowedHosts

o  closeConnectionAfterError
Answer true, if the connection should be closed when the request resulted in
an error. To avoid getting hogged down by a bad guy, limit his access speed,
by closing the connection.

o  inactiveConnectionTimeout
seconds

o  inactiveConnectionTimeout: something
seconds

o  listeningAddresses
HTTPServer allInstancesDo:[:httpServer |
Transcript printCR:httpServer.
httpServer listeningAddresses do:[:each |
Transcript printCR:(each port)
]
]

o  listeningAddresses: something

o  maxNumberOfConnections

o  maxNumberOfConnections: aNumber

o  maxNumberOfKeepAliveConnections

o  maxNumberOfKeepAliveConnections: aNumber

o  port
answer the (IPV4-)port, that we are or will be listening on.
This is not very well defined and kept only for backward compatibility

o  port: aPort
backward compatibility.
Set the IPV4-port of the server

o  realmUsersMap

o  realmUsersMap: aDict

o  serverHostName
Some pretty printed information about where we are running

o  serverHostName: aString
Set the name of the server - only for informational purposes.
If mothing is set, the host name is used.

o  serverProcess

o  serverProcess: something

o  serverReplyPresenter
the default server reply presenter
an instance for this class is created for every new request
this valid until the service is changing the presenter
if the service replyPrsenterClass is nil this replyPresenter is kept
during running through the service

o  serverReplyPresenter: something

o  serverSocket

o  serverStatusHolder
return a valueHolder holding the servers status (as a symbol)

o  serviceList

o  serviceList: aServiceSet

o  servicesSema

o  settingsFilename

o  settingsFilename: something

o  soapEnabled
mhmh: do we still need soapEnabled (isn't it tracking soapActionHandler's nilness)?

o  soapEnabled: aBoolean
mhmh: do we still need soapEnabled (isn't it tracking soapActionHandler's nilness)?

o  startupTime

o  tentativeObjectService
answer an tentative object service.
For backward compatibility: if there is none, create it on the fly

o  tlsCertificateStore

o  tlsCertificateStore: something

accessing-debugging & logging
o  addAlias: anAlias for: anUrl

o  debugErrors

o  debugErrors: aBoolean
if true, errors will trigger a debugger

o  logFile
return the name of the log file

o  logFile: something
the name of the log file

o  removeAliasFor: anUrl

o  standaloneMode
answer true, if we are running in standalone mode.
In this mode, even breakpoint exceptions are ignored

o  verbose
return the verbose flag - if set, trace messages are sent to the transcript.
The flag is initialized from the corresponding class variable

o  verbose: aBoolean
set/clear the verbose flag - if set, trace messages are sent to the transcript.
The flag is initialized from the corresponding class variable

o  verboseData
return the verboseData flag - if set, request data is dumped to the transcript.
The flag is initialized from the corresponding class variable

o  verboseData: aBoolean
set/clear the verboseData flag - if set, request data is dumped to the transcript.
The flag is initialized from the corresponding class variable

o  verboseErrors
return the verboseErrors flag - if set, errornous requests are logged to the transcript.
The flag is initialized from the corresponding class variable

o  verboseErrors: aBoolean
set/clear the verboseErrors flag - if set, errornous requests are logged to the transcript.
The flag is initialized from the corresponding class variable

o  verboseShort
if true,only a short verbose message is generated

o  verboseTiming
this flag enables some timing statistics

o  verboseTiming: aBoolean
this flag enables some timing statistics - the default is false

accessing-http session
o  httpSessionAt: anId

o  httpSessionAt: anId ifAbsent: aBlock

o  httpSessionAt: anId put: anHTTPSession

o  httpSessionRemove: aString

o  removeTimedOutSessions
Associated with the minute job. Removes sessions that have become invalid

<return: self>

authentication-users
o  addRealm: aRealm
add a realm to the list of known realms

o  addUser: aUserName password: aPassword toRealm: aRealm overWrite: overWrite
this message is sent if a user is added to a realm or changed.
If overWrite is true, the data of an already existing user is overwritten.
Notice that this adds the user to all existing services.
If individual services should be changed,
add the user there (i.e. service addUser:password:toRealm:)

o  allRealms
answer a collection of realm names known

o  allowedAuthMethods
answer a collection of allowed authenticatation method names

o  allowedAuthMethods: something

o  allowedAuthenticationClasses
answer a collection of authenticators that may be used to authenticate

o  authenticationDataForUser: userName inRealm: aRealm
answer the authentication data of a user belonging to aRealm

o  canAuthenticate: aRequest with: authenticator
is it allowed to authenticate using authenticator?

o  canAuthenticateWith: authenticator
is it allowed to authenticate using authenticator?

** This is an obsolete interface - do not use it (it may vanish in future versions) **

o  forbiddenUserAgents

o  hasUser: aUserName forRealm: aRealm
is aUserName known in aRealm?

o  removeRealm: aRealm
remove aRealm completely

o  removeUser: aUser fromRealm: aRealm
remove a user from a realm

o  supportsRealm: aRealm
by default, answer true, if users are registered for a realm.
Redefine this, if you use your own user database.

o  usersForRealm: aRealm
answer the users belonging to aRealm

authorization-hosts
o  addToAllowedHosts: aHostAddr
add aHostAddr to the list of addresses, that are allowed to connect to the server.
If there is a single entry in allowedHosts, only connections are permitted from peers that are listed
in allowedHosts.
Must be a hostAddress (i.e. 4-byte ByteArrays)

o  addToForbiddenHosts: aHostAddr
add aHostAddr to the list of addresses, that are never allowed to connect to the server.
Must be a hostAddress (i.e. 4-byte ByteArrays)

o  allowAllHosts

o  allowRobots
this is a general setting for this server (all services);
if false, robots are completely disallowed;
if true, individual services may or may not disallow individual pathes

o  allowRobots: aBoolean
this is a general setting for this server (all services);
if false, robots are completely disallowed;
if true, individual services may or may not disallow individual pathes

Usage example(s):

     self new allowRobots                      => true
     (self new allowRobots:false) allowRobots  => false

o  forbiddenHosts
return the list of addresses, that are never allowed to connect to the server.
Contains hostAddresses (i.e. 4-byte ByteArrays)

o  forbiddenHosts: aCollection
set the list of addresses, that are never allowed to connect to the server.
Must contain hostAddresses (i.e. 4-byte ByteArrays)

o  isConnectionAllowed: socket
return true, if the connection given by socket is allowed.
Check:
1. if allowedHosts contains entries, it MUST contain the peers address
2. if forbiddenHosts MUST NOT contain the peers address
3. if temporaryForbiddenHosts MUST NOT contain the peers address.
Entries in this collection will be removed by the server after some time (temporary not ok).

o  removeFromAllowedHosts: aHostAddr
must check again because of possible raise

o  removeFromForbiddenHosts: aHostAddr
must check again because of possible raise

o  temporaryForbid: aHostAddr
add aHostAddr to the list of addresses,
that are not allowed to connect to the server for some time.
This is used to protect against DOS attacks.
Must be a hostAddress (i.e. 4-byte ByteArrays)

change & update
o  update: something with: aParameter from: changedObject
(comment from inherited method)
dependent is notified of some change -
Default is to try update:with:

configuring
o  addToBackupJob: aJob
add a job (block) to be evaluated hourly by this server

o  clearBackupJobs
Clear the backupJobs list.

o  setupServer
this is called immediately before the server is started

default-urls
o  homeURL
return the homeURL - that's the URL used when an empty URL is entered
in the browser.

o  homeURL: anURL
set the homeURL - that's the URL used when an empty URL is entered
in the browser.

o  notFoundURL
return the notFoundURL - that's the URL used when no service for the request was found

o  notFoundURL: anURL
set the notFoundURL - that's the URL used when no service for the request was found

o  rootUri
return the uri, that represents our root

initialization
o  initialize
resolves links to services/rewritten links

links-action-soap
o  disableSoap
mhmh: do we still need soapEnabled (isn't it tracking soapActionHandler's nilness)?

o  setupSoap

o  setupSoapWithHandler: aSoapServiceHandler
mhmh: do we still need soapEnabled (isn't it tracking soapActionHandler's nilness)?

o  soapActionHandler

o  soapServiceHandler

logging
o  closeLogFile
must check again because of possible raise

o  createLogFileFor: filenameOrStream

o  log: aString
write aString to our logfile

o  logCommented: aString
write a comment line to our log

o  logEnabled
answer true, if logging is enabled

o  logEnabled: aBoolean
if aBoolean == true, enable logging;
if false, disable logging

o  newLogFilenameFor: filename
creates a backup filename string from a given filename

Usage example(s):

    HTTPServer new newLogFilenameFor:'/tmp/web_8080.log'

o  openNewLogFile
backup existing logfiles and open a filestream on the logfile name

o  verboseLog: aString
do verbose logging of aString (to Logger)

obsolete
o  logToFile: something
for backward compatibility

** This is an obsolete interface - do not use it (it may vanish in future versions) **

o  startServer

** This is an obsolete interface - do not use it (it may vanish in future versions) **

o  startServerOnPort: aPortNr

** This is an obsolete interface - do not use it (it may vanish in future versions) **

o  stopServer

** This is an obsolete interface - do not use it (it may vanish in future versions) **

o  verboseTimeConsumtion
marked as obsolete by exept MBP at 24-03-2022

** This is an obsolete interface - do not use it (it may vanish in future versions) **

obsolete-pwsswiki
o  setupAuthorizedSwiki
setup the authorized swiki service:
authorizedSwiki
In this swiki, you must be authorized to modify pages,
but anyone can read them.
In addition, to the secureSwiki, pages may include
embedded smalltalk (so be careful, to not let bad guys crash your system)
The initial user/password is 'test'/'secure'

Usage example(s):

     self setupAuthorizedSwiki

o  setupAuthorizedSwikiNamed: swikiName
setup the authorized swiki service:
authorizedSwiki
In this swiki, you must be authorized to modify pages,
but anyone can read them.
In addition, to the secureSwiki, pages may include
embedded smalltalk (so be careful, to not let bad guys crash your system)
The initial user/password is 'secure'/'secure'

o  setupMySwiki
setup the unauthorized swiki service:
mySwiki
In this swiki, anyone can read and modify pages.

Usage example(s):

     self setupMySwiki

o  setupSecureSwiki
setup the secure swiki service:
secureSwiki
In this swiki, you must be authorized to modify pages,
but anyone can read them.
The initial user/password is 'test'/'test'

o  setupSecureSwikiNamed: aSecureSwikiName
setup the secure swiki service:
secureSwiki
In this swiki, you must be authorized to modify pages,
but anyone can read them.
The initial user/password is 'test'/'test'

o  setupSwikiNamed: swikiName
setup or restore a swiki service named swikiName.
In this swiki, anyone can read and modify pages.

printing
o  printOn: aStream
(comment from inherited method)
append a user printed representation of the receiver to aStream.
The format is suitable for a human - not meant to be read back.

The default here is to output the receiver's class name.
BUT: this method is heavily redefined for objects which
can print prettier.

queries
o  connectionClass

o  doNightlySnapShot

o  hasSoapEnabled

o  overallNumberOfRequests
returns the overall number of served requests (both failed and successful)

o  overallNumberOfServedConnections
returns the overall number of served incoming connections

o  parametersPrintStrings

o  serverName
answer the server's name (for messages)

o  serverReplyPresenterFor: aRequest

regular jobs
o  doBackupJobs
This method is invoked every hour and is supposed to perform
required backup jobs. Applications may register for a backupaction to
be invoked hourly via #addToBackupJob:aJobBlock.
This is just a wrapper so we don't have to restart the server loop,
when we add/remove jobs.

o  doBackupJobs: jobCollection
This method is invoked every hour and is supposed to perform
required backup jobs. Applications may register for a backupaction to
be invoked hourly via #addToBackupJob:aJobBlock.
This is just a wrapper so we don't have to restart the server loop,
when we add/remove jobs.

o  doHourlyJobs
This method is invoked every hour and is supposed to perform cleanup actions.
Currently, it starts a garbage collect.
This is just a wrapper so we don't have to restart the server loop,
when we add/remove jobs.

o  doNightlyJobs
This method is invoked every midnight and is supposed to perform cleanup actions.
Currently, it purges old graphic and temporary links and performs a
compressing garbage collect.
This is just a wrapper so we don't have to restart the server loop,
when we add/remove jobs.

service-queries
o  allServiceLinkNames

o  fileServices

o  hasServiceForLink: aLinkName
Return true, if there is a service registered for aLinkName

o  hasServiceForServiceClass: aServiceClass
return true, if there is a link for a aServiceClass

o  linkResolver

o  resolveServiceForPath: pathArg
get serviceLinkName and service instance for aPath.
If there is a path transation active,
the third component contains the new relative path

o  serviceAndLinkNameFromPath: aPath into: aRequest
get serviceLinkName and service instance for aPath,
and set them in aRequest.
Also set the path relative to the service link name.
Called for incoming requests to determine, which service is to handle it.

o  serviceForLink: aLinkName
Return the service registered for aLinkName, or nil if there is none.

o  serviceForLink: aLinkName ifAbsent: exceptionBlock
Return the service registered for aString, or the value from exceptionBlock if there is none.

o  servicesForServiceClass: aServiceClass
return the collection of instances, for which the class is aServiceClass.
empty collection if there is none.

service-registration
o  addFileServiceWithRootLinkName: aLinkName class: aFileServiceClass rootDirectory: aRootDirectory defaultFileName: aDefaultFilename
create, register and return an instance of aFileServiceClass to serve files from aRootDirectory under the link aLinkName.
For nonexisting files, return aDefaultFilename

o  addFileServiceWithRootLinkName: aLinkName rootDirectory: aRootDirectory defaultFileName: aDefaultFilename
create, register and return a file service to serve files from aRootDirectory under the link aLinkName.
For nonexisting files, return aDefaultFilename

o  addLink: aLinkName toService: aService
add a link for aService

o  addRewriteLink: aLinkName to: newLinkName
all requests for aLinkName will be internally forwarded as newLinkName.
This allows for links like /images/foo to be mapped to a tentative image.

o  addServiceToServiceList: aService
add aService to the list of services.
If aService redefines link names,
unregister the old service using the same link names

o  changeLinksForService: aService
aService may have changed link names.
Update them

o  linkService: aService
register the links from aService

o  registerTentativeObjectService: aService
if no tentativeObjectService has been registered as default until now,
register aService

o  rewriteURLFor: anURL
anURL = '/foo' ifTrue:[

o  setupServices: serviceList
setup defaults service links

o  unRegisterAllServices
is this a consistency check, or why not unRegister aService right away?

o  unRegisterServiceForLink: aLinkName

o  unRegisterTentativeObjectService: aService
unregister aService, if is has been registered as default tentativeObjectService

o  unlinkService: aService
unlink aService.

serving
o  closeServerSocket

o  createServerProcess
Initialize the server to be run on the set port.
This creates and returns a new process, which can be started with #resume

o  loop
This is the inner HTTP server loop.
The logging argument may be a stream or a fileName or nil.
Periodically flush the logfile.
Invoke hourly and nightly jobs.

Usage example(s):

end of loop

o  openServerSocket
already open

o  restartServer
restart the server process

o  serve
This is the outer HTTP server loop.

o  serverSocketClosed
someone else closed my server socket!

o  start
Start the server on the default or before already set port.
This starts a new process, which executes autonomously

Usage example(s):

     self startServerOnPort:8080
     self startServerOnPort:9000
     self startServerOnPort:9090

o  startOnPort: aPortNr
Start the server on aPortNr.
This starts a new process (if not already running), which executes autonomously

o  stop
tell the server to stop; notice that there is a chance, that the server
continues operation for some time.
It will finish any ongoing requests, however not accepting any new ones.
If the request(s) take too long to execute, they will be aborted
(i.e. sooner or later the server will be definitely stopped)

o  terminateServer
hard terminate the server - pending requests will not be finished

serving-helpers
o  addConnection: aConnection
remember aConnection

o  closeOldestConnection
close the oldest connection we currently hold

o  countRequest
statistics only

o  doMinuteByMinuteActionAt: now
minutely action

o  removeConnection: aConnection
remove aConnection from the list of remebered connections

o  removeUnusedConnections
remove all connections that are inactive for some time (inactiveConnectionTimeout)

o  shutdownOldConnections
shut down (immediately) old connections, as we have too many already.
Here, shutDown the one with the longest already processing request
(could be a blocking one...)

serving-serverState
o  inMaintenanceMode
return true, iff in mainenance mode.
In this mode, no files are served (only Server.control-requests are served)

o  isInCollectGarbageStatus

o  isInQuitStatus

o  isInRestartServerStatus

o  isInSnapshotStatus

o  isRunning
true if serverProcess is up.
(but could still be in startUp or shutDown procedure

o  isServing
true if serverProcess is up and socket-connections are served

o  maintenanceMode: aBoolean

o  serverStatus
return the serverStatus as a symbol

o  waitForServerStatus: conditionBlock withTimeout: secondsOrNil
wait until server status changed, so that conditionBlock evaluates to true.
Raise TimeoutError on timeout, return self otherwise

o  waitUntilServing
wait until I am serving requests

o  waitUntilServingWithTimeout: secondsOrNil
wait until I am serving requests.
Raise TimeoutError on timeout, return self otherwise

o  waitUntilStopped
wait until I am no longer serving requests

o  waitUntilStoppedWithTimeout: secondsOrNil
wait until I am no longer serving requests.
Raise TimeoutError on timeout, return self otherwise

serving-serverState-private
o  changeServerStatusTo: newStatus

o  changeServerStatusToBackingUpLogFile

o  changeServerStatusToCollectGarbage

o  changeServerStatusToError

o  changeServerStatusToNotRunning

o  changeServerStatusToQuit

o  changeServerStatusToRestartServer

o  changeServerStatusToServing

o  changeServerStatusToSnapshot

settings persistency
o  elementDescriptorFor: anAspect
support for persistency:
answer the elements to be made persistent with an ObjectCoder

o  fetchServerSettingsFrom: fromHttpServer
fetch all settings as in fromHttpServer

o  hasSameSettingsLike: anHTTPServer

o  hasSettingsFile

o  putSettingsOn: aStream

o  readSettingsFromFile: aFilename

o  saveSettingsToFile: aFilename

o  settingsString
HTTPServer new settingsString

temporary link-add/remove
o  clearTemporaryLinkIds
Clear all temp linkIds

o  expireOldTemporaryLinksFor: now
expire old temporary links

o  graphicLinkIdFor: anImage
Return the linkId for a temporary graphic link.

o  graphicLinkIdFor: anImage expirationTimeDelta: anExpirationTimeDelta
Return the linkId for a temporary graphic link.

o  removeTemporaryLinkInfoForUrlPath: urlPath
remove the temporary link if it is available

o  temporaryLinkBaseName: aBaseName for: aValue type: aType expirationTimeDelta: anExpirationTimeDelta
Return the linkId for a temporary object with an lifeTime of anExpirationTimeDelta
of anExpirationTimeDelta in seconds. aValue may be a block (or other #value-responding)
thing; its value is computed when a client asks for the link

o  temporaryLinkPathFor: anObject type: aType
Return the linkId for a temporary object.

o  temporaryLinkPathFor: aValue type: aType expirationTimeDelta: anExpirationTimeDelta
Return the linkId for a temporary object with an lifeTime of anExpirationTimeDelta
of anExpirationTimeDelta in seconds. aValue may be a block (or other #value-responding)
thing; its value is computed when a client asks for the link

o  temporaryLinkPathForProcessBlock: aProcessBlock

o  temporaryLinkPathForProcessBlock: aProcessBlock removeLinkAfterUse: removeLinkAfterUse
returns a linkId, which ends up in the request processing block (the argument).
see example below.

this will be performed somehow later, not directly after a full request,
enhance the timeout.

the link will be removed after perform

Usage example(s):

        |actionUrl|

        actionUrl := httpServer tentativeObjectService
            temporaryLinkPathForProcessBlock:[:request |
                request postDataFieldsAt:'uploadedFile'
            ].

        builder
            form; target:'iframe'; method:'post'; action:actionUrl; enctype:'multipart/form-data';
                input; name:'uploadedFile'; type:'file';
            formEnd.

temporary link-queries
o  hasExpiredForLinkObject: aLinkObject time: aTime
return false if aLinkObject is valid (exists and has not expired). Otherwise return true

o  hasExpiredForUrlPath: urlPath time: aTime
return false if urlPath is valid (exists and has not expired). Otherwise return true

** This is an obsolete interface - do not use it (it may vanish in future versions) **

o  hasTemporaryLinkForLinkObject: aLinkObject

o  hasTemporaryLinkForUrlPath: aPath

o  temporaryLinkExpirationTime
return the time (in seconds) which controls how long temporary links should be kept

o  temporaryLinkExpirationTime: something
set the time (in seconds) which controls how long temporary links should be kept

o  temporaryLinkInfoForLinkObject: aLinkObject
retrieve a temporary objects linkInfo - or nil

o  temporaryLinkInfoForUrlPath: urlPath
retrieve a temporary object's linkInfo - or nil


Private classes:

    AbortRequestProcessing
    TerminationRequest

Examples:


Notice: st/x must run as setuid or rott in order to allow serving port 80 ... default setup & go:
 HTTPServer startServerOnPort:8080
one more than one port:
 HTTPServer startServerOnPort:8081
 HTTPServer startServerOnPort:9090
stop:
 HTTPServer stopAllServer
go:
 HTTPServer startServerOnPort:8080.
 HTTPServer startServerOnPort:80.
Use SSL/TLS:
 (HTTPServer newServerOnPort:4443)
    tlsCertificateStore:(SSL::SSLCertificateStore new
                         loadRSACertificateFile: '/etc/letsencrypt/live/exept.de-0001/cert.pem' 
                         privateKeyFile: '/etc/letsencrypt/live/exept.de-0001/privkey.pem' password:nil);
    start.


ST/X 7.7.0.0; WebServer 1.702 at 20f6060372b9.unknown:8081; Thu, 21 Nov 2024 12:44:37 GMT